diff --git a/.github/workflows/build-docs.yml b/.github/workflows/build-docs.yml index 4ff5e26cb..262c7fa5c 100644 --- a/.github/workflows/build-docs.yml +++ b/.github/workflows/build-docs.yml @@ -108,9 +108,9 @@ jobs: 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/** # https://github.com/marketplace/actions/alls-green#why diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index b8dbb7dc5..dd54608d9 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -19,18 +19,16 @@ jobs: run: | rm -rf ./site mkdir ./site - - name: Download Artifact Docs - id: download - uses: dawidd6/action-download-artifact@v3.1.4 + - 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.FASTAPI_PREVIEW_DOCS_DOWNLOAD_ARTIFACTS }} + 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 with: diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index a5cbf6da4..e7c69befc 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: @@ -21,19 +28,14 @@ jobs: # Issue ref: https://github.com/actions/setup-python/issues/436 # cache: "pip" # cache-dependency-path: pyproject.toml - - uses: actions/cache@v4 - id: cache - with: - path: ${{ env.pythonLocation }} - key: ${{ runner.os }}-python-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml') }}-publish - name: Install build dependencies 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.14 - with: - password: ${{ secrets.PYPI_API_TOKEN }} - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} diff --git a/.github/workflows/smokeshow.yml b/.github/workflows/smokeshow.yml index c4043cc6a..ffc9c5f8a 100644 --- a/.github/workflows/smokeshow.yml +++ b/.github/workflows/smokeshow.yml @@ -24,13 +24,14 @@ jobs: - run: pip install smokeshow - - uses: dawidd6/action-download-artifact@v3.1.4 + - uses: actions/download-artifact@v4 with: - github_token: ${{ secrets.FASTAPI_SMOKESHOW_DOWNLOAD_ARTIFACTS }} - workflow: test.yml - commit: ${{ github.event.workflow_run.head_sha }} + name: coverage-html + path: htmlcov + github-token: ${{ secrets.FASTAPI_SMOKESHOW_DOWNLOAD_ARTIFACTS }} + run-id: ${{ github.event.workflow_run.id }} - - run: smokeshow upload coverage-html + - run: smokeshow upload htmlcov env: SMOKESHOW_GITHUB_STATUS_DESCRIPTION: Coverage {coverage-percentage} SMOKESHOW_GITHUB_COVERAGE_THRESHOLD: 100 diff --git a/.github/workflows/test-redistribute.yml b/.github/workflows/test-redistribute.yml index c2e05013b..0cc5f866e 100644 --- a/.github/workflows/test-redistribute.yml +++ b/.github/workflows/test-redistribute.yml @@ -12,6 +12,11 @@ on: jobs: test-redistribute: runs-on: ubuntu-latest + strategy: + matrix: + package: + - fastapi + - fastapi-slim steps: - name: Dump GitHub context env: @@ -22,12 +27,11 @@ jobs: uses: actions/setup-python@v5 with: python-version: "3.10" - # Issue ref: https://github.com/actions/setup-python/issues/436 - # cache: "pip" - # cache-dependency-path: pyproject.toml - 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: | @@ -35,16 +39,18 @@ jobs: tar xvf fastapi*.tar.gz - name: Install test dependencies run: | - cd dist/fastapi-*/ + cd dist/fastapi*/ pip install -r requirements-tests.txt + env: + TIANGOLO_BUILD_PACKAGE: ${{ matrix.package }} - name: Run source distribution tests run: | - cd dist/fastapi-*/ + cd dist/fastapi*/ bash scripts/test.sh - name: Build wheel distribution run: | cd dist - pip wheel --no-deps fastapi-*.tar.gz + pip wheel --no-deps fastapi*.tar.gz - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index fe1e419d6..a33b6a68a 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -87,9 +87,9 @@ 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 coverage-combine: @@ -108,17 +108,18 @@ jobs: # cache: "pip" # cache-dependency-path: pyproject.toml - name: Get coverage files - uses: actions/download-artifact@v3 + uses: actions/download-artifact@v4 with: - name: coverage + pattern: coverage-* path: coverage + merge-multiple: true - run: pip install coverage[toml] - run: ls -la coverage - run: coverage combine coverage - run: coverage report - run: coverage html --show-contexts --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 diff --git a/README.md b/README.md index bcb18ac66..2bcccbe3b 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ --- -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: @@ -53,14 +53,17 @@ The key features are: - + - + + + - + + @@ -122,8 +125,6 @@ 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. @@ -141,18 +142,6 @@ $ pip install fastapi -You will also need an ASGI server, for production such as Uvicorn or Hypercorn. - -
- -```console -$ pip install "uvicorn[standard]" - ----> 100% -``` - -
- ## Example ### Create it @@ -213,11 +202,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. ``` @@ -225,13 +227,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.
@@ -304,7 +306,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 @@ -338,7 +340,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`: @@ -448,7 +450,7 @@ Independent TechEmpower benchmarks show **FastAPI** applications running under U To understand more about it, see the section Benchmarks. -## Optional Dependencies +## Dependencies Used by Pydantic: @@ -461,16 +463,36 @@ 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). Used by FastAPI / Starlette: * uvicorn - for the server that loads and serves your application. +* `fastapi-cli` - to provide the `fastapi` command. + +When you install `fastapi` it comes these standard dependencies. + +Additional optional dependencies: + * orjson - Required if you want to use `ORJSONResponse`. * ujson - Required if you want to use `UJSONResponse`. -You can install all of these with `pip install "fastapi[all]"`. +## `fastapi-slim` + +If you don't want the extra standard optional dependencies, install `fastapi-slim` instead. + +When you install with: + +```bash +pip install fastapi +``` + +...it includes the same code and dependencies as: + +```bash +pip install "fastapi-slim[standard]" +``` + +The standard extra dependencies are the ones mentioned above. ## License diff --git a/docs/az/docs/index.md b/docs/az/docs/index.md index 33bcc1556..430295d91 100644 --- a/docs/az/docs/index.md +++ b/docs/az/docs/index.md @@ -27,7 +27,7 @@ --- -FastAPI Python 3.8+ 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. +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: @@ -115,8 +115,6 @@ FastAPI Python 3.8+ ilə API yaratmaq üçün standart Python Starlette. @@ -330,7 +328,7 @@ 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 3.8+**. +Sadəcə standart **Python**. Məsələn, `int` üçün: diff --git a/docs/bn/docs/index.md b/docs/bn/docs/index.md index bbc3e9a3a..3105e69c8 100644 --- a/docs/bn/docs/index.md +++ b/docs/bn/docs/index.md @@ -126,7 +126,7 @@ $ pip install fastapi -আপনার একটি ASGI সার্ভারেরও প্রয়োজন হবে, প্রোডাকশনের জন্য Uvicorn অথবা Hypercorn. +আপনার একটি ASGI সার্ভারেরও প্রয়োজন হবে, প্রোডাকশনের জন্য Uvicorn অথবা Hypercorn.
diff --git a/docs/de/docs/advanced/generate-clients.md b/docs/de/docs/advanced/generate-clients.md index 7d1d69353..d69437954 100644 --- a/docs/de/docs/advanced/generate-clients.md +++ b/docs/de/docs/advanced/generate-clients.md @@ -20,7 +20,7 @@ Einige von diesen ✨ [**sponsern FastAPI**](../help-fastapi.md#den-autor-sponse 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. +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. 🤓 diff --git a/docs/de/docs/deployment/manually.md b/docs/de/docs/deployment/manually.md index c8e348aa1..ddc31dc5b 100644 --- a/docs/de/docs/deployment/manually.md +++ b/docs/de/docs/deployment/manually.md @@ -5,7 +5,7 @@ Das Wichtigste, was Sie zum Ausführen einer **FastAPI**-Anwendung auf einer ent Es gibt 3 Hauptalternativen: * Uvicorn: ein hochperformanter ASGI-Server. -* Hypercorn: ein ASGI-Server, der unter anderem mit HTTP/2 und Trio kompatibel ist. +* 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 @@ -43,7 +43,7 @@ Sie können einen ASGI-kompatiblen Server installieren mit: === "Hypercorn" - * Hypercorn, ein ASGI-Server, der auch mit HTTP/2 kompatibel ist. + * Hypercorn, ein ASGI-Server, der auch mit HTTP/2 kompatibel ist.
diff --git a/docs/de/docs/how-to/custom-docs-ui-assets.md b/docs/de/docs/how-to/custom-docs-ui-assets.md index 991eaf269..a9271b3f3 100644 --- a/docs/de/docs/how-to/custom-docs-ui-assets.md +++ b/docs/de/docs/how-to/custom-docs-ui-assets.md @@ -96,8 +96,8 @@ Sie können wahrscheinlich mit der rechten Maustaste auf jeden Link klicken und **Swagger UI** verwendet folgende Dateien: -* `swagger-ui-bundle.js` -* `swagger-ui.css` +* `swagger-ui-bundle.js` +* `swagger-ui.css` Und **ReDoc** verwendet diese Datei: diff --git a/docs/de/docs/how-to/graphql.md b/docs/de/docs/how-to/graphql.md index 9b03e8e05..b8e0bdddd 100644 --- a/docs/de/docs/how-to/graphql.md +++ b/docs/de/docs/how-to/graphql.md @@ -18,7 +18,7 @@ Hier sind einige der **GraphQL**-Bibliotheken, welche **ASGI** unterstützen. Di * Strawberry 🍓 * Mit Dokumentation für FastAPI * Ariadne - * Mit Dokumentation für Starlette (welche auch für FastAPI gilt) + * Mit Dokumentation für FastAPI * Tartiflette * Mit Tartiflette ASGI, für ASGI-Integration * Graphene diff --git a/docs/de/docs/index.md b/docs/de/docs/index.md index cf5a2b2d6..ccc50fd62 100644 --- a/docs/de/docs/index.md +++ b/docs/de/docs/index.md @@ -36,7 +36,7 @@ hide: --- -FastAPI ist ein modernes, schnelles (hoch performantes) Webframework zur Erstellung von APIs mit Python 3.8+ auf Basis von Standard-Python-Typhinweisen. +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: @@ -125,8 +125,6 @@ Wenn Sie eine Starlette für die Webanteile. @@ -144,7 +142,7 @@ $ pip install fastapi
-Sie benötigen außerdem einen ASGI-Server. Für die Produktumgebung beispielsweise Uvicorn oder Hypercorn. +Sie benötigen außerdem einen ASGI-Server. Für die Produktumgebung beispielsweise Uvicorn oder Hypercorn.
@@ -340,7 +338,7 @@ 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 3.8+**. +Nur Standard-**Python+**. Zum Beispiel für ein `int`: @@ -462,7 +460,7 @@ 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. +* 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. diff --git a/docs/em/docs/deployment/manually.md b/docs/em/docs/deployment/manually.md index f27b423e2..43cbc9409 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️⃣ & 🎻 👪 🎏 ⚒. * 👸: 🔫 💽 🏗 ✳ 📻. ## 💽 🎰 & 💽 📋 @@ -43,7 +43,7 @@ === "Hypercorn" - * Hypercorn, 🔫 💽 🔗 ⏮️ 🇺🇸🔍/2️⃣. + * Hypercorn, 🔫 💽 🔗 ⏮️ 🇺🇸🔍/2️⃣.
diff --git a/docs/em/docs/how-to/graphql.md b/docs/em/docs/how-to/graphql.md index 8509643ce..686a77949 100644 --- a/docs/em/docs/how-to/graphql.md +++ b/docs/em/docs/how-to/graphql.md @@ -18,7 +18,7 @@ * 🍓 👶 * ⏮️ 🩺 FastAPI * 👸 - * ⏮️ 🩺 💃 (👈 ✔ FastAPI) + * ⏮️ 🩺 FastAPI * 🍟 * ⏮️ 🍟 🔫 🚚 🔫 🛠️ * diff --git a/docs/em/docs/tutorial/sql-databases.md b/docs/em/docs/tutorial/sql-databases.md index 4c8740984..5a5227352 100644 --- a/docs/em/docs/tutorial/sql-databases.md +++ b/docs/em/docs/tutorial/sql-databases.md @@ -501,7 +501,7 @@ current_user.items "🛠️" ⚒ 🔁 💪 🕐❔ 👆 🔀 📊 👆 🇸🇲 🏷, 🚮 🆕 🔢, ♒️. 🔁 👈 🔀 💽, 🚮 🆕 🏓, 🆕 🏓, ♒️. -👆 💪 🔎 🖼 ⚗ FastAPI 🏗 📄 ⚪️➡️ [🏗 ⚡ - 📄](../project-generation.md){.internal-link target=_blank}. 🎯 `alembic` 📁 ℹ 📟. +👆 💪 🔎 🖼 ⚗ FastAPI 🏗 📄 ⚪️➡️ [🏗 ⚡ - 📄](../project-generation.md){.internal-link target=_blank}. 🎯 `alembic` 📁 ℹ 📟. ### ✍ 🔗 diff --git a/docs/en/data/external_links.yml b/docs/en/data/external_links.yml index 827581de5..15f6169ee 100644 --- a/docs/en/data/external_links.yml +++ b/docs/en/data/external_links.yml @@ -1,5 +1,8 @@ Articles: English: + - 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 @@ -24,7 +27,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 @@ -257,6 +260,10 @@ 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 German: - author: Marcel Sander (actidoo) author_link: https://www.actidoo.com @@ -347,6 +354,11 @@ 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 diff --git a/docs/en/data/github_sponsors.yml b/docs/en/data/github_sponsors.yml index 385bcb498..5f0be61c2 100644 --- a/docs/en/data/github_sponsors.yml +++ b/docs/en/data/github_sponsors.yml @@ -17,6 +17,9 @@ sponsors: - login: cryptapi avatarUrl: https://avatars.githubusercontent.com/u/44925437?u=61369138589bc7fee6c417f3fbd50fbd38286cc4&v=4 url: https://github.com/cryptapi + - login: Kong + avatarUrl: https://avatars.githubusercontent.com/u/962416?v=4 + url: https://github.com/Kong - login: codacy avatarUrl: https://avatars.githubusercontent.com/u/1834093?v=4 url: https://github.com/codacy @@ -48,7 +51,7 @@ sponsors: 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: BoostryJP avatarUrl: https://avatars.githubusercontent.com/u/57932412?v=4 @@ -56,10 +59,7 @@ sponsors: - login: acsone avatarUrl: https://avatars.githubusercontent.com/u/7601056?v=4 url: https://github.com/acsone -- - login: owlur - avatarUrl: https://avatars.githubusercontent.com/u/20010787?v=4 - url: https://github.com/owlur - - login: Trivie +- - login: Trivie avatarUrl: https://avatars.githubusercontent.com/u/8161763?v=4 url: https://github.com/Trivie - - login: americanair @@ -71,9 +71,6 @@ sponsors: - login: mainframeindustries avatarUrl: https://avatars.githubusercontent.com/u/55092103?v=4 url: https://github.com/mainframeindustries - - login: AccentDesign - avatarUrl: https://avatars.githubusercontent.com/u/2429332?v=4 - url: https://github.com/AccentDesign - login: mangualero avatarUrl: https://avatars.githubusercontent.com/u/3422968?u=c59272d7b5a912d6126fd6c6f17db71e20f506eb&v=4 url: https://github.com/mangualero @@ -89,7 +86,10 @@ sponsors: - login: povilasb avatarUrl: https://avatars.githubusercontent.com/u/1213442?u=b11f58ed6ceea6e8297c9b310030478ebdac894d&v=4 url: https://github.com/povilasb -- - login: upciti +- - login: jhundman + avatarUrl: https://avatars.githubusercontent.com/u/24263908?v=4 + url: https://github.com/jhundman + - login: upciti avatarUrl: https://avatars.githubusercontent.com/u/43346262?v=4 url: https://github.com/upciti - - login: samuelcolvin @@ -98,15 +98,15 @@ sponsors: - login: Kludex avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex - - login: koconder - avatarUrl: https://avatars.githubusercontent.com/u/25068?u=582657b23622aaa3dfe68bd028a780f272f456fa&v=4 - url: https://github.com/koconder - 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=9ae4b158c0d2cb29ebd46df6b6edb7de08a67566&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 @@ -119,6 +119,9 @@ sponsors: - login: ProteinQure avatarUrl: https://avatars.githubusercontent.com/u/33707203?v=4 url: https://github.com/ProteinQure + - login: catherinenelson1 + avatarUrl: https://avatars.githubusercontent.com/u/11951946?u=e714b957185b8cf3d301cced7fc3ad2842122c6a&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 @@ -146,18 +149,6 @@ sponsors: - 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: 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=60bdf46240cff8fca482ff0fc07d963fd5e1a27c&v=4 url: https://github.com/anthonycepeda @@ -170,15 +161,18 @@ sponsors: - login: DelfinaCare avatarUrl: https://avatars.githubusercontent.com/u/83734439?v=4 url: https://github.com/DelfinaCare + - 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: apitally avatarUrl: https://avatars.githubusercontent.com/u/138365043?v=4 url: https://github.com/apitally - login: logic-automation avatarUrl: https://avatars.githubusercontent.com/u/144732884?v=4 url: https://github.com/logic-automation - - 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 @@ -188,12 +182,15 @@ sponsors: - login: dudikbender avatarUrl: https://avatars.githubusercontent.com/u/53487583?u=3a57542938ebfd57579a0111db2b297e606d9681&v=4 url: https://github.com/dudikbender + - login: prodhype + avatarUrl: https://avatars.githubusercontent.com/u/60444672?u=3f278cff25ea37ead487d7861d4a984795de819e&v=4 + url: https://github.com/prodhype + - login: patsatsia + avatarUrl: https://avatars.githubusercontent.com/u/61111267?u=3271b85f7a37b479c8d0ae0a235182e83c166edf&v=4 + url: https://github.com/patsatsia - 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: dodo5522 avatarUrl: https://avatars.githubusercontent.com/u/1362607?u=9bf1e0e520cccc547c046610c468ce6115bbcf9f&v=4 url: https://github.com/dodo5522 @@ -212,12 +209,27 @@ sponsors: - login: dblackrun avatarUrl: https://avatars.githubusercontent.com/u/3528486?v=4 url: https://github.com/dblackrun + - login: zsinx6 + avatarUrl: https://avatars.githubusercontent.com/u/3532625?u=ba75a5dc744d1116ccfeaaf30d41cb2fe81fe8dd&v=4 + url: https://github.com/zsinx6 + - login: kennywakeland + avatarUrl: https://avatars.githubusercontent.com/u/3631417?u=7c8f743f1ae325dfadea7c62bbf1abd6a824fc55&v=4 + url: https://github.com/kennywakeland + - login: simw + avatarUrl: https://avatars.githubusercontent.com/u/6322526?v=4 + url: https://github.com/simw + - login: koconder + avatarUrl: https://avatars.githubusercontent.com/u/25068?u=582657b23622aaa3dfe68bd028a780f272f456fa&v=4 + url: https://github.com/koconder - 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: 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 @@ -248,15 +260,6 @@ sponsors: - 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=e714b957185b8cf3d301cced7fc3ad2842122c6a&v=4 - url: https://github.com/catherinenelson1 - - login: zsinx6 - avatarUrl: https://avatars.githubusercontent.com/u/3532625?u=ba75a5dc744d1116ccfeaaf30d41cb2fe81fe8dd&v=4 - url: https://github.com/zsinx6 - - login: kennywakeland - avatarUrl: https://avatars.githubusercontent.com/u/3631417?u=7c8f743f1ae325dfadea7c62bbf1abd6a824fc55&v=4 - url: https://github.com/kennywakeland - login: aacayaco avatarUrl: https://avatars.githubusercontent.com/u/3634801?u=eaadda178c964178fcb64886f6c732172c8f8219&v=4 url: https://github.com/aacayaco @@ -266,6 +269,9 @@ sponsors: - login: jgreys avatarUrl: https://avatars.githubusercontent.com/u/4136890?u=096820d1ef89877d57d0f68e669ead8b0fde84df&v=4 url: https://github.com/jgreys + - 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 @@ -284,15 +290,15 @@ sponsors: - login: FernandoCelmer avatarUrl: https://avatars.githubusercontent.com/u/6262214?u=d29fff3fd862fda4ca752079f13f32e84c762ea4&v=4 url: https://github.com/FernandoCelmer - - login: simw - avatarUrl: https://avatars.githubusercontent.com/u/6322526?v=4 - url: https://github.com/simw - - 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: 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 @@ -305,15 +311,15 @@ sponsors: - 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: bnkc - avatarUrl: https://avatars.githubusercontent.com/u/34930566?u=fa1dc8db3e920cf5c5636b97180a6f811fa01aaf&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/34930566?u=db5e6f4f87836cad26c2aa90ce390ce49041c5a9&v=4 url: https://github.com/bnkc + - login: DevOpsKev + avatarUrl: https://avatars.githubusercontent.com/u/36336550?u=6ccd5978fdaab06f37e22f2a14a7439341df7f67&v=4 + url: https://github.com/DevOpsKev - login: petercool avatarUrl: https://avatars.githubusercontent.com/u/37613029?u=81c525232bb35780945a68e88afd96bb2cdad9c4&v=4 url: https://github.com/petercool @@ -332,33 +338,33 @@ sponsors: - login: jangia avatarUrl: https://avatars.githubusercontent.com/u/17927101?u=9261b9bb0c3e3bb1ecba43e8915dc58d8c9a077e&v=4 url: https://github.com/jangia + - login: jackleeio + avatarUrl: https://avatars.githubusercontent.com/u/20477587?u=c5184dab6d021733d10c8f975b20e391856303d6&v=4 + url: https://github.com/jackleeio - login: shuheng-liu avatarUrl: https://avatars.githubusercontent.com/u/22414322?u=813c45f30786c6b511b21a661def025d8f7b609e&v=4 url: https://github.com/shuheng-liu - login: pers0n4 avatarUrl: https://avatars.githubusercontent.com/u/24864600?u=f211a13a7b572cbbd7779b9c8d8cb428cc7ba07e&v=4 url: https://github.com/pers0n4 - - login: SebTota - avatarUrl: https://avatars.githubusercontent.com/u/25122511?v=4 - url: https://github.com/SebTota + - login: curegit + avatarUrl: https://avatars.githubusercontent.com/u/37978051?u=1733c322079118c0cdc573c03d92813f50a9faec&v=4 + url: https://github.com/curegit - login: fernandosmither - avatarUrl: https://avatars.githubusercontent.com/u/66154723?u=a76a037b5d674938a75d2cff862fb6dfd63ec214&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/66154723?u=f79753eb207d01cca5bbb91ac62db6123e7622d1&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: 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: jugeeem - avatarUrl: https://avatars.githubusercontent.com/u/116043716?u=ae590d79c38ac79c91b9c5caa6887d061e865a3d&v=4 - url: https://github.com/jugeeem - login: tahmarrrr23 avatarUrl: https://avatars.githubusercontent.com/u/138208610?u=465a46b0ff72a74252d3e3a71ac7d2f1919cda28&v=4 url: https://github.com/tahmarrrr23 - - login: curegit - avatarUrl: https://avatars.githubusercontent.com/u/37978051?u=1733c322079118c0cdc573c03d92813f50a9faec&v=4 - url: https://github.com/curegit + - login: zk-Call + avatarUrl: https://avatars.githubusercontent.com/u/147117264?v=4 + url: https://github.com/zk-Call - login: kristiangronberg avatarUrl: https://avatars.githubusercontent.com/u/42678548?v=4 url: https://github.com/kristiangronberg @@ -374,12 +380,21 @@ sponsors: - login: ArtyomVancyan avatarUrl: https://avatars.githubusercontent.com/u/44609997?v=4 url: https://github.com/ArtyomVancyan + - login: harol97 + avatarUrl: https://avatars.githubusercontent.com/u/49042862?u=2b18e115ab73f5f09a280be2850f93c58a12e3d2&v=4 + url: https://github.com/harol97 - login: hgalytoby - avatarUrl: https://avatars.githubusercontent.com/u/50397689?u=f4888c2c54929bd86eed0d3971d09fcb306e5088&v=4 + 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: Joaopcamposs + avatarUrl: https://avatars.githubusercontent.com/u/57376574?u=699d5ba5ee66af1d089df6b5e532b97169e73650&v=4 + url: https://github.com/Joaopcamposs + - login: browniebroke + avatarUrl: https://avatars.githubusercontent.com/u/861044?u=5abfca5588f3e906b31583d7ee62f6de4b68aa24&v=4 + url: https://github.com/browniebroke - login: miguelgr avatarUrl: https://avatars.githubusercontent.com/u/1484589?u=54556072b8136efa12ae3b6902032ea2a39ace4b&v=4 url: https://github.com/miguelgr @@ -395,9 +410,6 @@ sponsors: - 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?u=dfe51d2080fbd3fee81e05911cd8d50da9dcc709&v=4 - url: https://github.com/anthonycorletti - login: ddanier avatarUrl: https://avatars.githubusercontent.com/u/113563?u=ed1dc79de72f93bd78581f88ebc6952b62f472da&v=4 url: https://github.com/ddanier @@ -422,9 +434,6 @@ sponsors: - login: tochikuji avatarUrl: https://avatars.githubusercontent.com/u/851759?v=4 url: https://github.com/tochikuji - - login: browniebroke - avatarUrl: https://avatars.githubusercontent.com/u/861044?u=5abfca5588f3e906b31583d7ee62f6de4b68aa24&v=4 - url: https://github.com/browniebroke - login: KentShikama avatarUrl: https://avatars.githubusercontent.com/u/6329898?u=8b236810db9b96333230430837e1f021f9246da1&v=4 url: https://github.com/KentShikama @@ -444,7 +453,7 @@ sponsors: 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=2ef1ede118a72c170805f50b9ad07341fd16a354&v=4 url: https://github.com/xncbf - login: DMantis avatarUrl: https://avatars.githubusercontent.com/u/9536869?v=4 @@ -467,9 +476,15 @@ sponsors: - login: dzoladz avatarUrl: https://avatars.githubusercontent.com/u/10561752?u=5ee314d54aa79592c18566827ad8914debd5630d&v=4 url: https://github.com/dzoladz + - login: Zuzah + avatarUrl: https://avatars.githubusercontent.com/u/10934846?u=1ef43e075ddc87bd1178372bf4d95ee6175cae27&v=4 + url: https://github.com/Zuzah - login: Alisa-lisa avatarUrl: https://avatars.githubusercontent.com/u/4137964?u=e7e393504f554f4ff15863a1e01a5746863ef9ce&v=4 url: https://github.com/Alisa-lisa + - login: Graeme22 + avatarUrl: https://avatars.githubusercontent.com/u/4185684?u=498182a42300d7bcd4de1215190cb17eb501136c&v=4 + url: https://github.com/Graeme22 - login: danielunderwood avatarUrl: https://avatars.githubusercontent.com/u/4472301?v=4 url: https://github.com/danielunderwood @@ -488,30 +503,30 @@ sponsors: - login: jakeecolution avatarUrl: https://avatars.githubusercontent.com/u/5884696?u=4a7c7883fb064b593b50cb6697b54687e6f7aafe&v=4 url: https://github.com/jakeecolution -- - login: abizovnuralem - avatarUrl: https://avatars.githubusercontent.com/u/33475993?u=6ce72b11a16a8232d3dd1f958f460b4735f520d8&v=4 - url: https://github.com/abizovnuralem - - login: danburonline + - login: stephane-rbn + avatarUrl: https://avatars.githubusercontent.com/u/5939522?u=eb7ffe768fa3bcbcd04de14fe4a47444cc00ec4c&v=4 + url: https://github.com/stephane-rbn +- - login: danburonline avatarUrl: https://avatars.githubusercontent.com/u/34251194?u=94935cccfbec58083ab1e535212d54f1bf2c978a&v=4 url: https://github.com/danburonline + - login: AliYmn + avatarUrl: https://avatars.githubusercontent.com/u/18416653?u=0de5a262e8b4dc0a08d065f30f7a39941e246530&v=4 + url: https://github.com/AliYmn - login: sadikkuzu avatarUrl: https://avatars.githubusercontent.com/u/23168063?u=d179c06bb9f65c4167fcab118526819f8e0dac17&v=4 url: https://github.com/sadikkuzu + - login: tran-hai-long + avatarUrl: https://avatars.githubusercontent.com/u/119793901?u=3b173a845dcf099b275bdc9713a69cbbc36040ce&v=4 + url: https://github.com/tran-hai-long - login: rwxd avatarUrl: https://avatars.githubusercontent.com/u/40308458?u=cd04a39e3655923be4f25c2ba8a5a07b3da3230a&v=4 url: https://github.com/rwxd - - login: YungBricoCoop - avatarUrl: https://avatars.githubusercontent.com/u/42273436?u=80470b400c416d1eabc2cc71b1efffc0e3503146&v=4 - url: https://github.com/YungBricoCoop - - login: nlazaro - avatarUrl: https://avatars.githubusercontent.com/u/44237350?u=939a570fc965d93e9db1284b5acc173c1a0be4a0&v=4 - url: https://github.com/nlazaro - - login: Patechoc - avatarUrl: https://avatars.githubusercontent.com/u/2376641?u=23b49e9eda04f078cb74fa3f93593aa6a57bb138&v=4 - url: https://github.com/Patechoc - login: ssbarnea avatarUrl: https://avatars.githubusercontent.com/u/102495?u=c2efbf6fea2737e21dfc6b1113c4edc9644e9eaa&v=4 url: https://github.com/ssbarnea - login: yuawn avatarUrl: https://avatars.githubusercontent.com/u/5111198?u=5315576f3fe1a70fd2d0f02181588f4eea5d353d&v=4 url: https://github.com/yuawn + - login: dongzhenye + avatarUrl: https://avatars.githubusercontent.com/u/5765843?u=fe420c9a4c41e5b060faaf44029f5485616b470d&v=4 + url: https://github.com/dongzhenye diff --git a/docs/en/data/people.yml b/docs/en/data/people.yml index cc5479c82..02d1779e0 100644 --- a/docs/en/data/people.yml +++ b/docs/en/data/people.yml @@ -1,12 +1,12 @@ maintainers: - login: tiangolo - answers: 1878 - prs: 559 + answers: 1885 + prs: 577 avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=740f11212a731f56798f558ceddb0bd07642afa7&v=4 url: https://github.com/tiangolo experts: - login: Kludex - count: 598 + count: 608 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex - login: dmontagu @@ -14,7 +14,7 @@ experts: avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 url: https://github.com/dmontagu - login: jgould22 - count: 235 + count: 241 avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 url: https://github.com/jgould22 - login: Mause @@ -23,7 +23,7 @@ experts: url: https://github.com/Mause - login: ycd count: 217 - avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=45aa6ef58220a3f1e8a3c3cd5f1b75a1a0a73347&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=29682e4b6ac7d5293742ccf818188394b9a82972&v=4 url: https://github.com/ycd - login: JarroVGIT count: 193 @@ -41,46 +41,46 @@ experts: count: 126 avatarUrl: https://avatars.githubusercontent.com/u/331403?v=4 url: https://github.com/phy25 +- login: YuriiMotov + count: 104 + avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 + url: https://github.com/YuriiMotov - login: raphaelauv count: 83 avatarUrl: https://avatars.githubusercontent.com/u/10202690?u=e6f86f5c0c3026a15d6b51792fa3e532b12f1371&v=4 url: https://github.com/raphaelauv -- 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: ghandic + count: 71 + avatarUrl: https://avatars.githubusercontent.com/u/23500353?u=e2e1d736f924d9be81e8bfc565b6d8836ba99773&v=4 + url: https://github.com/ghandic +- login: JavierSanchezCastro + count: 64 + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro - login: falkben count: 59 avatarUrl: https://avatars.githubusercontent.com/u/653031?u=ad9838e089058c9e5a0bab94c0eec7cc181e0cd0&v=4 url: https://github.com/falkben -- login: JavierSanchezCastro - count: 55 - avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 - url: https://github.com/JavierSanchezCastro - login: n8sty - count: 52 + count: 56 avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 url: https://github.com/n8sty +- login: acidjunk + count: 50 + avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 + url: https://github.com/acidjunk +- login: yinziyan1206 + count: 49 + avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4 + url: https://github.com/yinziyan1206 - 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 - avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4 - url: https://github.com/yinziyan1206 -- login: acidjunk - count: 47 - avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 - url: https://github.com/acidjunk -- login: adriangb - count: 45 - avatarUrl: https://avatars.githubusercontent.com/u/1755071?u=612704256e38d6ac9cbed24f10e4b6ac2da74ecb&v=4 - url: https://github.com/adriangb - login: insomnes count: 45 avatarUrl: https://avatars.githubusercontent.com/u/16958893?u=f8be7088d5076d963984a21f95f44e559192d912&v=4 @@ -89,10 +89,10 @@ experts: count: 45 avatarUrl: https://avatars.githubusercontent.com/u/27180793?u=5cf2877f50b3eb2bc55086089a78a36f07042889&v=4 url: https://github.com/Dustyposa -- login: YuriiMotov - count: 43 - avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 - url: https://github.com/YuriiMotov +- login: adriangb + count: 45 + avatarUrl: https://avatars.githubusercontent.com/u/1755071?u=612704256e38d6ac9cbed24f10e4b6ac2da74ecb&v=4 + url: https://github.com/adriangb - login: frankie567 count: 43 avatarUrl: https://avatars.githubusercontent.com/u/1144727?u=c159fe047727aedecbbeeaa96a1b03ceb9d39add&v=4 @@ -125,6 +125,10 @@ experts: count: 28 avatarUrl: https://avatars.githubusercontent.com/u/28061158?u=72309cc1f2e04e40fa38b29969cb4e9d3f722e7b&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 @@ -141,22 +145,18 @@ experts: 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: chrisK824 count: 22 avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 url: https://github.com/chrisK824 -- login: nymous - count: 21 - avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 - url: https://github.com/nymous - login: rafsaf count: 21 avatarUrl: https://avatars.githubusercontent.com/u/51059348?u=5fe59a56e1f2f9ccd8005d71752a8276f133ae1a&v=4 url: https://github.com/rafsaf -- login: hasansezertasan - count: 20 - avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 - url: https://github.com/hasansezertasan - login: nsidnev count: 20 avatarUrl: https://avatars.githubusercontent.com/u/22559461?u=a9cc3238217e21dc8796a1a500f01b722adb082c&v=4 @@ -193,273 +193,253 @@ experts: count: 17 avatarUrl: https://avatars.githubusercontent.com/u/16540232?u=05d2beb8e034d584d0a374b99d8826327bd7f614&v=4 url: https://github.com/caeser1996 -- login: jonatasoli +- login: dstlny count: 16 - avatarUrl: https://avatars.githubusercontent.com/u/26334101?u=071c062d2861d3dd127f6b4a5258cd8ef55d4c50&v=4 - url: https://github.com/jonatasoli + avatarUrl: https://avatars.githubusercontent.com/u/41964673?u=9f2174f9d61c15c6e3a4c9e3aeee66f711ce311f&v=4 + url: https://github.com/dstlny last_month_experts: - login: YuriiMotov - count: 40 + count: 29 avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 url: https://github.com/YuriiMotov -- login: JavierSanchezCastro - count: 11 - avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 - url: https://github.com/JavierSanchezCastro -- login: Kludex +- login: killjoy1221 count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/3409962?u=723662989f2027755e67d200137c13c53ae154ac&v=4 + url: https://github.com/killjoy1221 +- login: Kludex + count: 7 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex -- login: jgould22 - count: 7 - avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 - url: https://github.com/jgould22 -- login: omarcruzpantoja - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/15116058?u=4b64c643fad49225d854e1aaecd1ffc6f9071a1b&v=4 - url: https://github.com/omarcruzpantoja -- login: pythonweb2 - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 - url: https://github.com/pythonweb2 +- login: JavierSanchezCastro + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro +- login: hasansezertasan + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 + url: https://github.com/hasansezertasan - login: PhysicallyActive - count: 2 + count: 3 avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4 url: https://github.com/PhysicallyActive -- login: VatsalJagani +- login: n8sty count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/20964366?u=43552644be05c9107c029e26d5ab3be5a1920f45&v=4 - url: https://github.com/VatsalJagani -- login: khaledadrani + avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 + url: https://github.com/n8sty +- login: pedroconceicao count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/45245894?u=49ed5056426a149a5af29d385d8bd3847101d3a4&v=4 - url: https://github.com/khaledadrani -- login: chrisK824 + avatarUrl: https://avatars.githubusercontent.com/u/32837064?u=5a0e6559bc391442629a28b6923790b54deb4464&v=4 + url: https://github.com/pedroconceicao +- login: PREPONDERANCE count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 - url: https://github.com/chrisK824 -- login: ThirVondukr + avatarUrl: https://avatars.githubusercontent.com/u/112809059?u=30ab12dc9ddba2f94ab90e6ad4ad8bc5cfa7fccd&v=4 + url: https://github.com/PREPONDERANCE +- login: aanchlia count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/50728601?u=167c0bd655e52817082e50979a86d2f98f95b1a3&v=4 - url: https://github.com/ThirVondukr -- login: hussein-awala + avatarUrl: https://avatars.githubusercontent.com/u/2835374?u=3c3ed29aa8b09ccaf8d66def0ce82bc2f7e5aab6&v=4 + url: https://github.com/aanchlia +- login: 0sahil + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/58521386?u=ac00b731c07c712d0baa57b8b70ac8422acf183c&v=4 + url: https://github.com/0sahil +- login: jgould22 count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/21311487?u=cbbc60943d3fedfb869e49b604020a821f589659&v=4 - url: https://github.com/hussein-awala + avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 + url: https://github.com/jgould22 three_months_experts: -- login: Kludex - count: 84 - avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 - url: https://github.com/Kludex - login: YuriiMotov - count: 43 + count: 101 avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 url: https://github.com/YuriiMotov -- login: jgould22 - count: 30 - avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 - url: https://github.com/jgould22 - login: JavierSanchezCastro - count: 24 + count: 20 avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 url: https://github.com/JavierSanchezCastro -- login: n8sty - count: 11 - avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 - url: https://github.com/n8sty +- login: Kludex + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 + url: https://github.com/Kludex +- login: jgould22 + count: 14 + avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 + url: https://github.com/jgould22 +- login: killjoy1221 + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/3409962?u=723662989f2027755e67d200137c13c53ae154ac&v=4 + url: https://github.com/killjoy1221 - login: hasansezertasan count: 8 avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 url: https://github.com/hasansezertasan -- login: dolfinus - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/4661021?u=a51b39001a2e5e7529b45826980becf786de2327&v=4 - url: https://github.com/dolfinus -- login: aanchlia +- login: PhysicallyActive count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/2835374?u=3c3ed29aa8b09ccaf8d66def0ce82bc2f7e5aab6&v=4 - url: https://github.com/aanchlia -- login: GodMoonGoodman + avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4 + url: https://github.com/PhysicallyActive +- login: n8sty + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 + url: https://github.com/n8sty +- login: sehraramiz count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/29688727?u=7b251da620d999644c37c1feeb292d033eed7ad6&v=4 - url: https://github.com/GodMoonGoodman -- login: flo-at + avatarUrl: https://avatars.githubusercontent.com/u/14166324?v=4 + url: https://github.com/sehraramiz +- login: acidjunk count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/564288?v=4 - url: https://github.com/flo-at + avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 + url: https://github.com/acidjunk - login: estebanx64 - count: 4 + count: 3 avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 url: https://github.com/estebanx64 -- login: omarcruzpantoja - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/15116058?u=4b64c643fad49225d854e1aaecd1ffc6f9071a1b&v=4 - url: https://github.com/omarcruzpantoja -- login: fmelihh +- login: PREPONDERANCE count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/99879453?u=f76c4460556e41a59eb624acd0cf6e342d660700&v=4 - url: https://github.com/fmelihh -- login: ahmedabdou14 - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/104530599?u=05365b155a1ff911532e8be316acfad2e0736f98&v=4 - url: https://github.com/ahmedabdou14 + avatarUrl: https://avatars.githubusercontent.com/u/112809059?u=30ab12dc9ddba2f94ab90e6ad4ad8bc5cfa7fccd&v=4 + url: https://github.com/PREPONDERANCE - login: chrisK824 count: 3 avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 url: https://github.com/chrisK824 +- login: ryanisn + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/53449841?v=4 + url: https://github.com/ryanisn - login: pythonweb2 - count: 2 + count: 3 avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 url: https://github.com/pythonweb2 -- login: PhysicallyActive - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4 - url: https://github.com/PhysicallyActive -- login: richin13 - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/8370058?u=8e37a4cdbc78983a5f4b4847f6d1879fb39c851c&v=4 - url: https://github.com/richin13 -- login: VatsalJagani - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/20964366?u=43552644be05c9107c029e26d5ab3be5a1920f45&v=4 - url: https://github.com/VatsalJagani -- login: khaledadrani - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/45245894?u=49ed5056426a149a5af29d385d8bd3847101d3a4&v=4 - url: https://github.com/khaledadrani -- login: acidjunk - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 - url: https://github.com/acidjunk -- login: agn-7 - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/14202344?u=a1d05998ceaf4d06d1063575a7c4ef6e7ae5890e&v=4 - url: https://github.com/agn-7 -- login: ThirVondukr +- login: omarcruzpantoja + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/15116058?u=4b64c643fad49225d854e1aaecd1ffc6f9071a1b&v=4 + url: https://github.com/omarcruzpantoja +- login: mskrip count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/50728601?u=167c0bd655e52817082e50979a86d2f98f95b1a3&v=4 - url: https://github.com/ThirVondukr -- login: hussein-awala + avatarUrl: https://avatars.githubusercontent.com/u/17459600?u=10019d5c38ae3374dd4a6743b0223e56a78d4855&v=4 + url: https://github.com/mskrip +- login: pedroconceicao count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/21311487?u=cbbc60943d3fedfb869e49b604020a821f589659&v=4 - url: https://github.com/hussein-awala -- login: JoshYuJump + avatarUrl: https://avatars.githubusercontent.com/u/32837064?u=5a0e6559bc391442629a28b6923790b54deb4464&v=4 + url: https://github.com/pedroconceicao +- login: Jackiexiao count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/5901894?u=cdbca6296ac4cdcdf6945c112a1ce8d5342839ea&v=4 - url: https://github.com/JoshYuJump -- login: bhumkong + avatarUrl: https://avatars.githubusercontent.com/u/18050469?u=a2003e21a7780477ba00bf87a9abef8af58e91d1&v=4 + url: https://github.com/Jackiexiao +- login: aanchlia count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/13270137?u=1490432e6a0184fbc3d5c8d1b5df553ca92e7e5b&v=4 - url: https://github.com/bhumkong -- login: falkben + avatarUrl: https://avatars.githubusercontent.com/u/2835374?u=3c3ed29aa8b09ccaf8d66def0ce82bc2f7e5aab6&v=4 + url: https://github.com/aanchlia +- login: moreno-p count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/653031?u=ad9838e089058c9e5a0bab94c0eec7cc181e0cd0&v=4 - url: https://github.com/falkben -- login: mielvds + avatarUrl: https://avatars.githubusercontent.com/u/164261630?v=4 + url: https://github.com/moreno-p +- login: 0sahil count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/1032980?u=722c96b0a234752df23f04df150ef36441ceb43c&v=4 - url: https://github.com/mielvds -- login: admo1 + avatarUrl: https://avatars.githubusercontent.com/u/58521386?u=ac00b731c07c712d0baa57b8b70ac8422acf183c&v=4 + url: https://github.com/0sahil +- login: patrick91 count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/14835916?v=4 - url: https://github.com/admo1 -- login: pbasista + avatarUrl: https://avatars.githubusercontent.com/u/667029?u=e35958a75ac1f99c81b4bc99e22db8cd665ae7f0&v=4 + url: https://github.com/patrick91 +- login: pprunty count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/1535892?u=e9a8bd5b3b2f95340cfeb4bc97886e9334911669&v=4 - url: https://github.com/pbasista -- login: bogdan-coman-uv + avatarUrl: https://avatars.githubusercontent.com/u/58374462?u=5736576e586429abc97a803b8bcd4a6d828b8a2f&v=4 + url: https://github.com/pprunty +- login: angely-dev count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/92912507?v=4 - url: https://github.com/bogdan-coman-uv -- login: leonidktoto + avatarUrl: https://avatars.githubusercontent.com/u/4362224?v=4 + url: https://github.com/angely-dev +- login: mastizada count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/159561986?v=4 - url: https://github.com/leonidktoto -- login: DJoepie + avatarUrl: https://avatars.githubusercontent.com/u/1975818?u=0751a06d7271c8bf17cb73b1b845644ab4d2c6dc&v=4 + url: https://github.com/mastizada +- login: sm-Fifteen count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/78362619?u=fe6e8d05f94d8d4c0679a4da943955a686f96177&v=4 - url: https://github.com/DJoepie -- login: binbjz + avatarUrl: https://avatars.githubusercontent.com/u/516999?u=437c0c5038558c67e887ccd863c1ba0f846c03da&v=4 + url: https://github.com/sm-Fifteen +- login: methane count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/8213913?u=22b68b7a0d5bf5e09c02084c0f5f53d7503114cd&v=4 - url: https://github.com/binbjz -- login: JonnyBootsNpants + avatarUrl: https://avatars.githubusercontent.com/u/199592?v=4 + url: https://github.com/methane +- login: konstantinos1981 count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/155071540?u=2d3a72b74a2c4c8eaacdb625c7ac850369579352&v=4 - url: https://github.com/JonnyBootsNpants -- login: TarasKuzyo + avatarUrl: https://avatars.githubusercontent.com/u/39465388?v=4 + url: https://github.com/konstantinos1981 +- login: druidance count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/7178184?v=4 - url: https://github.com/TarasKuzyo -- login: msehnout + avatarUrl: https://avatars.githubusercontent.com/u/160344534?v=4 + url: https://github.com/druidance +- login: fabianfalon count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/9369632?u=8c988f1b008a3f601385a3616f9327820f66e3a5&v=4 - url: https://github.com/msehnout -- login: rafalkrupinski + avatarUrl: https://avatars.githubusercontent.com/u/3700760?u=95f69e31280b17ac22299cdcd345323b142fe0af&v=4 + url: https://github.com/fabianfalon +- login: VatsalJagani count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/3732079?u=929e95d40d524301cb481da05208a25ed059400d&v=4 - url: https://github.com/rafalkrupinski -- login: morian + avatarUrl: https://avatars.githubusercontent.com/u/20964366?u=43552644be05c9107c029e26d5ab3be5a1920f45&v=4 + url: https://github.com/VatsalJagani +- login: khaledadrani count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/1735308?u=8ef15491399b040bd95e2675bb8c8f2462e977b0&v=4 - url: https://github.com/morian -- login: garg10may + avatarUrl: https://avatars.githubusercontent.com/u/45245894?u=49ed5056426a149a5af29d385d8bd3847101d3a4&v=4 + url: https://github.com/khaledadrani +- login: ThirVondukr count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/8787120?u=7028d2b3a2a26534c1806eb76c7425a3fac9732f&v=4 - url: https://github.com/garg10may + avatarUrl: https://avatars.githubusercontent.com/u/50728601?u=167c0bd655e52817082e50979a86d2f98f95b1a3&v=4 + url: https://github.com/ThirVondukr six_months_experts: -- login: Kludex - count: 108 - avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 - url: https://github.com/Kludex -- login: jgould22 - count: 67 - avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 - url: https://github.com/jgould22 - login: YuriiMotov - count: 43 + count: 104 avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 url: https://github.com/YuriiMotov +- login: Kludex + count: 104 + avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 + url: https://github.com/Kludex - login: JavierSanchezCastro - count: 35 + count: 40 avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 url: https://github.com/JavierSanchezCastro -- login: n8sty - count: 21 - avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 - url: https://github.com/n8sty +- login: jgould22 + count: 40 + avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 + url: https://github.com/jgould22 - login: hasansezertasan - count: 20 + count: 21 avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 url: https://github.com/hasansezertasan -- login: WilliamStam +- login: n8sty + count: 19 + avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 + url: https://github.com/n8sty +- login: killjoy1221 count: 9 - avatarUrl: https://avatars.githubusercontent.com/u/182800?v=4 - url: https://github.com/WilliamStam -- login: pythonweb2 + avatarUrl: https://avatars.githubusercontent.com/u/3409962?u=723662989f2027755e67d200137c13c53ae154ac&v=4 + url: https://github.com/killjoy1221 +- login: aanchlia + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/2835374?u=3c3ed29aa8b09ccaf8d66def0ce82bc2f7e5aab6&v=4 + url: https://github.com/aanchlia +- login: estebanx64 + count: 7 + avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 + url: https://github.com/estebanx64 +- login: PhysicallyActive count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 - url: https://github.com/pythonweb2 + avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4 + url: https://github.com/PhysicallyActive - login: dolfinus count: 6 avatarUrl: https://avatars.githubusercontent.com/u/4661021?u=a51b39001a2e5e7529b45826980becf786de2327&v=4 url: https://github.com/dolfinus -- login: aanchlia - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/2835374?u=3c3ed29aa8b09ccaf8d66def0ce82bc2f7e5aab6&v=4 - url: https://github.com/aanchlia - login: Ventura94 count: 6 avatarUrl: https://avatars.githubusercontent.com/u/43103937?u=ccb837005aaf212a449c374618c4339089e2f733&v=4 url: https://github.com/Ventura94 -- login: White-Mask - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/31826970?u=8625355dc25ddf9c85a8b2b0b9932826c4c8f44c&v=4 - url: https://github.com/White-Mask -- login: nymous +- login: sehraramiz count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 - url: https://github.com/nymous + avatarUrl: https://avatars.githubusercontent.com/u/14166324?v=4 + url: https://github.com/sehraramiz +- login: acidjunk + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 + url: https://github.com/acidjunk - login: shashstormer count: 5 avatarUrl: https://avatars.githubusercontent.com/u/90090313?v=4 @@ -468,227 +448,223 @@ six_months_experts: count: 4 avatarUrl: https://avatars.githubusercontent.com/u/29688727?u=7b251da620d999644c37c1feeb292d033eed7ad6&v=4 url: https://github.com/GodMoonGoodman -- login: JoshYuJump - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/5901894?u=cdbca6296ac4cdcdf6945c112a1ce8d5342839ea&v=4 - url: https://github.com/JoshYuJump - login: flo-at count: 4 avatarUrl: https://avatars.githubusercontent.com/u/564288?v=4 url: https://github.com/flo-at -- login: estebanx64 - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 - url: https://github.com/estebanx64 -- login: omarcruzpantoja +- login: PREPONDERANCE count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/15116058?u=4b64c643fad49225d854e1aaecd1ffc6f9071a1b&v=4 - url: https://github.com/omarcruzpantoja -- login: fmelihh - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/99879453?u=f76c4460556e41a59eb624acd0cf6e342d660700&v=4 - url: https://github.com/fmelihh -- login: ahmedabdou14 - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/104530599?u=05365b155a1ff911532e8be316acfad2e0736f98&v=4 - url: https://github.com/ahmedabdou14 + avatarUrl: https://avatars.githubusercontent.com/u/112809059?u=30ab12dc9ddba2f94ab90e6ad4ad8bc5cfa7fccd&v=4 + url: https://github.com/PREPONDERANCE - login: chrisK824 count: 3 avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 url: https://github.com/chrisK824 -- login: ebottos94 +- login: angely-dev count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=e2c672da5a7977fd24d87ce6ab35f8bf5b1ed9fa&v=4 - url: https://github.com/ebottos94 -- login: binbjz + avatarUrl: https://avatars.githubusercontent.com/u/4362224?v=4 + url: https://github.com/angely-dev +- login: fmelihh count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/8213913?u=22b68b7a0d5bf5e09c02084c0f5f53d7503114cd&v=4 - url: https://github.com/binbjz -- login: theobouwman + avatarUrl: https://avatars.githubusercontent.com/u/99879453?u=671117dba9022db2237e3da7a39cbc2efc838db0&v=4 + url: https://github.com/fmelihh +- login: ryanisn count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/16098190?u=dc70db88a7a99b764c9a89a6e471e0b7ca478a35&v=4 - url: https://github.com/theobouwman -- login: sriram-kondakindi + avatarUrl: https://avatars.githubusercontent.com/u/53449841?v=4 + url: https://github.com/ryanisn +- login: JoshYuJump count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/32274323?v=4 - url: https://github.com/sriram-kondakindi -- login: yinziyan1206 + avatarUrl: https://avatars.githubusercontent.com/u/5901894?u=cdbca6296ac4cdcdf6945c112a1ce8d5342839ea&v=4 + url: https://github.com/JoshYuJump +- login: pythonweb2 count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4 - url: https://github.com/yinziyan1206 -- login: pcorvoh + avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 + url: https://github.com/pythonweb2 +- login: omarcruzpantoja count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/48502122?u=89fe3e55f3cfd15d34ffac239b32af358cca6481&v=4 - url: https://github.com/pcorvoh -- login: osangu + avatarUrl: https://avatars.githubusercontent.com/u/15116058?u=4b64c643fad49225d854e1aaecd1ffc6f9071a1b&v=4 + url: https://github.com/omarcruzpantoja +- login: bogdan-coman-uv + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/92912507?v=4 + url: https://github.com/bogdan-coman-uv +- login: ahmedabdou14 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/104530599?u=05365b155a1ff911532e8be316acfad2e0736f98&v=4 + url: https://github.com/ahmedabdou14 +- login: mskrip count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/80697064?u=de9bae685e2228bffd4e202274e1df1afaf54a0d&v=4 - url: https://github.com/osangu -- login: PhysicallyActive + avatarUrl: https://avatars.githubusercontent.com/u/17459600?u=10019d5c38ae3374dd4a6743b0223e56a78d4855&v=4 + url: https://github.com/mskrip +- login: leonidktoto count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4 - url: https://github.com/PhysicallyActive -- login: richin13 + avatarUrl: https://avatars.githubusercontent.com/u/159561986?v=4 + url: https://github.com/leonidktoto +- login: pedroconceicao count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/8370058?u=8e37a4cdbc78983a5f4b4847f6d1879fb39c851c&v=4 - url: https://github.com/richin13 -- login: amacfie + avatarUrl: https://avatars.githubusercontent.com/u/32837064?u=5a0e6559bc391442629a28b6923790b54deb4464&v=4 + url: https://github.com/pedroconceicao +- login: hwong557 count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/889657?u=d70187989940b085bcbfa3bedad8dbc5f3ab1fe7&v=4 - url: https://github.com/amacfie -- login: WSH032 + avatarUrl: https://avatars.githubusercontent.com/u/460259?u=7d2f1b33ea5bda4d8e177ab3cb924a673d53087e&v=4 + url: https://github.com/hwong557 +- login: Jackiexiao count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/126865849?v=4 - url: https://github.com/WSH032 -- login: MRigal + avatarUrl: https://avatars.githubusercontent.com/u/18050469?u=a2003e21a7780477ba00bf87a9abef8af58e91d1&v=4 + url: https://github.com/Jackiexiao +- login: admo1 count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/2190327?u=557f399ee90319da7bc4a7d9274e110836b0bd60&v=4 - url: https://github.com/MRigal -- login: VatsalJagani + avatarUrl: https://avatars.githubusercontent.com/u/14835916?v=4 + url: https://github.com/admo1 +- login: binbjz count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/20964366?u=43552644be05c9107c029e26d5ab3be5a1920f45&v=4 - url: https://github.com/VatsalJagani + avatarUrl: https://avatars.githubusercontent.com/u/8213913?u=22b68b7a0d5bf5e09c02084c0f5f53d7503114cd&v=4 + url: https://github.com/binbjz - login: nameer count: 2 avatarUrl: https://avatars.githubusercontent.com/u/3931725?u=6199fb065df098fc13ac0a5e649f89672b586732&v=4 url: https://github.com/nameer -- login: kiraware +- login: moreno-p count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/117554978?v=4 - url: https://github.com/kiraware -- login: iudeen + avatarUrl: https://avatars.githubusercontent.com/u/164261630?v=4 + url: https://github.com/moreno-p +- login: 0sahil count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 - url: https://github.com/iudeen -- login: khaledadrani + avatarUrl: https://avatars.githubusercontent.com/u/58521386?u=ac00b731c07c712d0baa57b8b70ac8422acf183c&v=4 + url: https://github.com/0sahil +- login: nymous count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/45245894?u=49ed5056426a149a5af29d385d8bd3847101d3a4&v=4 - url: https://github.com/khaledadrani -- login: acidjunk + avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 + url: https://github.com/nymous +- login: patrick91 count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 - url: https://github.com/acidjunk -- login: yavuzakyazici + avatarUrl: https://avatars.githubusercontent.com/u/667029?u=e35958a75ac1f99c81b4bc99e22db8cd665ae7f0&v=4 + url: https://github.com/patrick91 +- login: pprunty count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/148442912?u=1d2d150172c53daf82020b950c6483a6c6a77b7e&v=4 - url: https://github.com/yavuzakyazici -- login: AntonioBarral + avatarUrl: https://avatars.githubusercontent.com/u/58374462?u=5736576e586429abc97a803b8bcd4a6d828b8a2f&v=4 + url: https://github.com/pprunty +- login: JonnyBootsNpants count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/22151181?u=64416447a37a420e6dfd16e675cf74f66c9f204d&v=4 - url: https://github.com/AntonioBarral -- login: agn-7 + avatarUrl: https://avatars.githubusercontent.com/u/155071540?u=2d3a72b74a2c4c8eaacdb625c7ac850369579352&v=4 + url: https://github.com/JonnyBootsNpants +- login: richin13 count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/14202344?u=a1d05998ceaf4d06d1063575a7c4ef6e7ae5890e&v=4 - url: https://github.com/agn-7 -- login: ThirVondukr + avatarUrl: https://avatars.githubusercontent.com/u/8370058?u=8e37a4cdbc78983a5f4b4847f6d1879fb39c851c&v=4 + url: https://github.com/richin13 +- login: mastizada count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/50728601?u=167c0bd655e52817082e50979a86d2f98f95b1a3&v=4 - url: https://github.com/ThirVondukr -- login: hussein-awala + avatarUrl: https://avatars.githubusercontent.com/u/1975818?u=0751a06d7271c8bf17cb73b1b845644ab4d2c6dc&v=4 + url: https://github.com/mastizada +- login: sm-Fifteen count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/21311487?u=cbbc60943d3fedfb869e49b604020a821f589659&v=4 - url: https://github.com/hussein-awala -- login: jcphlux + avatarUrl: https://avatars.githubusercontent.com/u/516999?u=437c0c5038558c67e887ccd863c1ba0f846c03da&v=4 + url: https://github.com/sm-Fifteen +- login: amacfie count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/996689?v=4 - url: https://github.com/jcphlux -- login: bhumkong + avatarUrl: https://avatars.githubusercontent.com/u/889657?u=d70187989940b085bcbfa3bedad8dbc5f3ab1fe7&v=4 + url: https://github.com/amacfie +- login: garg10may count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/13270137?u=1490432e6a0184fbc3d5c8d1b5df553ca92e7e5b&v=4 - url: https://github.com/bhumkong -- login: falkben + avatarUrl: https://avatars.githubusercontent.com/u/8787120?u=7028d2b3a2a26534c1806eb76c7425a3fac9732f&v=4 + url: https://github.com/garg10may +- login: methane count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/653031?u=ad9838e089058c9e5a0bab94c0eec7cc181e0cd0&v=4 - url: https://github.com/falkben -- login: mielvds + avatarUrl: https://avatars.githubusercontent.com/u/199592?v=4 + url: https://github.com/methane +- login: konstantinos1981 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/39465388?v=4 + url: https://github.com/konstantinos1981 +- login: druidance count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/1032980?u=722c96b0a234752df23f04df150ef36441ceb43c&v=4 - url: https://github.com/mielvds + avatarUrl: https://avatars.githubusercontent.com/u/160344534?v=4 + url: https://github.com/druidance one_year_experts: - login: Kludex - count: 218 + count: 207 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex - login: jgould22 - count: 133 + count: 118 avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 url: https://github.com/jgould22 -- login: JavierSanchezCastro - count: 55 - avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 - url: https://github.com/JavierSanchezCastro - login: YuriiMotov - count: 43 + count: 104 avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 url: https://github.com/YuriiMotov +- login: JavierSanchezCastro + count: 59 + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro - login: n8sty - count: 37 + count: 40 avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 url: https://github.com/n8sty -- login: chrisK824 - count: 22 - avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 - url: https://github.com/chrisK824 - login: hasansezertasan - count: 20 + count: 27 avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 url: https://github.com/hasansezertasan -- login: nymous - count: 13 - avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 - url: https://github.com/nymous +- login: chrisK824 + count: 16 + avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 + url: https://github.com/chrisK824 - login: ahmedabdou14 count: 13 avatarUrl: https://avatars.githubusercontent.com/u/104530599?u=05365b155a1ff911532e8be316acfad2e0736f98&v=4 url: https://github.com/ahmedabdou14 -- login: abhint - count: 12 - avatarUrl: https://avatars.githubusercontent.com/u/25699289?u=b5d219277b4d001ac26fb8be357fddd88c29d51b&v=4 - url: https://github.com/abhint - login: arjwilliams count: 12 avatarUrl: https://avatars.githubusercontent.com/u/22227620?v=4 url: https://github.com/arjwilliams -- login: iudeen - count: 11 - avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 - url: https://github.com/iudeen +- login: killjoy1221 + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/3409962?u=723662989f2027755e67d200137c13c53ae154ac&v=4 + url: https://github.com/killjoy1221 - login: WilliamStam count: 10 avatarUrl: https://avatars.githubusercontent.com/u/182800?v=4 url: https://github.com/WilliamStam -- login: yinziyan1206 +- login: iudeen + count: 10 + avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 + url: https://github.com/iudeen +- login: nymous count: 9 - avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4 - url: https://github.com/yinziyan1206 -- login: mateoradman - count: 7 - avatarUrl: https://avatars.githubusercontent.com/u/48420316?u=066f36b8e8e263b0d90798113b0f291d3266db7c&v=4 - url: https://github.com/mateoradman -- login: Viicos + avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 + url: https://github.com/nymous +- login: aanchlia + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/2835374?u=3c3ed29aa8b09ccaf8d66def0ce82bc2f7e5aab6&v=4 + url: https://github.com/aanchlia +- login: estebanx64 count: 7 - avatarUrl: https://avatars.githubusercontent.com/u/65306057?u=fcd677dc1b9bef12aa103613e5ccb3f8ce305af9&v=4 - url: https://github.com/Viicos + avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 + url: https://github.com/estebanx64 - login: pythonweb2 - count: 6 + count: 7 avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 url: https://github.com/pythonweb2 -- login: ebottos94 +- login: romabozhanovgithub count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=e2c672da5a7977fd24d87ce6ab35f8bf5b1ed9fa&v=4 - url: https://github.com/ebottos94 + avatarUrl: https://avatars.githubusercontent.com/u/67696229?u=e4b921eef096415300425aca249348f8abb78ad7&v=4 + url: https://github.com/romabozhanovgithub +- login: PhysicallyActive + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4 + url: https://github.com/PhysicallyActive +- login: mikeedjones + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/4087139?u=cc4a242896ac2fcf88a53acfaf190d0fe0a1f0c9&v=4 + url: https://github.com/mikeedjones - login: dolfinus count: 6 avatarUrl: https://avatars.githubusercontent.com/u/4661021?u=a51b39001a2e5e7529b45826980becf786de2327&v=4 url: https://github.com/dolfinus -- login: aanchlia - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/2835374?u=3c3ed29aa8b09ccaf8d66def0ce82bc2f7e5aab6&v=4 - url: https://github.com/aanchlia -- login: romabozhanovgithub +- login: ebottos94 count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/67696229?u=e4b921eef096415300425aca249348f8abb78ad7&v=4 - url: https://github.com/romabozhanovgithub + avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=e2c672da5a7977fd24d87ce6ab35f8bf5b1ed9fa&v=4 + url: https://github.com/ebottos94 - login: Ventura94 count: 6 avatarUrl: https://avatars.githubusercontent.com/u/43103937?u=ccb837005aaf212a449c374618c4339089e2f733&v=4 @@ -697,18 +673,18 @@ one_year_experts: count: 6 avatarUrl: https://avatars.githubusercontent.com/u/31826970?u=8625355dc25ddf9c85a8b2b0b9932826c4c8f44c&v=4 url: https://github.com/White-Mask -- login: mikeedjones - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/4087139?u=cc4a242896ac2fcf88a53acfaf190d0fe0a1f0c9&v=4 - url: https://github.com/mikeedjones -- login: ThirVondukr +- login: sehraramiz count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/50728601?u=167c0bd655e52817082e50979a86d2f98f95b1a3&v=4 - url: https://github.com/ThirVondukr -- login: dmontagu + avatarUrl: https://avatars.githubusercontent.com/u/14166324?v=4 + url: https://github.com/sehraramiz +- login: acidjunk count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 - url: https://github.com/dmontagu + avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 + url: https://github.com/acidjunk +- login: JoshYuJump + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/5901894?u=cdbca6296ac4cdcdf6945c112a1ce8d5342839ea&v=4 + url: https://github.com/JoshYuJump - login: alex-pobeditel-2004 count: 5 avatarUrl: https://avatars.githubusercontent.com/u/14791483?v=4 @@ -717,82 +693,54 @@ one_year_experts: count: 5 avatarUrl: https://avatars.githubusercontent.com/u/90090313?v=4 url: https://github.com/shashstormer -- login: nzig - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/7372858?u=e769add36ed73c778cdb136eb10bf96b1e119671&v=4 - url: https://github.com/nzig - login: wu-clan count: 5 avatarUrl: https://avatars.githubusercontent.com/u/52145145?u=f8c9e5c8c259d248e1683fedf5027b4ee08a0967&v=4 url: https://github.com/wu-clan -- login: 8thgencore +- login: abhint count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/30128845?u=a747e840f751a1d196d70d0ecf6d07a530d412a1&v=4 - url: https://github.com/8thgencore + avatarUrl: https://avatars.githubusercontent.com/u/25699289?u=b5d219277b4d001ac26fb8be357fddd88c29d51b&v=4 + url: https://github.com/abhint - login: anthonycepeda count: 4 avatarUrl: https://avatars.githubusercontent.com/u/72019805?u=60bdf46240cff8fca482ff0fc07d963fd5e1a27c&v=4 url: https://github.com/anthonycepeda -- login: acidjunk - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 - url: https://github.com/acidjunk - login: GodMoonGoodman count: 4 avatarUrl: https://avatars.githubusercontent.com/u/29688727?u=7b251da620d999644c37c1feeb292d033eed7ad6&v=4 url: https://github.com/GodMoonGoodman -- login: JoshYuJump - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/5901894?u=cdbca6296ac4cdcdf6945c112a1ce8d5342839ea&v=4 - url: https://github.com/JoshYuJump - login: flo-at count: 4 avatarUrl: https://avatars.githubusercontent.com/u/564288?v=4 url: https://github.com/flo-at +- login: yinziyan1206 + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4 + url: https://github.com/yinziyan1206 +- login: amacfie + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/889657?u=d70187989940b085bcbfa3bedad8dbc5f3ab1fe7&v=4 + url: https://github.com/amacfie - login: commonism count: 4 avatarUrl: https://avatars.githubusercontent.com/u/164513?v=4 url: https://github.com/commonism -- login: estebanx64 - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 - url: https://github.com/estebanx64 -- login: djimontyp +- login: dmontagu count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/53098395?u=583bade70950b277c322d35f1be2b75c7b0f189c&v=4 - url: https://github.com/djimontyp + avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 + url: https://github.com/dmontagu - login: sanzoghenzo count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/977953?u=d94445b7b87b7096a92a2d4b652ca6c560f34039&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/977953?v=4 url: https://github.com/sanzoghenzo -- login: adriangb - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/1755071?u=612704256e38d6ac9cbed24f10e4b6ac2da74ecb&v=4 - url: https://github.com/adriangb -- login: 9en9i - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/44907258?u=297d0f31ea99c22b718118c1deec82001690cadb&v=4 - url: https://github.com/9en9i -- login: mht2953658596 - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/59814105?v=4 - url: https://github.com/mht2953658596 -- login: omarcruzpantoja - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/15116058?u=4b64c643fad49225d854e1aaecd1ffc6f9071a1b&v=4 - url: https://github.com/omarcruzpantoja -- login: fmelihh - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/99879453?u=f76c4460556e41a59eb624acd0cf6e342d660700&v=4 - url: https://github.com/fmelihh -- login: amacfie +- login: lucasgadams count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/889657?u=d70187989940b085bcbfa3bedad8dbc5f3ab1fe7&v=4 - url: https://github.com/amacfie -- login: nameer + avatarUrl: https://avatars.githubusercontent.com/u/36425095?v=4 + url: https://github.com/lucasgadams +- login: NeilBotelho count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/3931725?u=6199fb065df098fc13ac0a5e649f89672b586732&v=4 - url: https://github.com/nameer + avatarUrl: https://avatars.githubusercontent.com/u/39030675?u=16fea2ff90a5c67b974744528a38832a6d1bb4f7&v=4 + url: https://github.com/NeilBotelho - login: hhartzer count: 3 avatarUrl: https://avatars.githubusercontent.com/u/100533792?v=4 @@ -801,9 +749,37 @@ one_year_experts: count: 3 avatarUrl: https://avatars.githubusercontent.com/u/8213913?u=22b68b7a0d5bf5e09c02084c0f5f53d7503114cd&v=4 url: https://github.com/binbjz +- login: PREPONDERANCE + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/112809059?u=30ab12dc9ddba2f94ab90e6ad4ad8bc5cfa7fccd&v=4 + url: https://github.com/PREPONDERANCE +- login: nameer + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/3931725?u=6199fb065df098fc13ac0a5e649f89672b586732&v=4 + url: https://github.com/nameer +- login: angely-dev + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/4362224?v=4 + url: https://github.com/angely-dev +- login: fmelihh + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/99879453?u=671117dba9022db2237e3da7a39cbc2efc838db0&v=4 + url: https://github.com/fmelihh +- login: ryanisn + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/53449841?v=4 + url: https://github.com/ryanisn +- login: theobouwman + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/16098190?u=dc70db88a7a99b764c9a89a6e471e0b7ca478a35&v=4 + url: https://github.com/theobouwman +- login: methane + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/199592?v=4 + url: https://github.com/methane top_contributors: - login: nilslindemann - count: 127 + count: 130 avatarUrl: https://avatars.githubusercontent.com/u/6892179?u=1dca6a22195d6cd1ab20737c0e19a4c55d639472&v=4 url: https://github.com/nilslindemann - login: jaystone776 @@ -818,14 +794,18 @@ top_contributors: count: 24 avatarUrl: https://avatars.githubusercontent.com/u/41147016?u=55010621aece725aa702270b54fed829b6a1fe60&v=4 url: https://github.com/tokusumi +- login: SwftAlpc + count: 23 + avatarUrl: https://avatars.githubusercontent.com/u/52768429?u=6a3aa15277406520ad37f6236e89466ed44bc5b8&v=4 + url: https://github.com/SwftAlpc - login: Kludex count: 22 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex -- login: SwftAlpc - count: 21 - avatarUrl: https://avatars.githubusercontent.com/u/52768429?u=6a3aa15277406520ad37f6236e89466ed44bc5b8&v=4 - url: https://github.com/SwftAlpc +- login: hasansezertasan + count: 22 + avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 + url: https://github.com/hasansezertasan - login: dmontagu count: 17 avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 @@ -842,29 +822,25 @@ top_contributors: count: 12 avatarUrl: https://avatars.githubusercontent.com/u/11489395?u=4adb6986bf3debfc2b8216ae701f2bd47d73da7d&v=4 url: https://github.com/mariacamilagl -- login: hasansezertasan +- login: AlertRED count: 12 - avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 - url: https://github.com/hasansezertasan + avatarUrl: https://avatars.githubusercontent.com/u/15695000?u=f5a4944c6df443030409c88da7d7fa0b7ead985c&v=4 + url: https://github.com/AlertRED - login: Smlep count: 11 avatarUrl: https://avatars.githubusercontent.com/u/16785985?v=4 url: https://github.com/Smlep -- login: AlertRED +- login: alejsdev count: 11 - avatarUrl: https://avatars.githubusercontent.com/u/15695000?u=f5a4944c6df443030409c88da7d7fa0b7ead985c&v=4 - url: https://github.com/AlertRED + avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=9ca449ad5161af12766ddd1a22988e9b14315f5c&v=4 + url: https://github.com/alejsdev - login: hard-coders count: 10 avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=95db33927bbff1ed1c07efddeb97ac2ff33068ed&v=4 url: https://github.com/hard-coders -- login: alejsdev - count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=1ee3a9fbef27abc9448ef5951350f99c7d76f7af&v=4 - url: https://github.com/alejsdev - login: KaniKim count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/19832624?u=d8ff6fca8542d22f94388cd2c4292e76e3898584&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/19832624?u=40f8f7f3f36d5f2365ba2ad0b40693e60958ce70&v=4 url: https://github.com/KaniKim - login: xzmeng count: 9 @@ -912,7 +888,7 @@ top_contributors: url: https://github.com/Attsun1031 - login: ComicShrimp count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/43503750?u=f440bc9062afb3c43b9b9c6cdfdcfe31d58699ef&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/43503750?u=d2fbf412e7730183ce91686ca48d4147e1b7dc74&v=4 url: https://github.com/ComicShrimp - login: rostik1410 count: 5 @@ -932,7 +908,7 @@ top_contributors: url: https://github.com/jfunez - login: ycd count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=45aa6ef58220a3f1e8a3c3cd5f1b75a1a0a73347&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=29682e4b6ac7d5293742ccf818188394b9a82972&v=4 url: https://github.com/ycd - login: komtaki count: 4 @@ -988,7 +964,7 @@ top_contributors: url: https://github.com/pawamoy top_reviewers: - login: Kludex - count: 156 + count: 158 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex - login: BilalAlpaslan @@ -996,7 +972,7 @@ top_reviewers: avatarUrl: https://avatars.githubusercontent.com/u/47563997?u=63ed66e304fe8d765762c70587d61d9196e5c82d&v=4 url: https://github.com/BilalAlpaslan - login: yezz123 - count: 84 + count: 85 avatarUrl: https://avatars.githubusercontent.com/u/52716203?u=d7062cbc6eb7671d5dc9cc0e32a24ae335e0f225&v=4 url: https://github.com/yezz123 - login: iudeen @@ -1011,6 +987,10 @@ top_reviewers: count: 50 avatarUrl: https://avatars.githubusercontent.com/u/85196001?u=f8e2dc7e5104f109cef944af79050ea8d1b8f914&v=4 url: https://github.com/Xewus +- login: hasansezertasan + count: 50 + avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 + url: https://github.com/hasansezertasan - login: waynerv count: 47 avatarUrl: https://avatars.githubusercontent.com/u/39515546?u=ec35139777597cdbbbddda29bf8b9d4396b429a9&v=4 @@ -1021,19 +1001,15 @@ top_reviewers: url: https://github.com/Laineyzhang55 - login: ycd count: 45 - avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=45aa6ef58220a3f1e8a3c3cd5f1b75a1a0a73347&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=29682e4b6ac7d5293742ccf818188394b9a82972&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: hasansezertasan - count: 41 - avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 - url: https://github.com/hasansezertasan - login: alejsdev - count: 37 - avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=1ee3a9fbef27abc9448ef5951350f99c7d76f7af&v=4 + count: 38 + avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=9ca449ad5161af12766ddd1a22988e9b14315f5c&v=4 url: https://github.com/alejsdev - login: JarroVGIT count: 34 @@ -1059,6 +1035,10 @@ top_reviewers: count: 27 avatarUrl: https://avatars.githubusercontent.com/u/39375566?u=260ad6b1a4b34c07dbfa728da5e586f16f6d1824&v=4 url: https://github.com/komtaki +- login: YuriiMotov + count: 25 + avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 + url: https://github.com/YuriiMotov - login: Ryandaydev count: 25 avatarUrl: https://avatars.githubusercontent.com/u/4292423?u=48f68868db8886fce31a1d802c1003914c6cd7c6&v=4 @@ -1067,10 +1047,6 @@ top_reviewers: count: 24 avatarUrl: https://avatars.githubusercontent.com/u/16273730?u=095b66f243a2cd6a0aadba9a095009f8aaf18393&v=4 url: https://github.com/LorhanSohaky -- login: YuriiMotov - count: 24 - avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 - url: https://github.com/YuriiMotov - login: dmontagu count: 23 avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 @@ -1095,6 +1071,10 @@ top_reviewers: count: 19 avatarUrl: https://avatars.githubusercontent.com/u/63915557?u=47debaa860fd52c9b98c97ef357ddcec3b3fb399&v=4 url: https://github.com/0417taehyun +- login: JavierSanchezCastro + count: 19 + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro - login: Smlep count: 17 avatarUrl: https://avatars.githubusercontent.com/u/16785985?v=4 @@ -1103,6 +1083,10 @@ top_reviewers: count: 17 avatarUrl: https://avatars.githubusercontent.com/u/67154681?u=5d634834cc514028ea3f9115f7030b99a1f4d5a4&v=4 url: https://github.com/zy7y +- login: junah201 + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/75025529?u=2451c256e888fa2a06bcfc0646d09b87ddb6a945&v=4 + url: https://github.com/junah201 - login: peidrao count: 17 avatarUrl: https://avatars.githubusercontent.com/u/32584628?u=a66902b40c13647d0ed0e573d598128240a4dd04&v=4 @@ -1119,6 +1103,10 @@ top_reviewers: count: 16 avatarUrl: https://avatars.githubusercontent.com/u/1334088?u=9667041f5b15dc002b6f9665fda8c0412933ac04&v=4 url: https://github.com/axel584 +- login: codespearhead + count: 16 + avatarUrl: https://avatars.githubusercontent.com/u/72931357?u=0fce6b82219b604d58adb614a761556425579cb5&v=4 + url: https://github.com/codespearhead - login: Alexandrhub count: 16 avatarUrl: https://avatars.githubusercontent.com/u/119126536?u=9fc0d48f3307817bafecc5861eb2168401a6cb04&v=4 @@ -1127,6 +1115,14 @@ top_reviewers: count: 16 avatarUrl: https://avatars.githubusercontent.com/u/87962045?u=08e10fa516e844934f4b3fc7c38b33c61697e4a1&v=4 url: https://github.com/DevDae +- login: Aruelius + count: 16 + avatarUrl: https://avatars.githubusercontent.com/u/25380989?u=574f8cfcda3ea77a3f81884f6b26a97068e36a9d&v=4 + url: https://github.com/Aruelius +- login: OzgunCaglarArslan + count: 16 + avatarUrl: https://avatars.githubusercontent.com/u/86166426?v=4 + url: https://github.com/OzgunCaglarArslan - login: pedabraham count: 15 avatarUrl: https://avatars.githubusercontent.com/u/16860088?u=abf922a7b920bf8fdb7867d8b43e091f1e796178&v=4 @@ -1135,30 +1131,18 @@ top_reviewers: count: 15 avatarUrl: https://avatars.githubusercontent.com/u/63476957?u=6c86e59b48e0394d4db230f37fc9ad4d7e2c27c7&v=4 url: https://github.com/delhi09 -- login: Aruelius +- login: wdh99 count: 14 - avatarUrl: https://avatars.githubusercontent.com/u/25380989?u=574f8cfcda3ea77a3f81884f6b26a97068e36a9d&v=4 - url: https://github.com/Aruelius + avatarUrl: https://avatars.githubusercontent.com/u/108172295?u=8a8fb95d5afe3e0fa33257b2aecae88d436249eb&v=4 + url: https://github.com/wdh99 - login: sh0nk count: 13 avatarUrl: https://avatars.githubusercontent.com/u/6478810?u=af15d724875cec682ed8088a86d36b2798f981c0&v=4 url: https://github.com/sh0nk -- login: junah201 - count: 13 - avatarUrl: https://avatars.githubusercontent.com/u/75025529?u=2451c256e888fa2a06bcfc0646d09b87ddb6a945&v=4 - url: https://github.com/junah201 -- login: wdh99 - count: 13 - avatarUrl: https://avatars.githubusercontent.com/u/108172295?u=8a8fb95d5afe3e0fa33257b2aecae88d436249eb&v=4 - url: https://github.com/wdh99 - login: r0b2g1t count: 13 avatarUrl: https://avatars.githubusercontent.com/u/5357541?u=6428442d875d5d71aaa1bb38bb11c4be1a526bc2&v=4 url: https://github.com/r0b2g1t -- login: JavierSanchezCastro - count: 13 - avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 - url: https://github.com/JavierSanchezCastro - login: RunningIkkyu count: 12 avatarUrl: https://avatars.githubusercontent.com/u/31848542?u=494ecc298e3f26197495bb357ad0f57cfd5f7a32&v=4 @@ -1175,17 +1159,9 @@ top_reviewers: count: 11 avatarUrl: https://avatars.githubusercontent.com/u/46193920?u=789927ee09cfabd752d3bd554fa6baf4850d2777&v=4 url: https://github.com/solomein-sv -- login: dpinezich - count: 11 - avatarUrl: https://avatars.githubusercontent.com/u/3204540?u=a2e1465e3ee10d537614d513589607eddefde09f&v=4 - url: https://github.com/dpinezich -- login: mariacamilagl - count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/11489395?u=4adb6986bf3debfc2b8216ae701f2bd47d73da7d&v=4 - url: https://github.com/mariacamilagl top_translations_reviewers: - login: s111d - count: 143 + count: 146 avatarUrl: https://avatars.githubusercontent.com/u/4954856?v=4 url: https://github.com/s111d - login: Xewus @@ -1197,7 +1173,7 @@ top_translations_reviewers: avatarUrl: https://avatars.githubusercontent.com/u/41147016?u=55010621aece725aa702270b54fed829b6a1fe60&v=4 url: https://github.com/tokusumi - login: hasansezertasan - count: 84 + count: 91 avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 url: https://github.com/hasansezertasan - login: AlertRED @@ -1228,6 +1204,10 @@ top_translations_reviewers: count: 45 avatarUrl: https://avatars.githubusercontent.com/u/39375566?u=260ad6b1a4b34c07dbfa728da5e586f16f6d1824&v=4 url: https://github.com/komtaki +- login: alperiox + count: 42 + avatarUrl: https://avatars.githubusercontent.com/u/34214152?u=2c5acad3461d4dbc2d48371ba86cac56ae9b25cc&v=4 + url: https://github.com/alperiox - login: Winand count: 40 avatarUrl: https://avatars.githubusercontent.com/u/53390?u=bb0e71a2fc3910a8e0ee66da67c33de40ea695f8&v=4 @@ -1236,10 +1216,6 @@ top_translations_reviewers: count: 38 avatarUrl: https://avatars.githubusercontent.com/u/46193920?u=789927ee09cfabd752d3bd554fa6baf4850d2777&v=4 url: https://github.com/solomein-sv -- login: alperiox - count: 37 - avatarUrl: https://avatars.githubusercontent.com/u/34214152?u=2c5acad3461d4dbc2d48371ba86cac56ae9b25cc&v=4 - url: https://github.com/alperiox - login: lsglucas count: 36 avatarUrl: https://avatars.githubusercontent.com/u/61513630?u=320e43fe4dc7bc6efc64e9b8f325f8075634fd20&v=4 @@ -1264,6 +1240,10 @@ top_translations_reviewers: count: 32 avatarUrl: https://avatars.githubusercontent.com/u/132477732?v=4 url: https://github.com/romashevchenko +- login: wdh99 + count: 31 + avatarUrl: https://avatars.githubusercontent.com/u/108172295?u=8a8fb95d5afe3e0fa33257b2aecae88d436249eb&v=4 + url: https://github.com/wdh99 - login: LorhanSohaky count: 30 avatarUrl: https://avatars.githubusercontent.com/u/16273730?u=095b66f243a2cd6a0aadba9a095009f8aaf18393&v=4 @@ -1272,10 +1252,6 @@ top_translations_reviewers: count: 29 avatarUrl: https://avatars.githubusercontent.com/u/3127847?u=a08022b191ddbd0a6159b2981d9d878b6d5bb71f&v=4 url: https://github.com/cassiobotaro -- login: wdh99 - count: 29 - avatarUrl: https://avatars.githubusercontent.com/u/108172295?u=8a8fb95d5afe3e0fa33257b2aecae88d436249eb&v=4 - url: https://github.com/wdh99 - login: pedabraham count: 28 avatarUrl: https://avatars.githubusercontent.com/u/16860088?u=abf922a7b920bf8fdb7867d8b43e091f1e796178&v=4 @@ -1288,6 +1264,10 @@ top_translations_reviewers: count: 28 avatarUrl: https://avatars.githubusercontent.com/u/26196675?u=e2966887124e67932853df4f10f86cb526edc7b0&v=4 url: https://github.com/dedkot01 +- login: hsuanchi + count: 28 + avatarUrl: https://avatars.githubusercontent.com/u/24913710?u=0b094ae292292fee093818e37ceb645c114d2bff&v=4 + url: https://github.com/hsuanchi - login: dpinezich count: 28 avatarUrl: https://avatars.githubusercontent.com/u/3204540?u=a2e1465e3ee10d537614d513589607eddefde09f&v=4 @@ -1324,13 +1304,17 @@ top_translations_reviewers: count: 21 avatarUrl: https://avatars.githubusercontent.com/u/86262613?u=3c21606ab8d210a061a1673decff1e7d5592b380&v=4 url: https://github.com/AGolicyn +- login: OzgunCaglarArslan + count: 21 + avatarUrl: https://avatars.githubusercontent.com/u/86166426?v=4 + url: https://github.com/OzgunCaglarArslan - login: Attsun1031 count: 20 avatarUrl: https://avatars.githubusercontent.com/u/1175560?v=4 url: https://github.com/Attsun1031 - login: ycd count: 20 - avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=45aa6ef58220a3f1e8a3c3cd5f1b75a1a0a73347&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=29682e4b6ac7d5293742ccf818188394b9a82972&v=4 url: https://github.com/ycd - login: delhi09 count: 20 @@ -1350,8 +1334,12 @@ top_translations_reviewers: url: https://github.com/sattosan - login: ComicShrimp count: 18 - avatarUrl: https://avatars.githubusercontent.com/u/43503750?u=f440bc9062afb3c43b9b9c6cdfdcfe31d58699ef&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/43503750?u=d2fbf412e7730183ce91686ca48d4147e1b7dc74&v=4 url: https://github.com/ComicShrimp +- login: junah201 + count: 18 + avatarUrl: https://avatars.githubusercontent.com/u/75025529?u=2451c256e888fa2a06bcfc0646d09b87ddb6a945&v=4 + url: https://github.com/junah201 - login: simatheone count: 18 avatarUrl: https://avatars.githubusercontent.com/u/78508673?u=1b9658d9ee0bde33f56130dd52275493ddd38690&v=4 @@ -1360,23 +1348,11 @@ top_translations_reviewers: count: 18 avatarUrl: https://avatars.githubusercontent.com/u/36765187?u=c6e0ba571c1ccb6db9d94e62e4b8b5eda811a870&v=4 url: https://github.com/ivan-abc +- login: JavierSanchezCastro + count: 18 + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro - login: bezaca count: 17 avatarUrl: https://avatars.githubusercontent.com/u/69092910?u=4ac58eab99bd37d663f3d23551df96d4fbdbf760&v=4 url: https://github.com/bezaca -- login: lbmendes - count: 17 - avatarUrl: https://avatars.githubusercontent.com/u/80999926?u=646619e2f07ac5a7c3f65fe7834197461a4fff9f&v=4 - url: https://github.com/lbmendes -- login: rostik1410 - count: 17 - avatarUrl: https://avatars.githubusercontent.com/u/11443899?u=e26a635c2ba220467b308a326a579b8ccf4a8701&v=4 - url: https://github.com/rostik1410 -- login: spacesphere - count: 17 - avatarUrl: https://avatars.githubusercontent.com/u/34628304?u=cde91f6002dd33156e1bf8005f11a7a3ed76b790&v=4 - url: https://github.com/spacesphere -- login: panko - count: 17 - avatarUrl: https://avatars.githubusercontent.com/u/1569515?u=a84a5d255621ed82f8e1ca052f5f2eeb75997da2&v=4 - url: https://github.com/panko diff --git a/docs/en/data/sponsors.yml b/docs/en/data/sponsors.yml index 85ac30d6d..7fad270da 100644 --- a/docs/en/data/sponsors.yml +++ b/docs/en/data/sponsors.yml @@ -20,23 +20,29 @@ gold: - 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=banner%20january%2024 + - url: https://docs.withcoherence.com/configuration/frameworks/?utm_medium=advertising&utm_source=fastapi&utm_campaign=docs#fastapi-example 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://konghq.com/products/kong-konnect?utm_medium=referral&utm_source=github&utm_campaign=platform&utm_content=fast-api + title: Kong Konnect - API management platform + img: https://fastapi.tiangolo.com/img/sponsors/kong.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://fine.dev?ref=fastapibadge + title: "Fine's AI FastAPI Workflow: Effortlessly Deploy and Integrate FastAPI into Your Project" + img: https://fastapi.tiangolo.com/img/sponsors/fine.png silver: - - 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-v2.jpg - 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://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/ @@ -45,6 +51,9 @@ silver: - 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 bronze: - url: https://www.exoflare.com/open-source/?utm_source=FastAPI&utm_campaign=open_source title: Biosecurity risk assessments made easy. diff --git a/docs/en/data/sponsors_badge.yml b/docs/en/data/sponsors_badge.yml index 00cbec7d2..d8a41fbcb 100644 --- a/docs/en/data/sponsors_badge.yml +++ b/docs/en/data/sponsors_badge.yml @@ -28,3 +28,5 @@ logins: - bump-sh - andrew-propelauth - svix + - zuplo-oss + - Kong diff --git a/docs/en/docs/advanced/additional-responses.md b/docs/en/docs/advanced/additional-responses.md index 41b39c18e..88d27018c 100644 --- a/docs/en/docs/advanced/additional-responses.md +++ b/docs/en/docs/advanced/additional-responses.md @@ -224,7 +224,7 @@ 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: diff --git a/docs/en/docs/advanced/behind-a-proxy.md b/docs/en/docs/advanced/behind-a-proxy.md index b25c11b17..c17b024f9 100644 --- a/docs/en/docs/advanced/behind-a-proxy.md +++ b/docs/en/docs/advanced/behind-a-proxy.md @@ -22,7 +22,7 @@ Even though all your code is written assuming there's just `/app`. {!../../../docs_src/behind_a_proxy/tutorial001.py!} ``` -And the proxy would be **"stripping"** the **path prefix** on the fly before transmitting the request to Uvicorn, 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`. +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. @@ -63,7 +63,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` @@ -72,7 +72,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) ``` @@ -101,7 +101,7 @@ 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) ``` @@ -216,12 +216,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) ``` diff --git a/docs/en/docs/advanced/custom-response.md b/docs/en/docs/advanced/custom-response.md index 45c7c7bd5..1d12173a1 100644 --- a/docs/en/docs/advanced/custom-response.md +++ b/docs/en/docs/advanced/custom-response.md @@ -39,7 +39,7 @@ But if you are certain that the content that you are returning is **serializable And it will be documented as such in OpenAPI. !!! tip - The `ORJSONResponse` is currently only available in FastAPI, not in Starlette. + The `ORJSONResponse` is only available in FastAPI, not in Starlette. ## HTML Response @@ -149,10 +149,16 @@ 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`. +!!! info + 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. diff --git a/docs/en/docs/advanced/generate-clients.md b/docs/en/docs/advanced/generate-clients.md index fd9a73618..136ddb064 100644 --- a/docs/en/docs/advanced/generate-clients.md +++ b/docs/en/docs/advanced/generate-clients.md @@ -20,7 +20,7 @@ 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 and Stainless. There are also several other companies offering similar services that you can search and find online. 🤓 diff --git a/docs/en/docs/advanced/openapi-callbacks.md b/docs/en/docs/advanced/openapi-callbacks.md index 2785ee140..1ff51f077 100644 --- a/docs/en/docs/advanced/openapi-callbacks.md +++ b/docs/en/docs/advanced/openapi-callbacks.md @@ -172,7 +172,7 @@ Now use the parameter `callbacks` in *your API's path operation decorator* to pa ### 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 "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..f7f43b357 100644 --- a/docs/en/docs/advanced/openapi-webhooks.md +++ b/docs/en/docs/advanced/openapi-webhooks.md @@ -44,7 +44,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 c5544a78b..35f7d1b8d 100644 --- a/docs/en/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/en/docs/advanced/path-operation-advanced-configuration.md @@ -187,6 +187,6 @@ And then in our code, we parse that YAML content directly, and then we are again 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()`. !!! tip - Here we re-use the same Pydantic model. + Here we reuse the same Pydantic model. But the same way, we could have validated it in some other way. diff --git a/docs/en/docs/advanced/security/oauth2-scopes.md b/docs/en/docs/advanced/security/oauth2-scopes.md index b93d2991c..9a9c0dff9 100644 --- a/docs/en/docs/advanced/security/oauth2-scopes.md +++ b/docs/en/docs/advanced/security/oauth2-scopes.md @@ -58,19 +58,19 @@ First, let's quickly see the parts that change from the examples in the main **T === "Python 3.10+" - ```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155" + ```Python hl_lines="5 9 13 47 65 106 108-116 122-125 129-135 140 156" {!> ../../../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" + ```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" {!> ../../../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" + ```Python hl_lines="2 5 9 13 48 66 107 109-117 123-126 130-136 141 157" {!> ../../../docs_src/security/tutorial005_an.py!} ``` @@ -79,7 +79,7 @@ First, let's quickly see the parts that change from the examples in the main **T !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="3 7 11 45 63 104 106-114 120-123 127-133 138 154" + ```Python hl_lines="4 8 12 46 64 105 107-115 121-124 128-134 139 155" {!> ../../../docs_src/security/tutorial005_py310.py!} ``` @@ -88,7 +88,7 @@ First, let's quickly see the parts that change from the examples in the main **T !!! 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" + ```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" {!> ../../../docs_src/security/tutorial005_py39.py!} ``` @@ -97,7 +97,7 @@ First, let's quickly see the parts that change from the examples in the main **T !!! 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" + ```Python hl_lines="2 5 9 13 47 65 106 108-116 122-125 129-135 140 156" {!> ../../../docs_src/security/tutorial005.py!} ``` @@ -111,19 +111,19 @@ The `scopes` parameter receives a `dict` with each scope as a key and the descri === "Python 3.10+" - ```Python hl_lines="62-65" + ```Python hl_lines="63-66" {!> ../../../docs_src/security/tutorial005_an_py310.py!} ``` === "Python 3.9+" - ```Python hl_lines="62-65" + ```Python hl_lines="63-66" {!> ../../../docs_src/security/tutorial005_an_py39.py!} ``` === "Python 3.8+" - ```Python hl_lines="63-66" + ```Python hl_lines="64-67" {!> ../../../docs_src/security/tutorial005_an.py!} ``` @@ -132,7 +132,7 @@ The `scopes` parameter receives a `dict` with each scope as a key and the descri !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="61-64" + ```Python hl_lines="62-65" {!> ../../../docs_src/security/tutorial005_py310.py!} ``` @@ -142,7 +142,7 @@ The `scopes` parameter receives a `dict` with each scope as a key and the descri !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="62-65" + ```Python hl_lines="63-66" {!> ../../../docs_src/security/tutorial005_py39.py!} ``` @@ -151,7 +151,7 @@ The `scopes` parameter receives a `dict` with each scope as a key and the descri !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="62-65" + ```Python hl_lines="63-66" {!> ../../../docs_src/security/tutorial005.py!} ``` @@ -178,19 +178,19 @@ And we return the scopes as part of the JWT token. === "Python 3.10+" - ```Python hl_lines="155" + ```Python hl_lines="156" {!> ../../../docs_src/security/tutorial005_an_py310.py!} ``` === "Python 3.9+" - ```Python hl_lines="155" + ```Python hl_lines="156" {!> ../../../docs_src/security/tutorial005_an_py39.py!} ``` === "Python 3.8+" - ```Python hl_lines="156" + ```Python hl_lines="157" {!> ../../../docs_src/security/tutorial005_an.py!} ``` @@ -199,7 +199,7 @@ And we return the scopes as part of the JWT token. !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="154" + ```Python hl_lines="155" {!> ../../../docs_src/security/tutorial005_py310.py!} ``` @@ -208,7 +208,7 @@ And we return the scopes as part of the JWT token. !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="155" + ```Python hl_lines="156" {!> ../../../docs_src/security/tutorial005_py39.py!} ``` @@ -217,7 +217,7 @@ And we return the scopes as part of the JWT token. !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="155" + ```Python hl_lines="156" {!> ../../../docs_src/security/tutorial005.py!} ``` @@ -244,19 +244,19 @@ In this case, it requires the scope `me` (it could require more than one scope). === "Python 3.10+" - ```Python hl_lines="4 139 170" + ```Python hl_lines="5 140 171" {!> ../../../docs_src/security/tutorial005_an_py310.py!} ``` === "Python 3.9+" - ```Python hl_lines="4 139 170" + ```Python hl_lines="5 140 171" {!> ../../../docs_src/security/tutorial005_an_py39.py!} ``` === "Python 3.8+" - ```Python hl_lines="4 140 171" + ```Python hl_lines="5 141 172" {!> ../../../docs_src/security/tutorial005_an.py!} ``` @@ -265,7 +265,7 @@ In this case, it requires the scope `me` (it could require more than one scope). !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="3 138 167" + ```Python hl_lines="4 139 168" {!> ../../../docs_src/security/tutorial005_py310.py!} ``` @@ -274,7 +274,7 @@ In this case, it requires the scope `me` (it could require more than one scope). !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="4 139 168" + ```Python hl_lines="5 140 169" {!> ../../../docs_src/security/tutorial005_py39.py!} ``` @@ -283,7 +283,7 @@ In this case, it requires the scope `me` (it could require more than one scope). !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="4 139 168" + ```Python hl_lines="5 140 169" {!> ../../../docs_src/security/tutorial005.py!} ``` @@ -310,19 +310,19 @@ This `SecurityScopes` class is similar to `Request` (`Request` was used to get t === "Python 3.10+" - ```Python hl_lines="8 105" + ```Python hl_lines="9 106" {!> ../../../docs_src/security/tutorial005_an_py310.py!} ``` === "Python 3.9+" - ```Python hl_lines="8 105" + ```Python hl_lines="9 106" {!> ../../../docs_src/security/tutorial005_an_py39.py!} ``` === "Python 3.8+" - ```Python hl_lines="8 106" + ```Python hl_lines="9 107" {!> ../../../docs_src/security/tutorial005_an.py!} ``` @@ -331,7 +331,7 @@ This `SecurityScopes` class is similar to `Request` (`Request` was used to get t !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="7 104" + ```Python hl_lines="8 105" {!> ../../../docs_src/security/tutorial005_py310.py!} ``` @@ -340,7 +340,7 @@ This `SecurityScopes` class is similar to `Request` (`Request` was used to get t !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="8 105" + ```Python hl_lines="9 106" {!> ../../../docs_src/security/tutorial005_py39.py!} ``` @@ -349,7 +349,7 @@ This `SecurityScopes` class is similar to `Request` (`Request` was used to get t !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="8 105" + ```Python hl_lines="9 106" {!> ../../../docs_src/security/tutorial005.py!} ``` @@ -361,25 +361,25 @@ 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" + ```Python hl_lines="106 108-116" {!> ../../../docs_src/security/tutorial005_an_py310.py!} ``` === "Python 3.9+" - ```Python hl_lines="105 107-115" + ```Python hl_lines="106 108-116" {!> ../../../docs_src/security/tutorial005_an_py39.py!} ``` === "Python 3.8+" - ```Python hl_lines="106 108-116" + ```Python hl_lines="107 109-117" {!> ../../../docs_src/security/tutorial005_an.py!} ``` @@ -388,7 +388,7 @@ In this exception, we include the scopes required (if any) as a string separated !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="104 106-114" + ```Python hl_lines="105 107-115" {!> ../../../docs_src/security/tutorial005_py310.py!} ``` @@ -397,7 +397,7 @@ In this exception, we include the scopes required (if any) as a string separated !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="105 107-115" + ```Python hl_lines="106 108-116" {!> ../../../docs_src/security/tutorial005_py39.py!} ``` @@ -406,7 +406,7 @@ In this exception, we include the scopes required (if any) as a string separated !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="105 107-115" + ```Python hl_lines="106 108-116" {!> ../../../docs_src/security/tutorial005.py!} ``` @@ -426,19 +426,19 @@ We also verify that we have a user with that username, and if not, we raise that === "Python 3.10+" - ```Python hl_lines="46 116-127" + ```Python hl_lines="47 117-128" {!> ../../../docs_src/security/tutorial005_an_py310.py!} ``` === "Python 3.9+" - ```Python hl_lines="46 116-127" + ```Python hl_lines="47 117-128" {!> ../../../docs_src/security/tutorial005_an_py39.py!} ``` === "Python 3.8+" - ```Python hl_lines="47 117-128" + ```Python hl_lines="48 118-129" {!> ../../../docs_src/security/tutorial005_an.py!} ``` @@ -447,7 +447,7 @@ We also verify that we have a user with that username, and if not, we raise that !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="45 115-126" + ```Python hl_lines="46 116-127" {!> ../../../docs_src/security/tutorial005_py310.py!} ``` @@ -456,7 +456,7 @@ We also verify that we have a user with that username, and if not, we raise that !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="46 116-127" + ```Python hl_lines="47 117-128" {!> ../../../docs_src/security/tutorial005_py39.py!} ``` @@ -465,7 +465,7 @@ We also verify that we have a user with that username, and if not, we raise that !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="46 116-127" + ```Python hl_lines="47 117-128" {!> ../../../docs_src/security/tutorial005.py!} ``` @@ -477,19 +477,19 @@ For this, we use `security_scopes.scopes`, that contains a `list` with all these === "Python 3.10+" - ```Python hl_lines="128-134" + ```Python hl_lines="129-135" {!> ../../../docs_src/security/tutorial005_an_py310.py!} ``` === "Python 3.9+" - ```Python hl_lines="128-134" + ```Python hl_lines="129-135" {!> ../../../docs_src/security/tutorial005_an_py39.py!} ``` === "Python 3.8+" - ```Python hl_lines="129-135" + ```Python hl_lines="130-136" {!> ../../../docs_src/security/tutorial005_an.py!} ``` @@ -498,7 +498,7 @@ For this, we use `security_scopes.scopes`, that contains a `list` with all these !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="127-133" + ```Python hl_lines="128-134" {!> ../../../docs_src/security/tutorial005_py310.py!} ``` @@ -507,7 +507,7 @@ For this, we use `security_scopes.scopes`, that contains a `list` with all these !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="128-134" + ```Python hl_lines="129-135" {!> ../../../docs_src/security/tutorial005_py39.py!} ``` @@ -516,7 +516,7 @@ For this, we use `security_scopes.scopes`, that contains a `list` with all these !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="128-134" + ```Python hl_lines="129-135" {!> ../../../docs_src/security/tutorial005.py!} ``` diff --git a/docs/en/docs/advanced/settings.md b/docs/en/docs/advanced/settings.md index 8f72bf63a..56af4f441 100644 --- a/docs/en/docs/advanced/settings.md +++ b/docs/en/docs/advanced/settings.md @@ -199,7 +199,7 @@ 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) ``` @@ -369,7 +369,7 @@ Here we define the config `env_file` inside of your Pydantic `Settings` class, a ### 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: diff --git a/docs/en/docs/advanced/templates.md b/docs/en/docs/advanced/templates.md index 6055b3017..4a577215a 100644 --- a/docs/en/docs/advanced/templates.md +++ b/docs/en/docs/advanced/templates.md @@ -23,7 +23,7 @@ $ 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. diff --git a/docs/en/docs/advanced/websockets.md b/docs/en/docs/advanced/websockets.md index b8dfab1d1..3b6471dd5 100644 --- a/docs/en/docs/advanced/websockets.md +++ b/docs/en/docs/advanced/websockets.md @@ -72,7 +72,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) ``` @@ -160,7 +160,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) ``` diff --git a/docs/en/docs/advanced/wsgi.md b/docs/en/docs/advanced/wsgi.md index 852e25019..f07609ed6 100644 --- a/docs/en/docs/advanced/wsgi.md +++ b/docs/en/docs/advanced/wsgi.md @@ -22,7 +22,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/async.md b/docs/en/docs/async.md index a0c00933a..793d691e3 100644 --- a/docs/en/docs/async.md +++ b/docs/en/docs/async.md @@ -222,7 +222,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 diff --git a/docs/en/docs/css/custom.css b/docs/en/docs/css/custom.css index 386aa9d7e..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; diff --git a/docs/en/docs/css/termynal.css b/docs/en/docs/css/termynal.css index 406c00897..af2fbe670 100644 --- a/docs/en/docs/css/termynal.css +++ b/docs/en/docs/css/termynal.css @@ -26,6 +26,7 @@ position: relative; -webkit-box-sizing: border-box; box-sizing: border-box; + line-height: 1.2; } [data-termynal]:before { diff --git a/docs/en/docs/deployment/concepts.md b/docs/en/docs/deployment/concepts.md index b771ae663..9701c67d8 100644 --- a/docs/en/docs/deployment/concepts.md +++ b/docs/en/docs/deployment/concepts.md @@ -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 to use `fastapi run`, Uvicorn (or similar) manually, the same way you do when developing locally. And it will work and will be useful **during development**. diff --git a/docs/en/docs/deployment/docker.md b/docs/en/docs/deployment/docker.md index 467ba72de..5cd24eb46 100644 --- a/docs/en/docs/deployment/docker.md +++ b/docs/en/docs/deployment/docker.md @@ -21,10 +21,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 +70,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. @@ -113,9 +113,8 @@ You would of course use the same ideas you read in [About FastAPI versions](vers 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>=0.112.0,<0.113.0 +pydantic>=2.7.0,<3.0.0 ``` And you would normally install those package dependencies with `pip`, for example: @@ -125,7 +124,7 @@ 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 ```
@@ -133,8 +132,6 @@ Successfully installed fastapi pydantic uvicorn !!! info There are other formats and tools to define and install package dependencies. - I'll show you an example using Poetry later in a section below. 👇 - ### Create the **FastAPI** Code * Create an `app` directory and enter it. @@ -180,7 +177,7 @@ RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt COPY ./app /code/app # (6) -CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] +CMD ["fastapi", "run", "app/main.py", "--port", "80"] ``` 1. Start from the official Python base image. @@ -214,14 +211,12 @@ 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. 👆 @@ -238,10 +233,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 +249,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: @@ -362,14 +357,14 @@ RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt COPY ./main.py /code/ # (2) -CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] +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 @@ -626,7 +621,7 @@ RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt COPY ./app /code/app # (11) -CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] +CMD ["fastapi", "run", "app/main.py", "--port", "80"] ``` 1. This is the first stage, it is named `requirements-stage`. @@ -655,7 +650,7 @@ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] 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`. +11. Use the `fastapi run` command to run your app. !!! tip Click the bubble numbers to see what each line does. @@ -677,7 +672,7 @@ Then in the next (and final) stage you would build the image more or less in the 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"] +CMD ["fastapi", "run", "app/main.py", "--proxy-headers", "--port", "80"] ``` ## Recap diff --git a/docs/en/docs/deployment/manually.md b/docs/en/docs/deployment/manually.md index b10a3686d..51989d819 100644 --- a/docs/en/docs/deployment/manually.md +++ b/docs/en/docs/deployment/manually.md @@ -1,11 +1,71 @@ -# 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: + +
+ +```console +$ fastapi run 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 - Production mode ───────────╮ + │ │ + │ Serving at: http://0.0.0.0:8000 │ + │ │ + │ API docs: http://0.0.0.0:8000/docs │ + │ │ + │ Running in production mode, for development use: │ + │ │ + fastapi dev + │ │ + ╰─────────────────────────────────────────────────────╯ + +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) +``` + +
+ +That would work for most of the cases. 😎 + +You could use that command for example to start your **FastAPI** app in a container, in a server, etc. + +## ASGI Servers + +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. + +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. + +There are several alternatives, including: * Uvicorn: a high performance ASGI server. -* Hypercorn: an ASGI server compatible with HTTP/2 and Trio among other features. +* 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 @@ -20,7 +80,9 @@ When referring to the remote machine, it's common to call it **server**, but als ## Install the Server Program -You can install an ASGI compatible server with: +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: === "Uvicorn" @@ -41,9 +103,11 @@ You can install an ASGI compatible server with: That including `uvloop`, the high-performance drop-in replacement for `asyncio`, that provides the big concurrency performance boost. + When you install FastAPI with something like `pip install fastapi` you already get `uvicorn[standard]` as well. + === "Hypercorn" - * Hypercorn, an ASGI server also compatible with HTTP/2. + * Hypercorn, an ASGI server also compatible with HTTP/2.
@@ -59,7 +123,7 @@ You can install an ASGI compatible server with: ## Run the Server Program -You can then run your application the same way you have done in the tutorials, but without the `--reload` option, e.g.: +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: === "Uvicorn" @@ -85,8 +149,20 @@ You can then run your application the same way you have done in the tutorials, b
+!!! note + 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()`. + + It is equivalent to: + + ```Python + from main import app + ``` + !!! warning - Remember to remove the `--reload` option if you were using it. + Uvicorn and others support a `--reload` option that is useful during development. The `--reload` option consumes much more resources, is more unstable, etc. diff --git a/docs/en/docs/fastapi-cli.md b/docs/en/docs/fastapi-cli.md new file mode 100644 index 000000000..a6facde3a --- /dev/null +++ b/docs/en/docs/fastapi-cli.md @@ -0,0 +1,80 @@ +# 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`), 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 +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. +``` + +
+ +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/features.md b/docs/en/docs/features.md index 6f0e74b3d..8afa13a98 100644 --- a/docs/en/docs/features.md +++ b/docs/en/docs/features.md @@ -30,7 +30,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}. @@ -77,7 +77,7 @@ my_second_user: User = User(**second_user_data) 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. 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..053e5eacd 100644 --- a/docs/en/docs/how-to/custom-docs-ui-assets.md +++ b/docs/en/docs/how-to/custom-docs-ui-assets.md @@ -26,7 +26,7 @@ To disable them, set their URLs to `None` when creating your `FastAPI` app: 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. @@ -96,8 +96,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: @@ -163,7 +163,7 @@ To disable them, set their URLs to `None` when creating your `FastAPI` app: 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. diff --git a/docs/en/docs/how-to/graphql.md b/docs/en/docs/how-to/graphql.md index 154606406..d5a5826f1 100644 --- a/docs/en/docs/how-to/graphql.md +++ b/docs/en/docs/how-to/graphql.md @@ -18,7 +18,7 @@ Here are some of the **GraphQL** libraries that have **ASGI** support. You could * 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 diff --git a/docs/en/docs/how-to/nosql-databases-couchbase.md b/docs/en/docs/how-to/nosql-databases-couchbase.md index 563318984..18e3f4b7e 100644 --- a/docs/en/docs/how-to/nosql-databases-couchbase.md +++ b/docs/en/docs/how-to/nosql-databases-couchbase.md @@ -108,7 +108,7 @@ Now create a function that will: * 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: +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 reuse it in multiple parts and also add unit tests for it: ```Python hl_lines="36-42" {!../../../docs_src/nosql_databases/tutorial001.py!} 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/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/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/index.md b/docs/en/docs/index.md index a5ed8b330..8b54f175f 100644 --- a/docs/en/docs/index.md +++ b/docs/en/docs/index.md @@ -36,7 +36,7 @@ hide: --- -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: @@ -124,8 +124,6 @@ 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. @@ -143,18 +141,6 @@ $ pip install fastapi
-You will also need an ASGI server, for production such as Uvicorn or Hypercorn. - -
- -```console -$ pip install "uvicorn[standard]" - ----> 100% -``` - -
- ## Example ### Create it @@ -215,11 +201,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. ``` @@ -227,13 +226,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.
@@ -306,7 +305,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 @@ -340,7 +339,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`: @@ -450,7 +449,7 @@ Independent TechEmpower benchmarks show **FastAPI** applications running under U To understand more about it, see the section Benchmarks. -## Optional Dependencies +## Dependencies Used by Pydantic: @@ -463,16 +462,36 @@ 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). Used by FastAPI / Starlette: * uvicorn - for the server that loads and serves your application. +* `fastapi-cli` - to provide the `fastapi` command. + +When you install `fastapi` it comes these standard dependencies. + +Additional optional dependencies: + * orjson - Required if you want to use `ORJSONResponse`. * ujson - Required if you want to use `UJSONResponse`. -You can install all of these with `pip install "fastapi[all]"`. +## `fastapi-slim` + +If you don't want the extra standard optional dependencies, install `fastapi-slim` instead. + +When you install with: + +```bash +pip install fastapi +``` + +...it includes the same code and dependencies as: + +```bash +pip install "fastapi-slim[standard]" +``` + +The standard extra dependencies are the ones mentioned above. ## License diff --git a/docs/en/docs/js/custom.js b/docs/en/docs/js/custom.js index 8e3be4c13..0008db49e 100644 --- a/docs/en/docs/js/custom.js +++ b/docs/en/docs/js/custom.js @@ -35,7 +35,7 @@ function setupTermynal() { function createTermynals() { document - .querySelectorAll(`.${termynalActivateClass} .highlight`) + .querySelectorAll(`.${termynalActivateClass} .highlight code`) .forEach(node => { const text = node.textContent; const lines = text.split("\n"); diff --git a/docs/en/docs/python-types.md b/docs/en/docs/python-types.md index 3e8267aea..20ffcdccc 100644 --- a/docs/en/docs/python-types.md +++ b/docs/en/docs/python-types.md @@ -476,7 +476,7 @@ You will see a lot more of all this in practice in the [Tutorial - User Guide](t ## Type Hints with Metadata Annotations -Python also has a feature that allows putting **additional metadata** in these type hints using `Annotated`. +Python also has a feature that allows putting **additional metadata** in these type hints using `Annotated`. === "Python 3.9+" diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 636ed04dd..7872e2fbe 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,15 +9,172 @@ hide: ### Docs +* 📝 Update Speakeasy URL. PR [#11871](https://github.com/tiangolo/fastapi/pull/11871) by [@ndimares](https://github.com/ndimares). + +### Translations + +* 🌐 Add Portuguese translation for `docs/pt/docs/reference/background.md`. PR [#11849](https://github.com/tiangolo/fastapi/pull/11849) by [@lucasbalieiro](https://github.com/lucasbalieiro). +* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#11848](https://github.com/tiangolo/fastapi/pull/11848) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). +* 🌐 Add Portuguese translation for `docs/pt/docs/reference/apirouter.md`. PR [#11843](https://github.com/tiangolo/fastapi/pull/11843) by [@lucasbalieiro](https://github.com/lucasbalieiro). + +### Internal + +* 🔧 Update sponsors: remove TalkPython. PR [#11861](https://github.com/tiangolo/fastapi/pull/11861) by [@tiangolo](https://github.com/tiangolo). +* 🔨 Update docs Termynal scripts to not include line nums for local dev. PR [#11854](https://github.com/tiangolo/fastapi/pull/11854) by [@tiangolo](https://github.com/tiangolo). + +## 0.111.1 + +### Upgrades + +* ➖ Remove `orjson` and `ujson` from default dependencies. PR [#11842](https://github.com/tiangolo/fastapi/pull/11842) by [@tiangolo](https://github.com/tiangolo). + * These dependencies are still installed when you install with `pip install "fastapi[all]"`. But they not included in `pip install fastapi`. +* 📝 Restored Swagger-UI links to use the latest version possible. PR [#11459](https://github.com/tiangolo/fastapi/pull/11459) by [@UltimateLobster](https://github.com/UltimateLobster). + +### Docs + +* ✏️ Rewording in `docs/en/docs/fastapi-cli.md`. PR [#11716](https://github.com/tiangolo/fastapi/pull/11716) by [@alejsdev](https://github.com/alejsdev). +* 📝 Update Hypercorn links in all the docs. PR [#11744](https://github.com/tiangolo/fastapi/pull/11744) by [@kittydoor](https://github.com/kittydoor). +* 📝 Update docs with Ariadne reference from Starlette to FastAPI. PR [#11797](https://github.com/tiangolo/fastapi/pull/11797) by [@DamianCzajkowski](https://github.com/DamianCzajkowski). +* 📝 Update fastapi instrumentation external link. PR [#11317](https://github.com/tiangolo/fastapi/pull/11317) by [@softwarebloat](https://github.com/softwarebloat). +* ✏️ Fix links to alembic example repo in docs. PR [#11628](https://github.com/tiangolo/fastapi/pull/11628) by [@augiwan](https://github.com/augiwan). +* ✏️ Update `docs/en/docs/fastapi-cli.md`. PR [#11715](https://github.com/tiangolo/fastapi/pull/11715) by [@alejsdev](https://github.com/alejsdev). +* 📝 Update External Links . PR [#11500](https://github.com/tiangolo/fastapi/pull/11500) by [@devon2018](https://github.com/devon2018). +* 📝 Add External Link: Tutorial de FastAPI, ¿el mejor framework de Python?. PR [#11618](https://github.com/tiangolo/fastapi/pull/11618) by [@EduardoZepeda](https://github.com/EduardoZepeda). +* 📝 Fix typo in `docs/en/docs/tutorial/body-multiple-params.md`. PR [#11698](https://github.com/tiangolo/fastapi/pull/11698) by [@mwb-u](https://github.com/mwb-u). +* 📝 Add External Link: Deploy a Serverless FastAPI App with Neon Postgres and AWS App Runner at any scale. PR [#11633](https://github.com/tiangolo/fastapi/pull/11633) by [@ananis25](https://github.com/ananis25). +* 📝 Update `security/first-steps.md`. PR [#11674](https://github.com/tiangolo/fastapi/pull/11674) by [@alejsdev](https://github.com/alejsdev). +* 📝 Update `security/first-steps.md`. PR [#11673](https://github.com/tiangolo/fastapi/pull/11673) by [@alejsdev](https://github.com/alejsdev). +* 📝 Update note in `path-params-numeric-validations.md`. PR [#11672](https://github.com/tiangolo/fastapi/pull/11672) by [@alejsdev](https://github.com/alejsdev). +* 📝 Tweak intro docs about `Annotated` and `Query()` params. PR [#11664](https://github.com/tiangolo/fastapi/pull/11664) by [@tiangolo](https://github.com/tiangolo). +* 📝 Update JWT auth documentation to use PyJWT instead of pyhon-jose. PR [#11589](https://github.com/tiangolo/fastapi/pull/11589) by [@estebanx64](https://github.com/estebanx64). +* 📝 Update docs. PR [#11603](https://github.com/tiangolo/fastapi/pull/11603) by [@alejsdev](https://github.com/alejsdev). +* ✏️ Fix typo: convert every 're-use' to 'reuse'.. PR [#11598](https://github.com/tiangolo/fastapi/pull/11598) by [@hasansezertasan](https://github.com/hasansezertasan). +* ✏️ Fix typo in `fastapi/applications.py`. PR [#11593](https://github.com/tiangolo/fastapi/pull/11593) by [@petarmaric](https://github.com/petarmaric). +* ✏️ Fix link in `fastapi-cli.md`. PR [#11524](https://github.com/tiangolo/fastapi/pull/11524) by [@svlandeg](https://github.com/svlandeg). + +### Translations + +* 🌐 Add Spanish translation for `docs/es/docs/how-to/graphql.md`. PR [#11697](https://github.com/tiangolo/fastapi/pull/11697) by [@camigomezdev](https://github.com/camigomezdev). +* 🌐 Add Portuguese translation for `docs/pt/docs/reference/index.md`. PR [#11840](https://github.com/tiangolo/fastapi/pull/11840) by [@lucasbalieiro](https://github.com/lucasbalieiro). +* 🌐 Fix link in German translation. PR [#11836](https://github.com/tiangolo/fastapi/pull/11836) by [@anitahammer](https://github.com/anitahammer). +* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/sub-dependencies.md`. PR [#11792](https://github.com/tiangolo/fastapi/pull/11792) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). +* 🌐 Add Turkish translation for `docs/tr/docs/tutorial/request-forms.md`. PR [#11553](https://github.com/tiangolo/fastapi/pull/11553) by [@hasansezertasan](https://github.com/hasansezertasan). +* 🌐 Add Portuguese translation for `docs/pt/docs/reference/exceptions.md`. PR [#11834](https://github.com/tiangolo/fastapi/pull/11834) by [@lucasbalieiro](https://github.com/lucasbalieiro). +* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/global-dependencies.md`. PR [#11826](https://github.com/tiangolo/fastapi/pull/11826) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). +* 🌐 Add Portuguese translation for `docs/pt/docs/how-to/general.md`. PR [#11825](https://github.com/tiangolo/fastapi/pull/11825) by [@lucasbalieiro](https://github.com/lucasbalieiro). +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/async-tests.md`. PR [#11808](https://github.com/tiangolo/fastapi/pull/11808) by [@ceb10n](https://github.com/ceb10n). +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/first-steps.md`. PR [#11809](https://github.com/tiangolo/fastapi/pull/11809) by [@vkhoroshchak](https://github.com/vkhoroshchak). +* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-operators.md`. PR [#11804](https://github.com/tiangolo/fastapi/pull/11804) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). +* 🌐 Add Chinese translation for `docs/zh/docs/fastapi-cli.md`. PR [#11786](https://github.com/tiangolo/fastapi/pull/11786) by [@logan2d5](https://github.com/logan2d5). +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/openapi-webhooks.md`. PR [#11791](https://github.com/tiangolo/fastapi/pull/11791) by [@ceb10n](https://github.com/ceb10n). +* 🌐 Update Chinese translation for `docs/tutorial/security/oauth2-jwt.md`. PR [#11781](https://github.com/tiangolo/fastapi/pull/11781) by [@logan2d5](https://github.com/logan2d5). +* 📝 Fix image missing in French translation for `docs/fr/docs/async.md` . PR [#11787](https://github.com/tiangolo/fastapi/pull/11787) by [@pe-brian](https://github.com/pe-brian). +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/advanced-dependencies.md`. PR [#11775](https://github.com/tiangolo/fastapi/pull/11775) by [@ceb10n](https://github.com/ceb10n). +* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#11768](https://github.com/tiangolo/fastapi/pull/11768) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/additional-status-codes.md`. PR [#11753](https://github.com/tiangolo/fastapi/pull/11753) by [@ceb10n](https://github.com/ceb10n). +* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/dependencies/index.md`. PR [#11757](https://github.com/tiangolo/fastapi/pull/11757) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/settings.md`. PR [#11739](https://github.com/tiangolo/fastapi/pull/11739) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). +* 🌐 Add French translation for `docs/fr/docs/learn/index.md`. PR [#11712](https://github.com/tiangolo/fastapi/pull/11712) by [@benjaminvandammeholberton](https://github.com/benjaminvandammeholberton). +* 🌐 Add Portuguese translation for `docs/pt/docs/how-to/index.md`. PR [#11731](https://github.com/tiangolo/fastapi/pull/11731) by [@vhsenna](https://github.com/vhsenna). +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/additional-responses.md`. PR [#11736](https://github.com/tiangolo/fastapi/pull/11736) by [@ceb10n](https://github.com/ceb10n). +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/benchmarks.md`. PR [#11713](https://github.com/tiangolo/fastapi/pull/11713) by [@ceb10n](https://github.com/ceb10n). +* 🌐 Fix Korean translation for `docs/ko/docs/tutorial/response-status-code.md`. PR [#11718](https://github.com/tiangolo/fastapi/pull/11718) by [@nayeonkinn](https://github.com/nayeonkinn). +* 🌐 Add Korean translation for `docs/ko/docs/tutorial/extra-data-types.md`. PR [#11711](https://github.com/tiangolo/fastapi/pull/11711) by [@nayeonkinn](https://github.com/nayeonkinn). +* 🌐 Fix Korean translation for `docs/ko/docs/tutorial/body-nested-models.md`. PR [#11710](https://github.com/tiangolo/fastapi/pull/11710) by [@nayeonkinn](https://github.com/nayeonkinn). +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/fastapi-cli.md`. PR [#11641](https://github.com/tiangolo/fastapi/pull/11641) by [@ayr-ton](https://github.com/ayr-ton). +* 🌐 Add Traditional Chinese translation for `docs/zh-hant/docs/fastapi-people.md`. PR [#11639](https://github.com/tiangolo/fastapi/pull/11639) by [@hsuanchi](https://github.com/hsuanchi). +* 🌐 Add Turkish translation for `docs/tr/docs/advanced/index.md`. PR [#11606](https://github.com/tiangolo/fastapi/pull/11606) by [@hasansezertasan](https://github.com/hasansezertasan). +* 🌐 Add Turkish translation for `docs/tr/docs/deployment/cloud.md`. PR [#11610](https://github.com/tiangolo/fastapi/pull/11610) by [@hasansezertasan](https://github.com/hasansezertasan). +* 🌐 Add Turkish translation for `docs/tr/docs/advanced/security/index.md`. PR [#11609](https://github.com/tiangolo/fastapi/pull/11609) by [@hasansezertasan](https://github.com/hasansezertasan). +* 🌐 Add Turkish translation for `docs/tr/docs/advanced/testing-websockets.md`. PR [#11608](https://github.com/tiangolo/fastapi/pull/11608) by [@hasansezertasan](https://github.com/hasansezertasan). +* 🌐 Add Turkish translation for `docs/tr/docs/how-to/general.md`. PR [#11607](https://github.com/tiangolo/fastapi/pull/11607) by [@hasansezertasan](https://github.com/hasansezertasan). +* 🌐 Update Chinese translation for `docs/zh/docs/advanced/templates.md`. PR [#11620](https://github.com/tiangolo/fastapi/pull/11620) by [@chaoless](https://github.com/chaoless). +* 🌐 Add Turkish translation for `docs/tr/docs/deployment/index.md`. PR [#11605](https://github.com/tiangolo/fastapi/pull/11605) by [@hasansezertasan](https://github.com/hasansezertasan). +* 🌐 Add Turkish translation for `docs/tr/docs/tutorial/static-files.md`. PR [#11599](https://github.com/tiangolo/fastapi/pull/11599) by [@hasansezertasan](https://github.com/hasansezertasan). +* 🌐 Polish translation for `docs/pl/docs/fastapi-people.md`. PR [#10196](https://github.com/tiangolo/fastapi/pull/10196) by [@isulim](https://github.com/isulim). +* 🌐 Add Turkish translation for `docs/tr/docs/advanced/wsgi.md`. PR [#11575](https://github.com/tiangolo/fastapi/pull/11575) by [@hasansezertasan](https://github.com/hasansezertasan). +* 🌐 Add Turkish translation for `docs/tr/docs/tutorial/cookie-params.md`. PR [#11561](https://github.com/tiangolo/fastapi/pull/11561) by [@hasansezertasan](https://github.com/hasansezertasan). +* 🌐 Add Russian translation for `docs/ru/docs/about/index.md`. PR [#10961](https://github.com/tiangolo/fastapi/pull/10961) by [@s111d](https://github.com/s111d). +* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/sql-databases.md`. PR [#11539](https://github.com/tiangolo/fastapi/pull/11539) by [@chaoless](https://github.com/chaoless). +* 🌐 Add Chinese translation for `docs/zh/docs/how-to/configure-swagger-ui.md`. PR [#11501](https://github.com/tiangolo/fastapi/pull/11501) by [@Lucas-lyh](https://github.com/Lucas-lyh). +* 🌐 Update Chinese translation for `/docs/advanced/security/http-basic-auth.md`. PR [#11512](https://github.com/tiangolo/fastapi/pull/11512) by [@nick-cjyx9](https://github.com/nick-cjyx9). + +### Internal + +* ♻️ Simplify internal docs script. PR [#11777](https://github.com/tiangolo/fastapi/pull/11777) by [@gitworkflows](https://github.com/gitworkflows). +* 🔧 Update sponsors: add Fine. PR [#11784](https://github.com/tiangolo/fastapi/pull/11784) by [@tiangolo](https://github.com/tiangolo). +* 🔧 Tweak sponsors: Kong URL. PR [#11765](https://github.com/tiangolo/fastapi/pull/11765) by [@tiangolo](https://github.com/tiangolo). +* 🔧 Tweak sponsors: Kong URL. PR [#11764](https://github.com/tiangolo/fastapi/pull/11764) by [@tiangolo](https://github.com/tiangolo). +* 🔧 Update sponsors, add Stainless. PR [#11763](https://github.com/tiangolo/fastapi/pull/11763) by [@tiangolo](https://github.com/tiangolo). +* 🔧 Update sponsors, add Zuplo. PR [#11729](https://github.com/tiangolo/fastapi/pull/11729) by [@tiangolo](https://github.com/tiangolo). +* 🔧 Update Sponsor link: Coherence. PR [#11730](https://github.com/tiangolo/fastapi/pull/11730) by [@tiangolo](https://github.com/tiangolo). +* 👥 Update FastAPI People. PR [#11669](https://github.com/tiangolo/fastapi/pull/11669) by [@tiangolo](https://github.com/tiangolo). +* 🔧 Add sponsor Kong. PR [#11662](https://github.com/tiangolo/fastapi/pull/11662) by [@tiangolo](https://github.com/tiangolo). +* 👷 Update Smokeshow, fix sync download artifact and smokeshow configs. PR [#11563](https://github.com/tiangolo/fastapi/pull/11563) by [@tiangolo](https://github.com/tiangolo). +* 👷 Update Smokeshow download artifact GitHub Action. PR [#11562](https://github.com/tiangolo/fastapi/pull/11562) by [@tiangolo](https://github.com/tiangolo). +* 👷 Update GitHub actions to download and upload artifacts to v4, for docs and coverage. PR [#11550](https://github.com/tiangolo/fastapi/pull/11550) by [@tamird](https://github.com/tamird). +* 👷 Tweak CI for test-redistribute, add needed env vars for slim. PR [#11549](https://github.com/tiangolo/fastapi/pull/11549) by [@tiangolo](https://github.com/tiangolo). +* 👥 Update FastAPI People. PR [#11511](https://github.com/tiangolo/fastapi/pull/11511) by [@tiangolo](https://github.com/tiangolo). + +## 0.111.0 + +### Features + +* ✨ Add FastAPI CLI, the new `fastapi` command. PR [#11522](https://github.com/tiangolo/fastapi/pull/11522) by [@tiangolo](https://github.com/tiangolo). + * New docs: [FastAPI CLI](https://fastapi.tiangolo.com/fastapi-cli/). + +Try it out with: + +```console +$ pip install --upgrade fastapi + +$ 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. +``` + +### Refactors + +* 🔧 Add configs and setup for `fastapi-slim` including optional extras `fastapi-slim[standard]`, and `fastapi` including by default the same `standard` extras. PR [#11503](https://github.com/tiangolo/fastapi/pull/11503) by [@tiangolo](https://github.com/tiangolo). + +## 0.110.3 + +### Docs + +* 📝 Update references to Python version, FastAPI supports all the current versions, no need to make the version explicit. PR [#11496](https://github.com/tiangolo/fastapi/pull/11496) by [@tiangolo](https://github.com/tiangolo). +* ✏️ Fix typo in `fastapi/security/api_key.py`. PR [#11481](https://github.com/tiangolo/fastapi/pull/11481) by [@ch33zer](https://github.com/ch33zer). * ✏️ Fix typo in `security/http.py`. PR [#11455](https://github.com/tiangolo/fastapi/pull/11455) by [@omarmoo5](https://github.com/omarmoo5). ### Translations +* 🌐 Add Traditional Chinese translation for `docs/zh-hant/benchmarks.md`. PR [#11484](https://github.com/tiangolo/fastapi/pull/11484) by [@KNChiu](https://github.com/KNChiu). +* 🌐 Update Chinese translation for `docs/zh/docs/fastapi-people.md`. PR [#11476](https://github.com/tiangolo/fastapi/pull/11476) by [@billzhong](https://github.com/billzhong). * 🌐 Add Chinese translation for `docs/zh/docs/how-to/index.md` and `docs/zh/docs/how-to/general.md`. PR [#11443](https://github.com/tiangolo/fastapi/pull/11443) by [@billzhong](https://github.com/billzhong). * 🌐 Add Spanish translation for cookie-params `docs/es/docs/tutorial/cookie-params.md`. PR [#11410](https://github.com/tiangolo/fastapi/pull/11410) by [@fabianfalon](https://github.com/fabianfalon). ### Internal +* ⬆ Bump mkdocstrings[python] from 0.23.0 to 0.24.3. PR [#11469](https://github.com/tiangolo/fastapi/pull/11469) by [@dependabot[bot]](https://github.com/apps/dependabot). +* 🔨 Update internal scripts and remove unused ones. PR [#11499](https://github.com/tiangolo/fastapi/pull/11499) by [@tiangolo](https://github.com/tiangolo). +* 🔧 Migrate from Hatch to PDM for the internal build. PR [#11498](https://github.com/tiangolo/fastapi/pull/11498) by [@tiangolo](https://github.com/tiangolo). * ⬆️ Upgrade MkDocs Material and re-enable cards. PR [#11466](https://github.com/tiangolo/fastapi/pull/11466) by [@tiangolo](https://github.com/tiangolo). * ⬆ Bump pillow from 10.2.0 to 10.3.0. PR [#11403](https://github.com/tiangolo/fastapi/pull/11403) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔧 Ungroup dependabot updates. PR [#11465](https://github.com/tiangolo/fastapi/pull/11465) by [@tiangolo](https://github.com/tiangolo). @@ -3799,7 +3956,7 @@ Note: all the previous parameters are still there, so it's still possible to dec * New documentation about exceptions handlers: * [Install custom exception handlers](https://fastapi.tiangolo.com/tutorial/handling-errors/#install-custom-exception-handlers). * [Override the default exception handlers](https://fastapi.tiangolo.com/tutorial/handling-errors/#override-the-default-exception-handlers). - * [Re-use **FastAPI's** exception handlers](https://fastapi.tiangolo.com/tutorial/handling-errors/#re-use-fastapis-exception-handlers). + * [Reuse **FastAPI's** exception handlers](https://fastapi.tiangolo.com/tutorial/handling-errors/#reuse-fastapis-exception-handlers). * PR [#273](https://github.com/tiangolo/fastapi/pull/273). * Fix support for *paths* in *path parameters* without needing explicit `Path(...)`. diff --git a/docs/en/docs/tutorial/background-tasks.md b/docs/en/docs/tutorial/background-tasks.md index bc8e2af6a..bcfadc8b8 100644 --- a/docs/en/docs/tutorial/background-tasks.md +++ b/docs/en/docs/tutorial/background-tasks.md @@ -55,7 +55,7 @@ Inside of your *path operation function*, pass your task function to the *backgr Using `BackgroundTasks` also works with the dependency injection system, you can declare a parameter of type `BackgroundTasks` at multiple levels: in a *path operation function*, in a dependency (dependable), in a sub-dependency, etc. -**FastAPI** knows what to do in each case and how to re-use the same object, so that all the background tasks are merged together and are run in the background afterwards: +**FastAPI** knows what to do in each case and how to reuse the same object, so that all the background tasks are merged together and are run in the background afterwards: === "Python 3.10+" diff --git a/docs/en/docs/tutorial/body-multiple-params.md b/docs/en/docs/tutorial/body-multiple-params.md index ebef8eeaa..689db7ece 100644 --- a/docs/en/docs/tutorial/body-multiple-params.md +++ b/docs/en/docs/tutorial/body-multiple-params.md @@ -97,7 +97,7 @@ So, it will then use the parameter names as keys (field names) in the body, and Notice that even though the `item` was declared the same way as before, it is now expected to be inside of the body with a key `item`. -**FastAPI** will do the automatic conversion from the request, so that the parameter `item` receives it's specific content and the same for `user`. +**FastAPI** will do the automatic conversion from the request, so that the parameter `item` receives its specific content and the same for `user`. It will perform the validation of the compound data, and will document it like that for the OpenAPI schema and automatic docs. diff --git a/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md b/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md index eaab51d1b..082417f11 100644 --- a/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md +++ b/docs/en/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -107,7 +107,7 @@ These dependencies can `raise` exceptions, the same as normal dependencies: And they can return values or not, the values won't be used. -So, you can re-use a normal dependency (that returns a value) you already use somewhere else, and even though the value won't be used, the dependency will be executed: +So, you can reuse a normal dependency (that returns a value) you already use somewhere else, and even though the value won't be used, the dependency will be executed: === "Python 3.9+" diff --git a/docs/en/docs/tutorial/dependencies/sub-dependencies.md b/docs/en/docs/tutorial/dependencies/sub-dependencies.md index 1cb469a80..e5def9b7d 100644 --- a/docs/en/docs/tutorial/dependencies/sub-dependencies.md +++ b/docs/en/docs/tutorial/dependencies/sub-dependencies.md @@ -157,7 +157,7 @@ query_extractor --> query_or_cookie_extractor --> read_query If one of your dependencies is declared multiple times for the same *path operation*, for example, multiple dependencies have a common sub-dependency, **FastAPI** will know to call that sub-dependency only once per request. -And it will save the returned value in a "cache" and pass it to all the "dependants" that need it in that specific request, instead of calling the dependency multiple times for the same request. +And it will save the returned value in a "cache" and pass it to all the "dependants" that need it in that specific request, instead of calling the dependency multiple times for the same request. In an advanced scenario where you know you need the dependency to be called at every step (possibly multiple times) in the same request instead of using the "cached" value, you can set the parameter `use_cache=False` when using `Depends`: diff --git a/docs/en/docs/tutorial/first-steps.md b/docs/en/docs/tutorial/first-steps.md index cfa159329..d18b25d97 100644 --- a/docs/en/docs/tutorial/first-steps.md +++ b/docs/en/docs/tutorial/first-steps.md @@ -13,24 +13,51 @@ Run the live server:
```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 - 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()`. - * `--reload`: make the server restart after code changes. Only use for development. - In the output, there's a line with something like: ```hl_lines="4" @@ -151,36 +178,6 @@ Here the `app` variable will be an "instance" of the class `FastAPI`. This will be the main point of interaction to create all your API. -This `app` is the same one referred by `uvicorn` in the command: - -
- -```console -$ uvicorn main:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -If you create your app like: - -```Python hl_lines="3" -{!../../../docs_src/first_steps/tutorial002.py!} -``` - -And put it in a file `main.py`, then you would call `uvicorn` like: - -
- -```console -$ uvicorn main:my_awesome_api --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- ### Step 3: create a *path operation* #### Path @@ -328,6 +325,6 @@ There are many other objects and models that will be automatically converted to * Import `FastAPI`. * Create an `app` instance. -* Write a **path operation decorator** (like `@app.get("/")`). -* Write a **path operation function** (like `def root(): ...` above). -* Run the development server (like `uvicorn main:app --reload`). +* Write a **path operation decorator** using decorators like `@app.get("/")`. +* Define a **path operation function**; for example, `def root(): ...`. +* Run the development server using the command `fastapi dev`. diff --git a/docs/en/docs/tutorial/handling-errors.md b/docs/en/docs/tutorial/handling-errors.md index 98ac55d1f..6133898e4 100644 --- a/docs/en/docs/tutorial/handling-errors.md +++ b/docs/en/docs/tutorial/handling-errors.md @@ -248,12 +248,12 @@ In this example, to be able to have both `HTTPException`s in the same code, Star from starlette.exceptions import HTTPException as StarletteHTTPException ``` -### Re-use **FastAPI**'s exception handlers +### Reuse **FastAPI**'s exception handlers -If you want to use the exception along with the same default exception handlers from **FastAPI**, You can import and re-use the default exception handlers from `fastapi.exception_handlers`: +If you want to use the exception along with the same default exception handlers from **FastAPI**, You can import and reuse the default exception handlers from `fastapi.exception_handlers`: ```Python hl_lines="2-5 15 21" {!../../../docs_src/handling_errors/tutorial006.py!} ``` -In this example you are just `print`ing the error with a very expressive message, but you get the idea. You can use the exception and then just re-use the default exception handlers. +In this example you are just `print`ing the error with a very expressive message, but you get the idea. You can use the exception and then just reuse the default exception handlers. diff --git a/docs/en/docs/tutorial/index.md b/docs/en/docs/tutorial/index.md index 75665324d..74fe06acd 100644 --- a/docs/en/docs/tutorial/index.md +++ b/docs/en/docs/tutorial/index.md @@ -12,18 +12,53 @@ So you can come back and see exactly what you need. All the code blocks can be copied and used directly (they are actually tested Python files). -To run any of the examples, copy the code to a file `main.py`, and start `uvicorn` with: +To run any of the examples, copy the code to a file `main.py`, and start `fastapi dev` with:
```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. + ```
@@ -36,38 +71,22 @@ Using it in your editor is what really shows you the benefits of FastAPI, seeing ## Install FastAPI -The first step is to install FastAPI. - -For the tutorial, you might want to install it with all the optional dependencies and features: +The first step is to install FastAPI:
```console -$ pip install "fastapi[all]" +$ pip install fastapi ---> 100% ```
-...that also includes `uvicorn`, that you can use as the server that runs your code. - !!! note - You can also install it part by part. - - This is what you would probably do once you want to deploy your application to production: - - ``` - pip install fastapi - ``` - - Also install `uvicorn` to work as the server: - - ``` - pip install "uvicorn[standard]" - ``` + When you install with `pip install fastapi` it comes with some default optional standard dependencies. - And the same for each of the optional dependencies that you want to use. + If you don't want to have those optional dependencies, you can instead install `pip install fastapi-slim`. ## Advanced User Guide diff --git a/docs/en/docs/tutorial/path-params-numeric-validations.md b/docs/en/docs/tutorial/path-params-numeric-validations.md index b5b13cfbe..ca86ad226 100644 --- a/docs/en/docs/tutorial/path-params-numeric-validations.md +++ b/docs/en/docs/tutorial/path-params-numeric-validations.md @@ -92,11 +92,7 @@ For example, to declare a `title` metadata value for the path parameter `item_id ``` !!! note - A path parameter is always required as it has to be part of the path. - - So, you should declare it with `...` to mark it as required. - - Nevertheless, even if you declared it with `None` or set a default value, it would not affect anything, it would still be always required. + A path parameter is always required as it has to be part of the path. Even if you declared it with `None` or set a default value, it would not affect anything, it would still be always required. ## Order the parameters as you need diff --git a/docs/en/docs/tutorial/query-params-str-validations.md b/docs/en/docs/tutorial/query-params-str-validations.md index 24784efad..da8e53720 100644 --- a/docs/en/docs/tutorial/query-params-str-validations.md +++ b/docs/en/docs/tutorial/query-params-str-validations.md @@ -99,7 +99,7 @@ Now let's jump to the fun stuff. 🎉 ## Add `Query` to `Annotated` in the `q` parameter -Now that we have this `Annotated` where we can put more metadata, add `Query` to it, and set the parameter `max_length` to 50: +Now that we have this `Annotated` where we can put more information (in this case some additional validation), add `Query` inside of `Annotated`, and set the parameter `max_length` to `50`: === "Python 3.10+" @@ -115,7 +115,11 @@ Now that we have this `Annotated` where we can put more metadata, add `Query` to Notice that the default value is still `None`, so the parameter is still optional. -But now, having `Query(max_length=50)` inside of `Annotated`, we are telling FastAPI that we want it to extract this value from the query parameters (this would have been the default anyway 🤷) and that we want to have **additional validation** for this value (that's why we do this, to get the additional validation). 😎 +But now, having `Query(max_length=50)` inside of `Annotated`, we are telling FastAPI that we want it to have **additional validation** for this value, we want it to have maximum 50 characters. 😎 + +!!! tip + + Here we are using `Query()` because this is a **query parameter**. Later we will see others like `Path()`, `Body()`, `Header()`, and `Cookie()`, that also accept the same arguments as `Query()`. FastAPI will now: diff --git a/docs/en/docs/tutorial/security/first-steps.md b/docs/en/docs/tutorial/security/first-steps.md index 7d86e453e..a769cc0e6 100644 --- a/docs/en/docs/tutorial/security/first-steps.md +++ b/docs/en/docs/tutorial/security/first-steps.md @@ -45,9 +45,11 @@ Copy the example in a file `main.py`: ## Run it !!! info - First install `python-multipart`. + The `python-multipart` package is automatically installed with **FastAPI** when you run the `pip install fastapi` command. - E.g. `pip install python-multipart`. + However, if you use the `pip install fastapi-slim` command, the `python-multipart` package is not included by default. To install it manually, use the following command: + + `pip install python-multipart` This is because **OAuth2** uses "form data" for sending the `username` and `password`. @@ -56,7 +58,7 @@ Run the example 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) ``` diff --git a/docs/en/docs/tutorial/security/oauth2-jwt.md b/docs/en/docs/tutorial/security/oauth2-jwt.md index b02d00c3f..b011db67a 100644 --- a/docs/en/docs/tutorial/security/oauth2-jwt.md +++ b/docs/en/docs/tutorial/security/oauth2-jwt.md @@ -26,28 +26,24 @@ After a week, the token will be expired and the user will not be authorized and If you want to play with JWT tokens and see how they work, check https://jwt.io. -## Install `python-jose` +## Install `PyJWT` -We need to install `python-jose` to generate and verify the JWT tokens in Python: +We need to install `PyJWT` to generate and verify the JWT tokens in Python:
```console -$ pip install "python-jose[cryptography]" +$ pip install pyjwt ---> 100% ```
-Python-jose requires a cryptographic backend as an extra. +!!! info + If you are planning to use digital signature algorithms like RSA or ECDSA, you should install the cryptography library dependency `pyjwt[crypto]`. -Here we are using the recommended one: pyca/cryptography. - -!!! tip - This tutorial previously used PyJWT. - - But it was updated to use Python-jose instead as it provides all the features from PyJWT plus some extras that you might need later when building integrations with other tools. + You can read more about it in the PyJWT Installation docs. ## Password hashing @@ -111,19 +107,19 @@ And another one to authenticate and return a user. === "Python 3.10+" - ```Python hl_lines="7 48 55-56 59-60 69-75" + ```Python hl_lines="8 49 56-57 60-61 70-76" {!> ../../../docs_src/security/tutorial004_an_py310.py!} ``` === "Python 3.9+" - ```Python hl_lines="7 48 55-56 59-60 69-75" + ```Python hl_lines="8 49 56-57 60-61 70-76" {!> ../../../docs_src/security/tutorial004_an_py39.py!} ``` === "Python 3.8+" - ```Python hl_lines="7 49 56-57 60-61 70-76" + ```Python hl_lines="8 50 57-58 61-62 71-77" {!> ../../../docs_src/security/tutorial004_an.py!} ``` @@ -132,7 +128,7 @@ And another one to authenticate and return a user. !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="6 47 54-55 58-59 68-74" + ```Python hl_lines="7 48 55-56 59-60 69-75" {!> ../../../docs_src/security/tutorial004_py310.py!} ``` @@ -141,7 +137,7 @@ And another one to authenticate and return a user. !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="7 48 55-56 59-60 69-75" + ```Python hl_lines="8 49 56-57 60-61 70-76" {!> ../../../docs_src/security/tutorial004.py!} ``` @@ -178,19 +174,19 @@ Create a utility function to generate a new access token. === "Python 3.10+" - ```Python hl_lines="6 12-14 28-30 78-86" + ```Python hl_lines="4 7 13-15 29-31 79-87" {!> ../../../docs_src/security/tutorial004_an_py310.py!} ``` === "Python 3.9+" - ```Python hl_lines="6 12-14 28-30 78-86" + ```Python hl_lines="4 7 13-15 29-31 79-87" {!> ../../../docs_src/security/tutorial004_an_py39.py!} ``` === "Python 3.8+" - ```Python hl_lines="6 13-15 29-31 79-87" + ```Python hl_lines="4 7 14-16 30-32 80-88" {!> ../../../docs_src/security/tutorial004_an.py!} ``` @@ -199,7 +195,7 @@ Create a utility function to generate a new access token. !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="5 11-13 27-29 77-85" + ```Python hl_lines="3 6 12-14 28-30 78-86" {!> ../../../docs_src/security/tutorial004_py310.py!} ``` @@ -208,7 +204,7 @@ Create a utility function to generate a new access token. !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="6 12-14 28-30 78-86" + ```Python hl_lines="4 7 13-15 29-31 79-87" {!> ../../../docs_src/security/tutorial004.py!} ``` @@ -222,19 +218,19 @@ If the token is invalid, return an HTTP error right away. === "Python 3.10+" - ```Python hl_lines="89-106" + ```Python hl_lines="90-107" {!> ../../../docs_src/security/tutorial004_an_py310.py!} ``` === "Python 3.9+" - ```Python hl_lines="89-106" + ```Python hl_lines="90-107" {!> ../../../docs_src/security/tutorial004_an_py39.py!} ``` === "Python 3.8+" - ```Python hl_lines="90-107" + ```Python hl_lines="91-108" {!> ../../../docs_src/security/tutorial004_an.py!} ``` @@ -243,7 +239,7 @@ If the token is invalid, return an HTTP error right away. !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="88-105" + ```Python hl_lines="89-106" {!> ../../../docs_src/security/tutorial004_py310.py!} ``` @@ -252,7 +248,7 @@ If the token is invalid, return an HTTP error right away. !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="89-106" + ```Python hl_lines="90-107" {!> ../../../docs_src/security/tutorial004.py!} ``` @@ -264,19 +260,19 @@ Create a real JWT access token and return it. === "Python 3.10+" - ```Python hl_lines="117-132" + ```Python hl_lines="118-133" {!> ../../../docs_src/security/tutorial004_an_py310.py!} ``` === "Python 3.9+" - ```Python hl_lines="117-132" + ```Python hl_lines="118-133" {!> ../../../docs_src/security/tutorial004_an_py39.py!} ``` === "Python 3.8+" - ```Python hl_lines="118-133" + ```Python hl_lines="119-134" {!> ../../../docs_src/security/tutorial004_an.py!} ``` @@ -285,7 +281,7 @@ Create a real JWT access token and return it. !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="114-129" + ```Python hl_lines="115-130" {!> ../../../docs_src/security/tutorial004_py310.py!} ``` @@ -294,7 +290,7 @@ Create a real JWT access token and return it. !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="115-130" + ```Python hl_lines="116-131" {!> ../../../docs_src/security/tutorial004.py!} ``` @@ -384,7 +380,7 @@ Many packages that simplify it a lot have to make many compromises with the data It gives you all the flexibility to choose the ones that fit your project the best. -And you can use directly many well maintained and widely used packages like `passlib` and `python-jose`, because **FastAPI** doesn't require any complex mechanisms to integrate external packages. +And you can use directly many well maintained and widely used packages like `passlib` and `PyJWT`, because **FastAPI** doesn't require any complex mechanisms to integrate external packages. But it provides you the tools to simplify the process as much as possible without compromising flexibility, robustness, or security. diff --git a/docs/en/docs/tutorial/sql-databases.md b/docs/en/docs/tutorial/sql-databases.md index 0b4d06b99..1f0ebc08b 100644 --- a/docs/en/docs/tutorial/sql-databases.md +++ b/docs/en/docs/tutorial/sql-databases.md @@ -513,7 +513,7 @@ And you would also use Alembic for "migrations" (that's its main job). A "migration" is the set of steps needed whenever you change the structure of your SQLAlchemy models, add a new attribute, etc. to replicate those changes in the database, add a new column, a new table, etc. -You can find an example of Alembic in a FastAPI project in the templates from [Project Generation - Template](../project-generation.md){.internal-link target=_blank}. Specifically in the `alembic` directory in the source code. +You can find an example of Alembic in a FastAPI project in the [Full Stack FastAPI Template](../project-generation.md){.internal-link target=_blank}. Specifically in the `alembic` directory in the source code. ### Create a dependency diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index 933e7e4a2..05dffb706 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -167,6 +167,7 @@ nav: - advanced/openapi-webhooks.md - advanced/wsgi.md - advanced/generate-clients.md + - fastapi-cli.md - Deployment: - deployment/index.md - deployment/versions.md diff --git a/docs/en/overrides/main.html b/docs/en/overrides/main.html index 28a912fb3..ae8ea5667 100644 --- a/docs/en/overrides/main.html +++ b/docs/en/overrides/main.html @@ -65,7 +65,7 @@
- + @@ -76,6 +76,24 @@
+ + +
{% endblock %} diff --git a/docs/es/docs/how-to/graphql.md b/docs/es/docs/how-to/graphql.md new file mode 100644 index 000000000..1138af76a --- /dev/null +++ b/docs/es/docs/how-to/graphql.md @@ -0,0 +1,56 @@ +# GraphQL + +Como **FastAPI** está basado en el estándar **ASGI**, es muy fácil integrar cualquier library **GraphQL** que sea compatible con ASGI. + +Puedes combinar *operaciones de path* regulares de la library de FastAPI con GraphQL en la misma aplicación. + +!!! tip + **GraphQL** resuelve algunos casos de uso específicos. + + Tiene **ventajas** y **desventajas** cuando lo comparas con **APIs web** comunes. + + Asegúrate de evaluar si los **beneficios** para tu caso de uso compensan las **desventajas.** 🤓 + +## Librerías GraphQL + +Aquí hay algunas de las libraries de **GraphQL** que tienen soporte con **ASGI** las cuales podrías usar con **FastAPI**: + +* Strawberry 🍓 + * Con documentación para FastAPI +* Ariadne + * Con documentación para FastAPI +* Tartiflette + * Con Tartiflette ASGI para proveer integración con ASGI +* Graphene + * Con starlette-graphene3 + +## GraphQL con Strawberry + +Si necesitas o quieres trabajar con **GraphQL**, **Strawberry** es la library **recomendada** por el diseño más cercano a **FastAPI**, el cual es completamente basado en **anotaciones de tipo**. + +Dependiendo de tus casos de uso, podrías preferir usar una library diferente, pero si me preguntas, probablemente te recomendaría **Strawberry**. + +Aquí hay una pequeña muestra de cómo podrías integrar Strawberry con FastAPI: + +```Python hl_lines="3 22 25-26" +{!../../../docs_src/graphql/tutorial001.py!} +``` + +Puedes aprender más sobre Strawberry en la documentación de Strawberry. + +Y también en la documentación sobre Strawberry con FastAPI. + +## Clase obsoleta `GraphQLApp` en Starlette + +Versiones anteriores de Starlette incluyen la clase `GraphQLApp` para integrarlo con Graphene. + +Esto fue marcado como obsoleto en Starlette, pero si aún tienes código que lo usa, puedes fácilmente **migrar** a starlette-graphene3, la cual cubre el mismo caso de uso y tiene una **interfaz casi idéntica.** + +!!! tip + Si necesitas GraphQL, te recomendaría revisar Strawberry, que es basada en anotaciones de tipo en vez de clases y tipos personalizados. + +## Aprende más + +Puedes aprender más acerca de **GraphQL** en la documentación oficial de GraphQL. + +También puedes leer más acerca de cada library descrita anteriormente en sus enlaces. diff --git a/docs/es/docs/index.md b/docs/es/docs/index.md index 9fc275caf..5153367dd 100644 --- a/docs/es/docs/index.md +++ b/docs/es/docs/index.md @@ -32,7 +32,7 @@ hide: **Código Fuente**: https://github.com/tiangolo/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. +FastAPI es un web framework moderno y rápido (de alto rendimiento) para construir APIs con Python basado en las anotaciones de tipos estándar de Python. Sus características principales son: @@ -115,8 +115,6 @@ Si estás construyendo un app de Starlette para las partes web. @@ -134,7 +132,7 @@ $ pip install fastapi
-También vas a necesitar un servidor ASGI para producción cómo Uvicorn o Hypercorn. +También vas a necesitar un servidor ASGI para producción cómo Uvicorn o Hypercorn.
@@ -328,7 +326,7 @@ Lo haces con tipos modernos estándar de Python. No tienes que aprender una sintaxis nueva, los métodos o clases de una library específica, etc. -Solo **Python 3.8+** estándar. +Solo **Python** estándar. Por ejemplo, para un `int`: diff --git a/docs/fa/docs/index.md b/docs/fa/docs/index.md index 623bc0f75..dfbb8e647 100644 --- a/docs/fa/docs/index.md +++ b/docs/fa/docs/index.md @@ -134,7 +134,7 @@ $ pip install fastapi
-نصب یک سرور پروداکشن نظیر Uvicorn یا Hypercorn نیز جزء نیازمندی‌هاست. +نصب یک سرور پروداکشن نظیر Uvicorn یا Hypercorn نیز جزء نیازمندی‌هاست.
diff --git a/docs/fr/docs/async.md b/docs/fr/docs/async.md index 3f65032fe..eabd9686a 100644 --- a/docs/fr/docs/async.md +++ b/docs/fr/docs/async.md @@ -103,24 +103,41 @@ 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 +166,41 @@ 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. diff --git a/docs/fr/docs/deployment/manually.md b/docs/fr/docs/deployment/manually.md index c53e2db67..eb1253cf8 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. @@ -46,7 +46,7 @@ Vous pouvez installer un serveur compatible ASGI avec : === "Hypercorn" - * Hypercorn, un serveur ASGI également compatible avec HTTP/2. + * Hypercorn, un serveur ASGI également compatible avec HTTP/2.
diff --git a/docs/fr/docs/index.md b/docs/fr/docs/index.md index 324681a74..e31f416ce 100644 --- a/docs/fr/docs/index.md +++ b/docs/fr/docs/index.md @@ -36,7 +36,7 @@ hide: --- -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 : @@ -124,8 +124,6 @@ Si vous souhaitez construire une application Starlette pour les parties web. @@ -340,7 +338,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`: 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/he/docs/index.md b/docs/he/docs/index.md index 621126128..626578e40 100644 --- a/docs/he/docs/index.md +++ b/docs/he/docs/index.md @@ -138,7 +138,7 @@ $ pip install fastapi
-תצטרכו גם שרת ASGI כגון Uvicorn או Hypercorn. +תצטרכו גם שרת ASGI כגון Uvicorn או Hypercorn.
diff --git a/docs/hu/docs/index.md b/docs/hu/docs/index.md index 896db6d1f..671b0477f 100644 --- a/docs/hu/docs/index.md +++ b/docs/hu/docs/index.md @@ -26,7 +26,7 @@ **Forrás kód**: https://github.com/tiangolo/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: @@ -115,8 +115,6 @@ 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. @@ -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: diff --git a/docs/it/docs/index.md b/docs/it/docs/index.md index c06d3a174..016316a64 100644 --- a/docs/it/docs/index.md +++ b/docs/it/docs/index.md @@ -129,7 +129,7 @@ $ pip install fastapi
-Per il rilascio in produzione, sarà necessario un server ASGI come Uvicorn oppure Hypercorn. +Per il rilascio in produzione, sarà necessario un server ASGI come Uvicorn oppure Hypercorn.
diff --git a/docs/ja/docs/deployment/manually.md b/docs/ja/docs/deployment/manually.md index 67010a66f..449aea31e 100644 --- a/docs/ja/docs/deployment/manually.md +++ b/docs/ja/docs/deployment/manually.md @@ -25,7 +25,7 @@ === "Hypercorn" - * Hypercorn, HTTP/2にも対応しているASGIサーバ。 + * Hypercorn, HTTP/2にも対応しているASGIサーバ。
diff --git a/docs/ja/docs/index.md b/docs/ja/docs/index.md index a991222cb..2d4daac75 100644 --- a/docs/ja/docs/index.md +++ b/docs/ja/docs/index.md @@ -33,7 +33,7 @@ hide: --- -FastAPI は、Pythonの標準である型ヒントに基づいてPython 3.8 以降でAPI を構築するための、モダンで、高速(高パフォーマンス)な、Web フレームワークです。 +FastAPI は、Pythonの標準である型ヒントに基づいてPython 以降でAPI を構築するための、モダンで、高速(高パフォーマンス)な、Web フレームワークです。 主な特徴: @@ -116,8 +116,6 @@ FastAPI は、Pythonの標準である型ヒントに基づいてPython 3.8 以 ## 必要条件 -Python 3.8+ - FastAPI は巨人の肩の上に立っています。 - Web の部分はStarlette @@ -135,7 +133,7 @@ $ pip install fastapi
-本番環境では、Uvicorn または、 Hypercornのような、 ASGI サーバーが必要になります。 +本番環境では、Uvicorn または、 Hypercornのような、 ASGI サーバーが必要になります。
diff --git a/docs/ko/docs/index.md b/docs/ko/docs/index.md index dea087332..21dd16f59 100644 --- a/docs/ko/docs/index.md +++ b/docs/ko/docs/index.md @@ -33,7 +33,7 @@ hide: --- -FastAPI는 현대적이고, 빠르며(고성능), 파이썬 표준 타입 힌트에 기초한 Python3.8+의 API를 빌드하기 위한 웹 프레임워크입니다. +FastAPI는 현대적이고, 빠르며(고성능), 파이썬 표준 타입 힌트에 기초한 Python의 API를 빌드하기 위한 웹 프레임워크입니다. 주요 특징으로: @@ -116,8 +116,6 @@ FastAPI는 현대적이고, 빠르며(고성능), 파이썬 표준 타입 힌트 ## 요구사항 -Python 3.8+ - FastAPI는 거인들의 어깨 위에 서 있습니다: * 웹 부분을 위한 Starlette. @@ -135,7 +133,7 @@ $ pip install fastapi
-프로덕션을 위해 Uvicorn 또는 Hypercorn과 같은 ASGI 서버도 필요할 겁니다. +프로덕션을 위해 Uvicorn 또는 Hypercorn과 같은 ASGI 서버도 필요할 겁니다.
@@ -332,7 +330,7 @@ def update_item(item_id: int, item: Item): 새로운 문법, 특정 라이브러리의 메소드나 클래스 등을 배울 필요가 없습니다. -그저 표준 **Python 3.8+** 입니다. +그저 표준 **Python** 입니다. 예를 들어, `int`에 대해선: diff --git a/docs/ko/docs/tutorial/body-nested-models.md b/docs/ko/docs/tutorial/body-nested-models.md index edf1a5f77..10af0a062 100644 --- a/docs/ko/docs/tutorial/body-nested-models.md +++ b/docs/ko/docs/tutorial/body-nested-models.md @@ -48,7 +48,7 @@ my_list: List[str] ## 집합 타입 -그런데 생각해보니 태그는 반복되면 안 돼고, 고유한(Unique) 문자열이어야 할 것 같습니다. +그런데 생각해보니 태그는 반복되면 안 되고, 고유한(Unique) 문자열이어야 할 것 같습니다. 그리고 파이썬은 집합을 위한 특별한 데이터 타입 `set`이 있습니다. 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..673cf5b73 --- /dev/null +++ b/docs/ko/docs/tutorial/extra-data-types.md @@ -0,0 +1,130 @@ +# 추가 데이터 자료형 + +지금까지 일반적인 데이터 자료형을 사용했습니다. 예를 들면 다음과 같습니다: + +* `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 데이터 자료형. + +## 예시 + +위의 몇몇 자료형을 매개변수로 사용하는 *경로 작동* 예시입니다. + +=== "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 + Prefer to use the `Annotated` version if possible. + + ```Python hl_lines="1 2 11-15" + {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + Prefer to use the `Annotated` version if possible. + + ```Python hl_lines="1 2 12-16" + {!> ../../../docs_src/extra_data_types/tutorial001.py!} + ``` + +함수 안의 매개변수가 그들만의 데이터 자료형을 가지고 있으며, 예를 들어, 다음과 같이 날짜를 조작할 수 있음을 참고하십시오: + +=== "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 + Prefer to use the `Annotated` version if possible. + + ```Python hl_lines="17-18" + {!> ../../../docs_src/extra_data_types/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + Prefer to use the `Annotated` version if possible. + + ```Python hl_lines="18-19" + {!> ../../../docs_src/extra_data_types/tutorial001.py!} + ``` diff --git a/docs/ko/docs/tutorial/response-status-code.md b/docs/ko/docs/tutorial/response-status-code.md index f92c057be..e6eed5120 100644 --- a/docs/ko/docs/tutorial/response-status-code.md +++ b/docs/ko/docs/tutorial/response-status-code.md @@ -43,16 +43,16 @@ HTTP는 세자리의 숫자 상태 코드를 응답의 일부로 전송합니다 요약하자면: -* `**1xx**` 상태 코드는 "정보"용입니다. 이들은 직접적으로는 잘 사용되지는 않습니다. 이 상태 코드를 갖는 응답들은 본문을 가질 수 없습니다. -* `**2xx**` 상태 코드는 "성공적인" 응답을 위해 사용됩니다. 가장 많이 사용되는 유형입니다. +* `1xx` 상태 코드는 "정보"용입니다. 이들은 직접적으로는 잘 사용되지는 않습니다. 이 상태 코드를 갖는 응답들은 본문을 가질 수 없습니다. +* **`2xx`** 상태 코드는 "성공적인" 응답을 위해 사용됩니다. 가장 많이 사용되는 유형입니다. * `200` 은 디폴트 상태 코드로, 모든 것이 "성공적임"을 의미합니다. * 다른 예로는 `201` "생성됨"이 있습니다. 일반적으로 데이터베이스에 새로운 레코드를 생성한 후 사용합니다. * 단, `204` "내용 없음"은 특별한 경우입니다. 이것은 클라이언트에게 반환할 내용이 없는 경우 사용합니다. 따라서 응답은 본문을 가질 수 없습니다. -* `**3xx**` 상태 코드는 "리다이렉션"용입니다. 본문을 가질 수 없는 `304` "수정되지 않음"을 제외하고, 이 상태 코드를 갖는 응답에는 본문이 있을 수도, 없을 수도 있습니다. -* `**4xx**` 상태 코드는 "클라이언트 오류" 응답을 위해 사용됩니다. 이것은 아마 가장 많이 사용하게 될 두번째 유형입니다. +* **`3xx`** 상태 코드는 "리다이렉션"용입니다. 본문을 가질 수 없는 `304` "수정되지 않음"을 제외하고, 이 상태 코드를 갖는 응답에는 본문이 있을 수도, 없을 수도 있습니다. +* **`4xx`** 상태 코드는 "클라이언트 오류" 응답을 위해 사용됩니다. 이것은 아마 가장 많이 사용하게 될 두번째 유형입니다. * 일례로 `404` 는 "찾을 수 없음" 응답을 위해 사용합니다. * 일반적인 클라이언트 오류의 경우 `400` 을 사용할 수 있습니다. -* `**5xx**` 상태 코드는 서버 오류에 사용됩니다. 이것들을 직접 사용할 일은 거의 없습니다. 응용 프로그램 코드나 서버의 일부에서 문제가 발생하면 자동으로 이들 상태 코드 중 하나를 반환합니다. +* `5xx` 상태 코드는 서버 오류에 사용됩니다. 이것들을 직접 사용할 일은 거의 없습니다. 응용 프로그램 코드나 서버의 일부에서 문제가 발생하면 자동으로 이들 상태 코드 중 하나를 반환합니다. !!! tip "팁" 각각의 상태 코드와 이들이 의미하는 내용에 대해 더 알고싶다면 MDN HTTP 상태 코드에 관한 문서 를 확인하십시오. @@ -82,7 +82,7 @@ HTTP는 세자리의 숫자 상태 코드를 응답의 일부로 전송합니다 !!! note "기술적 세부사항" `from starlette import status` 역시 사용할 수 있습니다. - **FastAPI**는 개발자인 당신의 편의를 위해 `fastapi.status` 와 동일한 `starlette.status` 도 제공합니다. 하지만 이것은 Starlette로부터 직접 제공됩니다. + **FastAPI**는 개발자인 여러분의 편의를 위해 `fastapi.status` 와 동일한 `starlette.status` 도 제공합니다. 하지만 이것은 Starlette로부터 직접 제공됩니다. ## 기본값 변경 diff --git a/docs/pl/docs/fastapi-people.md b/docs/pl/docs/fastapi-people.md new file mode 100644 index 000000000..b244ab489 --- /dev/null +++ b/docs/pl/docs/fastapi-people.md @@ -0,0 +1,178 @@ +# Ludzie FastAPI + +FastAPI posiada wspaniałą społeczność, która jest otwarta dla ludzi z każdego środowiska. + +## Twórca - Opienik + +Cześć! 👋 + +To ja: + +{% if people %} +
+{% for user in people.maintainers %} + +
@{{ user.login }}
Liczba odpowiedzi: {{ user.answers }}
Pull Requesty: {{ user.prs }}
+{% endfor %} + +
+{% endif %} + +Jestem twórcą i opiekunem **FastAPI**. Możesz przeczytać więcej na ten temat w [Pomoc FastAPI - Uzyskaj pomoc - Skontaktuj się z autorem](help-fastapi.md#connect-with-the-author){.internal-link target=_blank}. + +...Ale tutaj chcę pokazać Ci społeczność. + +--- + +**FastAPI** otrzymuje wiele wsparcia od społeczności. Chciałbym podkreślić ich wkład. + +To są ludzie, którzy: + +* [Pomagają innym z pytaniami na GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. +* [Tworzą Pull Requesty](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. +* Oceniają Pull Requesty, [to szczególnie ważne dla tłumaczeń](contributing.md#translations){.internal-link target=_blank}. + +Proszę o brawa dla nich. 👏 🙇 + +## Najaktywniejsi użytkownicy w zeszłym miesiącu + +Oto niektórzy użytkownicy, którzy [pomagali innym w największej liczbie pytań na GitHubie](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} podczas ostatniego miesiąca. ☕ + +{% if people %} +
+{% for user in people.last_month_active %} + +
@{{ user.login }}
Udzielonych odpowiedzi: {{ user.count }}
+{% endfor %} + +
+{% endif %} + +## Eksperci + +Oto **eksperci FastAPI**. 🤓 + +To użytkownicy, którzy [pomogli innym z największa liczbą pytań na GitHubie](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} od *samego początku*. + +Poprzez pomoc wielu innym, udowodnili, że są ekspertami. ✨ + +{% if people %} +
+{% for user in people.experts %} + +
@{{ user.login }}
Udzielonych odpowiedzi: {{ user.count }}
+{% endfor %} + +
+{% endif %} + +## Najlepsi Kontrybutorzy + +Oto **Najlepsi Kontrybutorzy**. 👷 + +Ci użytkownicy [stworzyli najwięcej Pull Requestów](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}, które zostały *wcalone*. + +Współtworzyli kod źródłowy, dokumentację, tłumaczenia itp. 📦 + +{% if people %} +
+{% for user in people.top_contributors %} + +
@{{ user.login }}
Pull Requesty: {{ user.count }}
+{% endfor %} + +
+{% endif %} + +Jest wielu więcej kontrybutorów (ponad setka), możesz zobaczyć ich wszystkich na stronie Kontrybutorzy FastAPI na GitHub. 👷 + +## Najlepsi Oceniajacy + +Ci uzytkownicy są **Najlepszymi oceniającymi**. 🕵️ + +### Oceny Tłumaczeń + +Ja mówię tylko kilkoma językami (i to niezbyt dobrze 😅). Zatem oceniający są tymi, którzy mają [**moc zatwierdzania tłumaczeń**](contributing.md#translations){.internal-link target=_blank} dokumentacji. Bez nich nie byłoby dokumentacji w kilku innych językach. + +--- + +**Najlepsi Oceniający** 🕵️ przejrzeli więcej Pull Requestów, niż inni, zapewniając jakość kodu, dokumentacji, a zwłaszcza **tłumaczeń**. + +{% if people %} +
+{% for user in people.top_reviewers %} + +
@{{ user.login }}
Liczba ocen: {{ user.count }}
+{% endfor %} + +
+{% endif %} + +## Sponsorzy + +Oto **Sponsorzy**. 😎 + +Wspierają moją pracę nad **FastAPI** (i innymi), głównie poprzez GitHub Sponsors. + +{% if sponsors %} + +{% if sponsors.gold %} + +### Złoci Sponsorzy + +{% for sponsor in sponsors.gold -%} + +{% endfor %} +{% endif %} + +{% if sponsors.silver %} + +### Srebrni Sponsorzy + +{% for sponsor in sponsors.silver -%} + +{% endfor %} +{% endif %} + +{% if sponsors.bronze %} + +### Brązowi Sponsorzy + +{% for sponsor in sponsors.bronze -%} + +{% endfor %} +{% endif %} + +{% endif %} + +### Indywidualni Sponsorzy + +{% 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 %} + +## Techniczne szczegóły danych + +Głównym celem tej strony jest podkreślenie wysiłku społeczności w pomaganiu innym. + +Szczególnie włączając wysiłki, które są zwykle mniej widoczne, a w wielu przypadkach bardziej żmudne, tak jak pomaganie innym z pytaniami i ocenianie Pull Requestów z tłumaczeniami. + +Dane są obliczane każdego miesiąca, możesz przeczytać kod źródłowy tutaj. + +Tutaj również podkreślam wkład od sponsorów. + +Zastrzegam sobie prawo do aktualizacji algorytmu, sekcji, progów itp. (na wszelki wypadek 🤷). diff --git a/docs/pl/docs/index.md b/docs/pl/docs/index.md index 06fa706bc..83bbe19cf 100644 --- a/docs/pl/docs/index.md +++ b/docs/pl/docs/index.md @@ -33,7 +33,7 @@ hide: --- -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: @@ -115,8 +115,6 @@ Jeżeli tworzysz aplikacje CLI< ## Wymagania -Python 3.8+ - FastAPI oparty jest na: * Starlette dla części webowej. @@ -134,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.
@@ -330,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`: diff --git a/docs/pt/docs/advanced/additional-responses.md b/docs/pt/docs/advanced/additional-responses.md new file mode 100644 index 000000000..7c7d22611 --- /dev/null +++ b/docs/pt/docs/advanced/additional-responses.md @@ -0,0 +1,240 @@ +# 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: + +```Python hl_lines="18 22" +{!../../../docs_src/additional_responses/tutorial001.py!} +``` + +!!! 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: + +```Python hl_lines="19-24 28" +{!../../../docs_src/additional_responses/tutorial002.py!} +``` + +!!! 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: + +```Python hl_lines="20-31" +{!../../../docs_src/additional_responses/tutorial003.py!} +``` + +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: + +```Python hl_lines="13-17 26" +{!../../../docs_src/additional_responses/tutorial004.py!} +``` + +## 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..a7699b324 --- /dev/null +++ b/docs/pt/docs/advanced/additional-status-codes.md @@ -0,0 +1,69 @@ +# 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: + +=== "Python 3.10+" + + ```Python hl_lines="4 25" + {!> ../../../docs_src/additional_status_codes/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="4 25" + {!> ../../../docs_src/additional_status_codes/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="4 26" + {!> ../../../docs_src/additional_status_codes/tutorial001_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip "Dica" + Faça uso da versão `Annotated` quando possível. + + ```Python hl_lines="2 23" + {!> ../../../docs_src/additional_status_codes/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip "Dica" + Faça uso da versão `Annotated` quando possível. + + ```Python hl_lines="4 25" + {!> ../../../docs_src/additional_status_codes/tutorial001.py!} + ``` + +!!! 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..58887f9c8 --- /dev/null +++ b/docs/pt/docs/advanced/advanced-dependencies.md @@ -0,0 +1,138 @@ +# 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__`: + +=== "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 "Dica" + Prefira utilizar a versão `Annotated` se possível. + + ```Python hl_lines="10" + {!> ../../../docs_src/dependencies/tutorial011.py!} + ``` + +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: + +=== "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 "Dica" + Prefira utilizar a versão `Annotated` se possível. + + ```Python hl_lines="7" + {!> ../../../docs_src/dependencies/tutorial011.py!} + ``` + +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: + +=== "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 "Dica" + Prefira utilizar a versão `Annotated` se possível. + + ```Python hl_lines="16" + {!> ../../../docs_src/dependencies/tutorial011.py!} + ``` + +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`: + +=== "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" + + !!! tip "Dica" + Prefira utilizar a versão `Annotated` se possível. + + ```Python hl_lines="20" + {!> ../../../docs_src/dependencies/tutorial011.py!} + ``` + +!!! 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..4ccc0c452 --- /dev/null +++ b/docs/pt/docs/advanced/async-tests.md @@ -0,0 +1,95 @@ +# 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: + +```Python +{!../../../docs_src/async_tests/main.py!} +``` + +O arquivo `test_main.py` teria os testes para para o arquivo `main.py`, ele poderia ficar assim: + +```Python +{!../../../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: + +```Python hl_lines="7" +{!../../../docs_src/async_tests/test_main.py!} +``` + +!!! 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`. + +```Python hl_lines="9-10" +{!../../../docs_src/async_tests/test_main.py!} +``` + +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/benchmarks.md b/docs/pt/docs/advanced/benchmarks.md new file mode 100644 index 000000000..72ef1e444 --- /dev/null +++ b/docs/pt/docs/advanced/benchmarks.md @@ -0,0 +1,34 @@ +# Benchmarks + +Benchmarks independentes da TechEmpower mostram que aplicações **FastAPI** rodando com o Uvicorn como um dos frameworks Python mais rápidos disponíveis, ficando atrás apenas do Starlette e Uvicorn (utilizado internamente pelo FastAPI). + +Porém, ao verificar benchmarks e comparações você deve prestar atenção ao seguinte: + +## Benchmarks e velocidade + +Quando você verifica os benchmarks, é comum ver diversas ferramentas de diferentes tipos comparados como se fossem equivalentes. + +Especificamente, para ver o Uvicorn, Starlette e FastAPI comparados entre si (entre diversas outras ferramentas). + +Quanto mais simples o problema resolvido pela ferramenta, melhor será a performance. E a maioria das análises não testa funcionalidades adicionais que são oferecidas pela ferramenta. + +A hierarquia é: + +* **Uvicorn**: um servidor ASGI + * **Starlette**: (utiliza Uvicorn) um microframework web + * **FastAPI**: (utiliza Starlette) um microframework para APIs com diversas funcionalidades adicionais para a construção de APIs, com validação de dados, etc. + +* **Uvicorn**: + * Terá a melhor performance, pois não possui muito código além do próprio servidor. + * Você não escreveria uma aplicação utilizando o Uvicorn diretamente. Isso significaria que o seu código teria que incluir pelo menos todo o código fornecido pelo Starlette (ou o **FastAPI**). E caso você fizesse isso, a sua aplicação final teria a mesma sobrecarga que teria se utilizasse um framework, minimizando o código e os bugs. + * Se você está comparando o Uvicorn, compare com os servidores de aplicação Daphne, Hypercorn, uWSGI, etc. +* **Starlette**: + * Terá o melhor desempenho, depois do Uvicorn. Na verdade, o Starlette utiliza o Uvicorn para rodar. Portanto, ele pode ficar mais "devagar" que o Uvicorn apenas por ter que executar mais código. + * Mas ele fornece as ferramentas para construir aplicações web simples, com roteamento baseado em caminhos, etc. + * Se você está comparando o Starlette, compare-o com o Sanic, Flask, Django, etc. Frameworks web (ou microframeworks). +* **FastAPI**: + * Da mesma forma que o Starlette utiliza o Uvicorn e não consegue ser mais rápido que ele, o **FastAPI** utiliza o Starlette, portanto, ele não consegue ser mais rápido que ele. + * O FastAPI provê mais funcionalidades em cima do Starlette. Funcionalidades que você quase sempre precisará quando estiver construindo APIs, como validação de dados e serialização. E ao utilizá-lo, você obtém documentação automática sem custo nenhum (a documentação automática sequer adiciona sobrecarga nas aplicações rodando, pois ela é gerada na inicialização). + * Caso você não utilize o FastAPI e faz uso do Starlette diretamente (ou outra ferramenta, como o Sanic, Flask, Responder, etc) você mesmo teria que implementar toda a validação de dados e serialização. Então, a sua aplicação final ainda teria a mesma sobrecarga caso estivesse usando o FastAPI. E em muitos casos, validação de dados e serialização é a maior parte do código escrito em aplicações. + * Então, ao utilizar o FastAPI, você está economizando tempo de programação, evitando bugs, linhas de código, e provavelmente terá a mesma performance (ou até melhor) do que teria caso você não o utilizasse (já que você teria que implementar tudo no seu código). + * Se você está comparando o FastAPI, compare-o com frameworks de aplicações web (ou conjunto de ferramentas) que oferecem validação de dados, serialização e documentação, como por exemplo o Flask-apispec, NestJS, Molten, etc. Frameworks que possuem validação integrada de dados, serialização e documentação. diff --git a/docs/pt/docs/advanced/openapi-webhooks.md b/docs/pt/docs/advanced/openapi-webhooks.md new file mode 100644 index 000000000..932fe0d9a --- /dev/null +++ b/docs/pt/docs/advanced/openapi-webhooks.md @@ -0,0 +1,51 @@ +# 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()`. + +```Python hl_lines="9-13 36-53" +{!../../../docs_src/openapi_webhooks/tutorial001.py!} +``` + +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/settings.md b/docs/pt/docs/advanced/settings.md new file mode 100644 index 000000000..f6962831f --- /dev/null +++ b/docs/pt/docs/advanced/settings.md @@ -0,0 +1,485 @@ +# 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 + +!!! 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: + +=== "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 + ``` + +
+ +=== "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") +``` + +!!! 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 +``` + +
+ +!!! 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()`. + +=== "Pydantic v2" + + ```Python hl_lines="2 5-8 11" + {!> ../../../docs_src/settings/tutorial001.py!} + ``` + +=== "Pydantic v1" + + !!! Info + Na versão 1 do Pydantic você importaria `BaseSettings` diretamente do módulo `pydantic` em vez do módulo `pydantic_settings`. + + ```Python hl_lines="2 5-8 11" + {!> ../../../docs_src/settings/tutorial001_pv1.py!} + ``` + +!!! 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: + +```Python hl_lines="18-20" +{!../../../docs_src/settings/tutorial001.py!} +``` + +### 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) +``` + +
+ +!!! 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: + +```Python +{!../../../docs_src/settings/app01/config.py!} +``` + +E utilizar essa configuração em `main.py`: + +```Python hl_lines="3 11-13" +{!../../../docs_src/settings/app01/main.py!} +``` + +!!! 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: + +```Python hl_lines="10" +{!../../../docs_src/settings/app02/config.py!} +``` + +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()`. + +=== "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+ non-Annotated" + + !!! dica + Utilize a versão com `Annotated` se possível. + + ```Python hl_lines="5 11-12" + {!> ../../../docs_src/settings/app02/main.py!} + ``` + +!!! 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. + +=== "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" + + !!! dica + Utilize a versão com `Annotated` se possível. + + ```Python hl_lines="16 18-20" + {!> ../../../docs_src/settings/app02/main.py!} + ``` + +### 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`: + +```Python hl_lines="9-10 13 21" +{!../../../docs_src/settings/app02/test_main.py!} +``` + +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". + +!!! 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. + +!!! 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`: + +=== "Pydantic v2" + + ```Python hl_lines="9" + {!> ../../../docs_src/settings/app03_an/config.py!} + ``` + + !!! dica + O atributo `model_config` é usado apenas para configuração do Pydantic. Você pode ler mais em Pydantic Model Config. + +=== "Pydantic v1" + + ```Python hl_lines="9-10" + {!> ../../../docs_src/settings/app03_an/config_pv1.py!} + ``` + + !!! 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. ✔️ + +=== "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" + + !!! dica + Utilize a versão com `Annotated` se possível. + + ```Python hl_lines="1 10" + {!> ../../../docs_src/settings/app03/main.py!} + ``` + +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/deployment.md b/docs/pt/docs/deployment.md index 2272467fd..d25ea79fd 100644 --- a/docs/pt/docs/deployment.md +++ b/docs/pt/docs/deployment.md @@ -345,7 +345,7 @@ Você apenas precisa instalar um servidor ASGI compatível como: === "Hypercorn" - * Hypercorn, um servidor ASGI também compatível com HTTP/2. + * Hypercorn, um servidor ASGI também compatível com HTTP/2.
diff --git a/docs/pt/docs/fastapi-cli.md b/docs/pt/docs/fastapi-cli.md new file mode 100644 index 000000000..a4dfda660 --- /dev/null +++ b/docs/pt/docs/fastapi-cli.md @@ -0,0 +1,84 @@ +# 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/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/index.md b/docs/pt/docs/how-to/index.md new file mode 100644 index 000000000..664e89144 --- /dev/null +++ b/docs/pt/docs/how-to/index.md @@ -0,0 +1,11 @@ +# 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/index.md b/docs/pt/docs/index.md index 86b77f117..6e7aa21f7 100644 --- a/docs/pt/docs/index.md +++ b/docs/pt/docs/index.md @@ -33,7 +33,7 @@ hide: --- -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: @@ -109,8 +109,6 @@ Se você estiver construindo uma aplicação Starlette para as partes web. @@ -128,7 +126,7 @@ $ pip install fastapi
-Você também precisará de um servidor ASGI para produção, tal como Uvicorn ou Hypercorn. +Você também precisará de um servidor ASGI para produção, tal como Uvicorn ou Hypercorn.
@@ -325,7 +323,7 @@ Você faz com tipos padrão do Python moderno. Você não terá que aprender uma nova sintaxe, métodos ou classes de uma biblioteca específica etc. -Apenas **Python 3.8+** padrão. +Apenas **Python** padrão. Por exemplo, para um `int`: diff --git a/docs/pt/docs/reference/apirouter.md b/docs/pt/docs/reference/apirouter.md new file mode 100644 index 000000000..7568601c9 --- /dev/null +++ b/docs/pt/docs/reference/apirouter.md @@ -0,0 +1,24 @@ +# Classe `APIRouter` + +Aqui está a informação de referência para a classe `APIRouter`, com todos os seus parâmetros, atributos e métodos. + +Você pode importar a classe `APIRouter` diretamente do `fastapi`: + +```python +from fastapi import APIRouter +``` + +::: fastapi.APIRouter + options: + members: + - websocket + - include_router + - get + - put + - post + - delete + - options + - head + - patch + - trace + - on_event diff --git a/docs/pt/docs/reference/background.md b/docs/pt/docs/reference/background.md new file mode 100644 index 000000000..bfc15aa76 --- /dev/null +++ b/docs/pt/docs/reference/background.md @@ -0,0 +1,11 @@ +# Tarefas em Segundo Plano - `BackgroundTasks` + +Você pode declarar um parâmetro em uma *função de operação de rota* ou em uma função de dependência com o tipo `BackgroundTasks`, e então utilizá-lo para agendar a execução de tarefas em segundo plano após o envio da resposta. + +Você pode importá-lo diretamente do `fastapi`: + +```python +from fastapi import BackgroundTasks +``` + +::: fastapi.BackgroundTasks diff --git a/docs/pt/docs/reference/exceptions.md b/docs/pt/docs/reference/exceptions.md new file mode 100644 index 000000000..d6b5d2613 --- /dev/null +++ b/docs/pt/docs/reference/exceptions.md @@ -0,0 +1,20 @@ +# Exceções - `HTTPException` e `WebSocketException` + +Essas são as exceções que você pode lançar para mostrar erros ao cliente. + +Quando você lança uma exceção, como aconteceria com o Python normal, o restante da execução é abortado. Dessa forma, você pode lançar essas exceções de qualquer lugar do código para abortar uma solicitação e mostrar o erro ao cliente. + +Você pode usar: + +* `HTTPException` +* `WebSocketException` + +Essas exceções podem ser importadas diretamente do `fastapi`: + +```python +from fastapi import HTTPException, WebSocketException +``` + +::: fastapi.HTTPException + +::: fastapi.WebSocketException diff --git a/docs/pt/docs/reference/index.md b/docs/pt/docs/reference/index.md new file mode 100644 index 000000000..533a6a996 --- /dev/null +++ b/docs/pt/docs/reference/index.md @@ -0,0 +1,6 @@ +# Referência - API de Código + +Aqui está a referência ou API de código, as classes, funções, parâmetros, atributos e todas as partes do FastAPI que você pode usar em suas aplicações. + +Se você quer **aprender FastAPI**, é muito melhor ler o +[FastAPI Tutorial](https://fastapi.tiangolo.com/tutorial/). 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..028bf3d20 --- /dev/null +++ b/docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md @@ -0,0 +1,497 @@ +# 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"): + +=== "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.8+" + + ```Python hl_lines="12" + {!> ../../../docs_src/dependencies/tutorial001_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + ```Python hl_lines="7" + {!> ../../../docs_src/dependencies/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + ```Python hl_lines="11" + {!> ../../../docs_src/dependencies/tutorial001.py!} + ``` + +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`: + +=== "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.8+" + + ```Python hl_lines="12-16" + {!> ../../../docs_src/dependencies/tutorial002_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + + ```Python hl_lines="9-13" + {!> ../../../docs_src/dependencies/tutorial002_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + + ```Python hl_lines="11-15" + {!> ../../../docs_src/dependencies/tutorial002.py!} + ``` + +Observe o método `__init__` usado para criar uma instância da classe: + +=== "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.8+" + + ```Python hl_lines="13" + {!> ../../../docs_src/dependencies/tutorial002_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + + ```Python hl_lines="10" + {!> ../../../docs_src/dependencies/tutorial002_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + + ```Python hl_lines="12" + {!> ../../../docs_src/dependencies/tutorial002.py!} + ``` + +...ele possui os mesmos parâmetros que nosso `common_parameters` anterior: + +=== "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.8+" + + ```Python hl_lines="10" + {!> ../../../docs_src/dependencies/tutorial001_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + + ```Python hl_lines="6" + {!> ../../../docs_src/dependencies/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + + ```Python hl_lines="9" + {!> ../../../docs_src/dependencies/tutorial001.py!} + ``` + +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. + +=== "Python 3.10+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="20" + {!> ../../../docs_src/dependencies/tutorial002_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + + ```Python hl_lines="17" + {!> ../../../docs_src/dependencies/tutorial002_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial002.py!} + ``` + +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: + +=== "Python 3.8+" + + ```Python + commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] + ``` + +=== "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: + +=== "Python 3.8+" + + ```Python + commons: Annotated[CommonQueryParams, ... + ``` + +=== "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: + +=== "Python 3.8+" + + ```Python + commons: Annotated[Any, Depends(CommonQueryParams)] + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + + ```Python + commons = Depends(CommonQueryParams) + ``` + +...como em: + +=== "Python 3.10+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial003_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial003_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="20" + {!> ../../../docs_src/dependencies/tutorial003_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + + ```Python hl_lines="17" + {!> ../../../docs_src/dependencies/tutorial003_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial003.py!} + ``` + +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: + +=== "Python 3.8+" + + ```Python + commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] + ``` + +=== "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: + +=== "Python 3.8+" + + ```Python + commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + ```Python + commons: CommonQueryParams = Depends(CommonQueryParams) + ``` + +...escreva: + +=== "Python 3.8+" + + ```Python + commons: Annotated[CommonQueryParams, Depends()] + ``` + +=== "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: + +=== "Python 3.10+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial004_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial004_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="20" + {!> ../../../docs_src/dependencies/tutorial004_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + + ```Python hl_lines="17" + {!> ../../../docs_src/dependencies/tutorial004_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial004.py!} + ``` + +...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..4a297268c --- /dev/null +++ b/docs/pt/docs/tutorial/dependencies/dependencies-in-path-operation-decorators.md @@ -0,0 +1,138 @@ +# 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()`: + +=== "Python 3.9+" + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="18" + {!> ../../../docs_src/dependencies/tutorial006_an.py!} + ``` + +=== "Python 3.8 non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível + + ```Python hl_lines="17" + {!> ../../../docs_src/dependencies/tutorial006.py!} + ``` +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: + +=== "Python 3.9+" + + ```Python hl_lines="8 13" + {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="7 12" + {!> ../../../docs_src/dependencies/tutorial006_an.py!} + ``` + +=== "Python 3.8 non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível + + ```Python hl_lines="6 11" + {!> ../../../docs_src/dependencies/tutorial006.py!} + ``` + +### Levantando exceções + +Essas dependências podem levantar exceções, da mesma forma que dependências comuns: + +=== "Python 3.9+" + + ```Python hl_lines="10 15" + {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9 14" + {!> ../../../docs_src/dependencies/tutorial006_an.py!} + ``` + +=== "Python 3.8 non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível + + ```Python hl_lines="8 13" + {!> ../../../docs_src/dependencies/tutorial006.py!} + ``` + +### 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: + +=== "Python 3.9+" + + ```Python hl_lines="11 16" + {!> ../../../docs_src/dependencies/tutorial006_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="10 15" + {!> ../../../docs_src/dependencies/tutorial006_an.py!} + ``` + +=== "Python 3.8 non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível + + ```Python hl_lines="9 14" + {!> ../../../docs_src/dependencies/tutorial006.py!} + ``` + +## 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..8b4175fc5 --- /dev/null +++ b/docs/pt/docs/tutorial/dependencies/dependencies-with-yield.md @@ -0,0 +1,349 @@ +# 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. + +```Python hl_lines="2-4" +{!../../../docs_src/dependencies/tutorial007.py!} +``` + +O valor gerado (yielded) é o que é injetado nas *operações de rota* e outras dependências. + +```Python hl_lines="4" +{!../../../docs_src/dependencies/tutorial007.py!} +``` + +O código após o `yield` é executado após a resposta ser entregue: + +```Python hl_lines="5-6" +{!../../../docs_src/dependencies/tutorial007.py!} +``` + +!!! 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`: + +=== "python 3.9+" + + ```python hl_lines="6 14 22" + {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} + ``` + +=== "python 3.8+" + + ```python hl_lines="5 13 21" + {!> ../../../docs_src/dependencies/tutorial008_an.py!} + ``` + +=== "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. + +=== "python 3.9+" + + ```python hl_lines="18-19 26-27" + {!> ../../../docs_src/dependencies/tutorial008_an_py39.py!} + ``` + +=== "python 3.8+" + + ```python hl_lines="17-18 25-26" + {!> ../../../docs_src/dependencies/tutorial008_an.py!} + ``` + +=== "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. 🤓 + +=== "python 3.9+" + + ```python hl_lines="18-22 31" + {!> ../../../docs_src/dependencies/tutorial008b_an_py39.py!} + ``` + +=== "python 3.8+" + + ```python hl_lines="17-21 30" + {!> ../../../docs_src/dependencies/tutorial008b_an.py!} + ``` + +=== "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: + +=== "Python 3.9+" + + ```Python hl_lines="15-16" + {!> ../../../docs_src/dependencies/tutorial008c_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="14-15" + {!> ../../../docs_src/dependencies/tutorial008c_an.py!} + ``` + +=== "Python 3.8+ non-annotated" + + !!! tip "dica" + utilize a versão com `Annotated` se possível. + + ```Python hl_lines="13-14" + {!> ../../../docs_src/dependencies/tutorial008c.py!} + ``` + +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`: + +=== "Python 3.9+" + + ```Python hl_lines="17" + {!> ../../../docs_src/dependencies/tutorial008d_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="16" + {!> ../../../docs_src/dependencies/tutorial008d_an.py!} + ``` + +=== "python 3.8+ non-annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + ```Python hl_lines="15" + {!> ../../../docs_src/dependencies/tutorial008d.py!} + ``` + +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: + +```Python hl_lines="1-9 13" +{!../../../docs_src/dependencies/tutorial010.py!} +``` + +!!! 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..3eb5faa34 --- /dev/null +++ b/docs/pt/docs/tutorial/dependencies/global-dependencies.md @@ -0,0 +1,34 @@ +# 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: + +=== "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 "Dica" + Utilize a versão com `Annotated` se possível. + + ```Python hl_lines="15" + {!> ../../../docs_src/dependencies/tutorial012.py!} + ``` + +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..3c0155a6e --- /dev/null +++ b/docs/pt/docs/tutorial/dependencies/index.md @@ -0,0 +1,353 @@ +# 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*: + +=== "Python 3.10+" + + ```Python hl_lines="8-9" + {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="8-11" + {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9-12" + {!> ../../../docs_src/dependencies/tutorial001_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + ```Python hl_lines="6-7" + {!> ../../../docs_src/dependencies/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + ```Python hl_lines="8-11" + {!> ../../../docs_src/dependencies/tutorial001.py!} + ``` + +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` + +=== "Python 3.10+" + + ```Python hl_lines="3" + {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="3" + {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="3" + {!> ../../../docs_src/dependencies/tutorial001_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + ```Python hl_lines="1" + {!> ../../../docs_src/dependencies/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + ```Python hl_lines="3" + {!> ../../../docs_src/dependencies/tutorial001.py!} + ``` + +### 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: + +=== "Python 3.10+" + + ```Python hl_lines="13 18" + {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="15 20" + {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="16 21" + {!> ../../../docs_src/dependencies/tutorial001_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + ```Python hl_lines="11 16" + {!> ../../../docs_src/dependencies/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + ```Python hl_lines="15 20" + {!> ../../../docs_src/dependencies/tutorial001.py!} + ``` + +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: + +=== "Python 3.10+" + + ```Python hl_lines="12 16 21" + {!> ../../../docs_src/dependencies/tutorial001_02_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="14 18 23" + {!> ../../../docs_src/dependencies/tutorial001_02_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="15 19 24" + {!> ../../../docs_src/dependencies/tutorial001_02_an.py!} + ``` + +!!! 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..189f196ab --- /dev/null +++ b/docs/pt/docs/tutorial/dependencies/sub-dependencies.md @@ -0,0 +1,194 @@ +# 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: + +=== "Python 3.10+" + + ```Python hl_lines="8-9" + {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="8-9" + {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="9-10" + {!> ../../../docs_src/dependencies/tutorial005_an.py!} + ``` + +=== "Python 3.10 non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + ```Python hl_lines="6-7" + {!> ../../../docs_src/dependencies/tutorial005_py310.py!} + ``` + +=== "Python 3.8 non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + ```Python hl_lines="8-9" + {!> ../../../docs_src/dependencies/tutorial005.py!} + ``` + +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): + +=== "Python 3.10+" + + ```Python hl_lines="13" + {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="13" + {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="14" + {!> ../../../docs_src/dependencies/tutorial005_an.py!} + ``` + +=== "Python 3.10 non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + ```Python hl_lines="11" + {!> ../../../docs_src/dependencies/tutorial005_py310.py!} + ``` + +=== "Python 3.8 non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + ```Python hl_lines="13" + {!> ../../../docs_src/dependencies/tutorial005.py!} + ``` + +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: + +=== "Python 3.10+" + + ```Python hl_lines="23" + {!> ../../../docs_src/dependencies/tutorial005_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="23" + {!> ../../../docs_src/dependencies/tutorial005_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="24" + {!> ../../../docs_src/dependencies/tutorial005_an.py!} + ``` + +=== "Python 3.10 non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial005_py310.py!} + ``` + +=== "Python 3.8 non-Annotated" + + !!! tip "Dica" + Utilize a versão com `Annotated` se possível. + + ```Python hl_lines="22" + {!> ../../../docs_src/dependencies/tutorial005.py!} + ``` + +!!! 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`: + +=== "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} + ``` + +=== "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/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/deployment/manually.md b/docs/ru/docs/deployment/manually.md index a24580489..0b24c0695 100644 --- a/docs/ru/docs/deployment/manually.md +++ b/docs/ru/docs/deployment/manually.md @@ -5,7 +5,7 @@ Существует три наиболее распространённые альтернативы: * Uvicorn: высокопроизводительный ASGI сервер. -* Hypercorn: ASGI сервер, помимо прочего поддерживающий HTTP/2 и Trio. +* Hypercorn: ASGI сервер, помимо прочего поддерживающий HTTP/2 и Trio. * Daphne: ASGI сервер, созданный для Django Channels. ## Сервер как машина и сервер как программа @@ -46,7 +46,7 @@ === "Hypercorn" - * Hypercorn, ASGI сервер, поддерживающий протокол HTTP/2. + * Hypercorn, ASGI сервер, поддерживающий протокол HTTP/2.
diff --git a/docs/ru/docs/index.md b/docs/ru/docs/index.md index 81c3835d9..d59f45031 100644 --- a/docs/ru/docs/index.md +++ b/docs/ru/docs/index.md @@ -36,7 +36,7 @@ hide: --- -FastAPI — это современный, быстрый (высокопроизводительный) веб-фреймворк для создания API используя Python 3.8+, в основе которого лежит стандартная аннотация типов Python. +FastAPI — это современный, быстрый (высокопроизводительный) веб-фреймворк для создания API используя Python, в основе которого лежит стандартная аннотация типов Python. Ключевые особенности: @@ -118,8 +118,6 @@ FastAPI — это современный, быстрый (высокопрои ## Зависимости -Python 3.8+ - FastAPI стоит на плечах гигантов: * Starlette для части связанной с вебом. @@ -137,7 +135,7 @@ $ pip install fastapi
-Вам также понадобится сервер ASGI для производства, такой как Uvicorn или Hypercorn. +Вам также понадобится сервер ASGI для производства, такой как Uvicorn или Hypercorn.
@@ -334,7 +332,7 @@ def update_item(item_id: int, item: Item): Вам не нужно изучать новый синтаксис, методы или классы конкретной библиотеки и т. д. -Только стандартный **Python 3.8+**. +Только стандартный **Python**. Например, для `int`: diff --git a/docs/tr/docs/advanced/index.md b/docs/tr/docs/advanced/index.md new file mode 100644 index 000000000..c0a566d12 --- /dev/null +++ b/docs/tr/docs/advanced/index.md @@ -0,0 +1,33 @@ +# 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..89a431687 --- /dev/null +++ b/docs/tr/docs/advanced/security/index.md @@ -0,0 +1,16 @@ +# 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..cdd5b7ae5 --- /dev/null +++ b/docs/tr/docs/advanced/testing-websockets.md @@ -0,0 +1,12 @@ +# 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: + +```Python hl_lines="27-31" +{!../../../docs_src/app_testing/tutorial002.py!} +``` + +!!! 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..54a6f20e2 --- /dev/null +++ b/docs/tr/docs/advanced/wsgi.md @@ -0,0 +1,37 @@ +# 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. + +```Python hl_lines="2-3 23" +{!../../../docs_src/wsgi/tutorial001.py!} +``` + +## 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/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/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/index.md b/docs/tr/docs/index.md index 67a9b4462..f7a8cf2a5 100644 --- a/docs/tr/docs/index.md +++ b/docs/tr/docs/index.md @@ -36,7 +36,7 @@ hide: --- -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: @@ -124,8 +124,6 @@ Eğer API yerine, terminalde kullanılmak üzere bir Starlette. @@ -143,7 +141,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.
@@ -340,7 +338,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: diff --git a/docs/tr/docs/tutorial/cookie-params.md b/docs/tr/docs/tutorial/cookie-params.md new file mode 100644 index 000000000..4a66f26eb --- /dev/null +++ b/docs/tr/docs/tutorial/cookie-params.md @@ -0,0 +1,97 @@ +# Ç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: + +=== "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 "İpucu" + Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. + + ```Python hl_lines="1" + {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip "İpucu" + Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. + + ```Python hl_lines="3" + {!> ../../../docs_src/cookie_params/tutorial001.py!} + ``` + +## `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: + +=== "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 "İpucu" + Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. + + ```Python hl_lines="7" + {!> ../../../docs_src/cookie_params/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip "İpucu" + Mümkün mertebe 'Annotated' sınıfını kullanmaya çalışın. + + ```Python hl_lines="9" + {!> ../../../docs_src/cookie_params/tutorial001.py!} + ``` + +!!! 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/request-forms.md b/docs/tr/docs/tutorial/request-forms.md new file mode 100644 index 000000000..2728b6164 --- /dev/null +++ b/docs/tr/docs/tutorial/request-forms.md @@ -0,0 +1,92 @@ +# 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: + +=== "Python 3.9+" + + ```Python hl_lines="3" + {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="1" + {!> ../../../docs_src/request_forms/tutorial001_an.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + Prefer to use the `Annotated` version if possible. + + ```Python hl_lines="1" + {!> ../../../docs_src/request_forms/tutorial001.py!} + ``` + +## `Form` Parametrelerini Tanımlayın + +Form parametrelerini `Body` veya `Query` için yaptığınız gibi oluşturun: + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/request_forms/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="8" + {!> ../../../docs_src/request_forms/tutorial001_an.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + Prefer to use the `Annotated` version if possible. + + ```Python hl_lines="7" + {!> ../../../docs_src/request_forms/tutorial001.py!} + ``` + +Ö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..00c833686 --- /dev/null +++ b/docs/tr/docs/tutorial/static-files.md @@ -0,0 +1,39 @@ +# 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. + +```Python hl_lines="2 6" +{!../../../docs_src/static_files/tutorial001.py!} +``` + +!!! 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/index.md b/docs/uk/docs/index.md index bb21b68c2..29e19025a 100644 --- a/docs/uk/docs/index.md +++ b/docs/uk/docs/index.md @@ -27,7 +27,7 @@ --- -FastAPI - це сучасний, швидкий (високопродуктивний), вебфреймворк для створення API за допомогою Python 3.8+,в основі якого лежить стандартна анотація типів Python. +FastAPI - це сучасний, швидкий (високопродуктивний), вебфреймворк для створення API за допомогою Python,в основі якого лежить стандартна анотація типів Python. Ключові особливості: @@ -110,8 +110,6 @@ FastAPI - це сучасний, швидкий (високопродуктив ## Вимоги -Python 3.8+ - FastAPI стоїть на плечах гігантів: * Starlette для web частини. @@ -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`: diff --git a/docs/uk/docs/tutorial/first-steps.md b/docs/uk/docs/tutorial/first-steps.md new file mode 100644 index 000000000..725677e42 --- /dev/null +++ b/docs/uk/docs/tutorial/first-steps.md @@ -0,0 +1,328 @@ +# Перші кроки + +Найпростіший файл FastAPI може виглядати так: + +```Python +{!../../../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` + +```Python hl_lines="1" +{!../../../docs_src/first_steps/tutorial001.py!} +``` + +`FastAPI` це клас у Python, який надає всю функціональність для API. + +!!! note "Технічні деталі" + `FastAPI` це клас, який успадковується безпосередньо від `Starlette`. + + Ви також можете використовувати всю функціональність Starlette у `FastAPI`. + +### Крок 2: створюємо екземпляр `FastAPI` + +```Python hl_lines="3" +{!../../../docs_src/first_steps/tutorial001.py!} +``` +Змінна `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) + +```Python hl_lines="6" +{!../../../docs_src/first_steps/tutorial001.py!} +``` +Декоратор `@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("/")`). + +```Python hl_lines="7" +{!../../../docs_src/first_steps/tutorial001.py!} +``` + +Це звичайна функція Python. + +FastAPI викликатиме її щоразу, коли отримає запит до URL із шляхом "/", використовуючи операцію `GET`. + +У даному випадку це асинхронна функція. + +--- + +Ви також можете визначити її як звичайну функцію замість `async def`: + +```Python hl_lines="7" +{!../../../docs_src/first_steps/tutorial003.py!} +``` + +!!! note "Примітка" + Якщо не знаєте в чому різниця, подивіться [Конкурентність: *"Поспішаєш?"*](../async.md#in-a-hurry){.internal-link target=_blank}. + +### Крок 5: поверніть результат + +```Python hl_lines="8" +{!../../../docs_src/first_steps/tutorial001.py!} +``` + +Ви можете повернути `dict`, `list`, а також окремі значення `str`, `int`, ітд. + +Також можна повернути моделі Pydantic (про це ви дізнаєтесь пізніше). + +Існує багато інших об'єктів і моделей, які будуть автоматично конвертовані в JSON (зокрема ORM тощо). Спробуйте використати свої улюблені, велика ймовірність, що вони вже підтримуються. + +## Підіб'ємо підсумки + +* Імпортуємо `FastAPI`. +* Створюємо екземпляр `app`. +* Пишемо **декоратор операції шляху** як `@app.get("/")`. +* Пишемо **функцію операції шляху**; наприклад, `def root(): ...`. +* Запускаємо сервер у режимі розробки `fastapi dev`. diff --git a/docs/vi/docs/index.md b/docs/vi/docs/index.md index 652218afa..b13f91fb7 100644 --- a/docs/vi/docs/index.md +++ b/docs/vi/docs/index.md @@ -36,7 +36,7 @@ hide: --- -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ư: @@ -125,8 +125,6 @@ Nếu bạn đang xây dựng một CLIStarlette cho phần web. @@ -341,7 +339,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`: diff --git a/docs/yo/docs/index.md b/docs/yo/docs/index.md index 352bf4df8..9bd21c4b9 100644 --- a/docs/yo/docs/index.md +++ b/docs/yo/docs/index.md @@ -36,7 +36,7 @@ hide: --- -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: @@ -124,8 +124,6 @@ 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. @@ -340,7 +338,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`: diff --git a/docs/zh-hant/docs/benchmarks.md b/docs/zh-hant/docs/benchmarks.md new file mode 100644 index 000000000..cbd5a6cde --- /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/fastapi-people.md b/docs/zh-hant/docs/fastapi-people.md new file mode 100644 index 000000000..0bc00f9c6 --- /dev/null +++ b/docs/zh-hant/docs/fastapi-people.md @@ -0,0 +1,236 @@ +--- +hide: + - navigation +--- + +# FastAPI 社群 + +FastAPI 有一個非常棒的社群,歡迎來自不同背景的朋友參與。 + +## 作者 + +嘿! 👋 + +關於我: + +{% if people %} +
+{% for user in people.maintainers %} + +
@{{ user.login }}
解答問題: {{ 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-questions-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}。 + +讓我們為他們熱烈鼓掌。 👏 🙇 + +## FastAPI 專家 + +這些是在 [GitHub 中幫助其他人解決問題最多的用戶](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}。 🙇 + +他們透過幫助其他人,證明了自己是 **FastAPI 專家**。 ✨ + +!!! 提示 + 你也可以成為官方的 FastAPI 專家! + + 只需要在 [GitHub 中幫助他人解答問題](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}。 🤓 + +你可以查看這些期間的 **FastAPI 專家**: + +* [上個月](#fastapi-experts-last-month) 🤓 +* [過去 3 個月](#fastapi-experts-3-months) 😎 +* [過去 6 個月](#fastapi-experts-6-months) 🧐 +* [過去 1 年](#fastapi-experts-1-year) 🧑‍🔬 +* [**所有時間**](#fastapi-experts-all-time) 🧙 + +### FastAPI 專家 - 上個月 + +上個月在 [GitHub 中幫助他人解決問題最多的](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}用戶。 🤓 + +{% if people %} +
+{% for user in people.last_month_experts[:10] %} + +
@{{ user.login }}
回答問題數: {{ user.count }}
+{% endfor %} + +
+{% endif %} + +### FastAPI 專家 - 過去 3 個月 + +過去三個月在 [GitHub 中幫助他人解決問題最多的](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}用戶。 😎 + +{% if people %} +
+{% for user in people.three_months_experts[:10] %} + +
@{{ user.login }}
回答問題數: {{ user.count }}
+{% endfor %} + +
+{% endif %} + +### FastAPI 專家 - 過去 6 個月 + +過去六個月在 [GitHub 中幫助他人解決問題最多的](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}用戶。 🧐 + +{% if people %} +
+{% for user in people.six_months_experts[:10] %} + +
@{{ user.login }}
回答問題數: {{ user.count }}
+{% endfor %} + +
+{% endif %} + +### FastAPI 專家 - 過去一年 + +過去一年在 [GitHub 中幫助他人解決最多問題的](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}用戶。 🧑‍🔬 + +{% if people %} +
+{% for user in people.one_year_experts[:20] %} + +
@{{ user.login }}
回答問題數: {{ user.count }}
+{% endfor %} + +
+{% endif %} + +### FastAPI 專家 - 全部時間 + +以下是全部時間的 **FastAPI 專家**。 🤓🤯 + +過去在 [GitHub 中幫助他人解決問題最多的](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}用戶。 🧙 + +{% if people %} +
+{% for user in people.experts[:50] %} + +
@{{ user.login }}
回答問題數: {{ 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[:50] %} + +
@{{ user.login }}
Pull Requests: {{ user.count }}
+{% endfor %} + +
+{% endif %} + +還有許多其他的貢獻者(超過一百位),你可以在 FastAPI GitHub 貢獻者頁面查看。 👷 + +## 主要翻譯審核者 + +以下是 **主要翻譯審核者**。 🕵️ + +我只會講幾種語言(而且不是很流利 😅),所以審核者[**擁有批准翻譯**](contributing.md#translations){.internal-link target=_blank}文件的權限。沒有他們,就不會有多語言版本的文件。 + +{% if people %} +
+{% for user in people.top_translations_reviewers[:50] %} + +
@{{ 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-hant/docs/index.md b/docs/zh-hant/docs/index.md index f90eb2177..cdd98ae84 100644 --- a/docs/zh-hant/docs/index.md +++ b/docs/zh-hant/docs/index.md @@ -27,7 +27,7 @@ --- -FastAPI 是一個現代、快速(高效能)的 web 框架,用於 Python 3.8+ 並採用標準 Python 型別提示。 +FastAPI 是一個現代、快速(高效能)的 web 框架,用於 Python 並採用標準 Python 型別提示。 主要特點包含: @@ -115,8 +115,6 @@ FastAPI 是一個現代、快速(高效能)的 web 框架,用於 Python 3. ## 安裝需求 -Python 3.8+ - FastAPI 是站在以下巨人的肩膀上: - Starlette 負責網頁的部分 @@ -331,7 +329,7 @@ def update_item(item_id: int, item: Item): 你不需要學習新的語法、類別、方法或函式庫等等。 -只需要使用 **Python 3.8 以上的版本**。 +只需要使用 **Python 以上的版本**。 舉個範例,比如宣告 int 的型別: diff --git a/docs/zh/docs/advanced/security/http-basic-auth.md b/docs/zh/docs/advanced/security/http-basic-auth.md index 1f251ca45..ab8961e7c 100644 --- a/docs/zh/docs/advanced/security/http-basic-auth.md +++ b/docs/zh/docs/advanced/security/http-basic-auth.md @@ -14,15 +14,32 @@ HTTP 基础授权让浏览器显示内置的用户名与密码提示。 ## 简单的 HTTP 基础授权 -* 导入 `HTTPBsic` 与 `HTTPBasicCredentials` -* 使用 `HTTPBsic` 创建**安全概图** +* 导入 `HTTPBasic` 与 `HTTPBasicCredentials` +* 使用 `HTTPBasic` 创建**安全概图** * 在*路径操作*的依赖项中使用 `security` * 返回类型为 `HTTPBasicCredentials` 的对象: * 包含发送的 `username` 与 `password` -```Python hl_lines="2 6 10" -{!../../../docs_src/security/tutorial006.py!} -``` +=== "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 + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="2 6 10" + {!> ../../../docs_src/security/tutorial006.py!} + ``` 第一次打开 URL(或在 API 文档中点击 **Execute** 按钮)时,浏览器要求输入用户名与密码: @@ -34,13 +51,35 @@ HTTP 基础授权让浏览器显示内置的用户名与密码提示。 使用依赖项检查用户名与密码是否正确。 -为此要使用 Python 标准模块 `secrets` 检查用户名与密码: +为此要使用 Python 标准模块 `secrets` 检查用户名与密码。 -```Python hl_lines="1 11-13" -{!../../../docs_src/security/tutorial007.py!} -``` +`secrets.compare_digest()` 需要仅包含 ASCII 字符(英语字符)的 `bytes` 或 `str`,这意味着它不适用于像`á`一样的字符,如 `Sebastián`。 + +为了解决这个问题,我们首先将 `username` 和 `password` 转换为使用 UTF-8 编码的 `bytes` 。 + +然后我们可以使用 `secrets.compare_digest()` 来确保 `credentials.username` 是 `"stanleyjobson"`,且 `credentials.password` 是`"swordfish"`。 + +=== "Python 3.9+" + + ```Python hl_lines="1 12-24" + {!> ../../../docs_src/security/tutorial007_an_py39.py!} + ``` -这段代码确保 `credentials.username` 是 `"stanleyjobson"`,且 `credentials.password` 是`"swordfish"`。与以下代码类似: +=== "Python 3.8+" + + ```Python hl_lines="1 12-24" + {!> ../../../docs_src/security/tutorial007_an.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="1 11-21" + {!> ../../../docs_src/security/tutorial007.py!} + ``` +这类似于: ```Python if not (credentials.username == "stanleyjobson") or not (credentials.password == "swordfish"): @@ -102,6 +141,23 @@ if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish": 检测到凭证不正确后,返回 `HTTPException` 及状态码 401(与无凭证时返回的内容一样),并添加请求头 `WWW-Authenticate`,让浏览器再次显示登录提示: -```Python hl_lines="15-19" -{!../../../docs_src/security/tutorial007.py!} -``` +=== "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 + 尽可能选择使用 `Annotated` 的版本。 + + ```Python hl_lines="23-27" + {!> ../../../docs_src/security/tutorial007.py!} + ``` diff --git a/docs/zh/docs/advanced/templates.md b/docs/zh/docs/advanced/templates.md index d735f1697..612b69176 100644 --- a/docs/zh/docs/advanced/templates.md +++ b/docs/zh/docs/advanced/templates.md @@ -20,24 +20,12 @@ $ pip install jinja2
-如需使用静态文件,还要安装 `aiofiles`: - -
- -```console -$ pip install aiofiles - ----> 100% -``` - -
- ## 使用 `Jinja2Templates` * 导入 `Jinja2Templates` * 创建可复用的 `templates` 对象 * 在返回模板的*路径操作*中声明 `Request` 参数 -* 使用 `templates` 渲染并返回 `TemplateResponse`, 以键值对方式在 Jinja2 的 **context** 中传递 `request` +* 使用 `templates` 渲染并返回 `TemplateResponse`, 传递模板的名称、request对象以及一个包含多个键值对(用于Jinja2模板)的"context"字典, ```Python hl_lines="4 11 15-16" {!../../../docs_src/templates/tutorial001.py!} @@ -45,7 +33,8 @@ $ pip install aiofiles !!! note "笔记" - 注意,必须为 Jinja2 以键值对方式在上下文中传递 `request`。因此,还要在*路径操作*中声明。 + 在FastAPI 0.108.0,Starlette 0.29.0之前,`name`是第一个参数。 + 并且,在此之前,`request`对象是作为context的一部分以键值对的形式传递的。 !!! tip "提示" @@ -65,30 +54,68 @@ $ pip install aiofiles {!../../../docs_src/templates/templates/item.html!} ``` -它会显示从 **context** 字典中提取的 `id`: +### 模板上下文 + +在包含如下语句的html中: + +{% raw %} + +```jinja +Item ID: {{ id }} +``` + +{% endraw %} + +...这将显示你从"context"字典传递的 `id`: ```Python -{"request": request, "id": id} +{"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()`,例如,与挂载的 `StaticFiles` 一起使用。 +你还可以在模板内部将 `url_for()`用于静态文件,例如你挂载的 `name="static"`的 `StaticFiles`。 ```jinja hl_lines="4" {!../../../docs_src/templates/templates/item.html!} ``` -本例中,使用 `url_for()` 为模板添加 CSS 文件 `static/styles.css` 链接: +本例中,它将链接到 `static/styles.css`中的CSS文件: ```CSS hl_lines="4" {!../../../docs_src/templates/static/styles.css!} ``` -因为使用了 `StaticFiles`, **FastAPI** 应用自动提供位于 URL `/static/styles.css` - -的 CSS 文件。 +因为使用了 `StaticFiles`, **FastAPI** 应用会自动提供位于 URL `/static/styles.css`的 CSS 文件。 ## 更多说明 -包括测试模板等更多详情,请参阅 Starlette 官档 - 模板。 +包括测试模板等更多详情,请参阅 Starlette 官方文档 - 模板。 diff --git a/docs/zh/docs/deployment/manually.md b/docs/zh/docs/deployment/manually.md index 15588043f..ca7142613 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 服务器。 ## 服务器主机和服务器程序 @@ -44,7 +44,7 @@ === "Hypercorn" - * Hypercorn,一个也与 HTTP/2 兼容的 ASGI 服务器。 + * Hypercorn,一个也与 HTTP/2 兼容的 ASGI 服务器。
diff --git a/docs/zh/docs/fastapi-cli.md b/docs/zh/docs/fastapi-cli.md new file mode 100644 index 000000000..dd3914921 --- /dev/null +++ b/docs/zh/docs/fastapi-cli.md @@ -0,0 +1,84 @@ +# FastAPI CLI + +**FastAPI CLI** 是一个命令行程序,你可以用它来部署和运行你的 FastAPI 应用程序,管理你的 FastAPI 项目,等等。 + +当你安装 FastAPI 时(例如使用 `pip install FastAPI` 命令),会包含一个名为 `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 程序路径,自动检测包含 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 index 6cf35253c..d6a3e66c3 100644 --- a/docs/zh/docs/fastapi-people.md +++ b/docs/zh/docs/fastapi-people.md @@ -33,39 +33,98 @@ FastAPI 有一个非常棒的社区,它欢迎来自各个领域和背景的朋 这些人: -* [帮助他人解决 GitHub 的 issues](help-fastapi.md#github_1){.internal-link target=_blank}。 +* [帮助他人解决 GitHub 上的问题](help-fastapi.md#github_1){.internal-link target=_blank}。 * [创建 Pull Requests](help-fastapi.md#pr){.internal-link target=_blank}。 * 审核 Pull Requests, 对于 [翻译](contributing.md#_8){.internal-link target=_blank} 尤为重要。 向他们致以掌声。 👏 🙇 -## 上个月最活跃的用户 +## FastAPI 专家 -上个月这些用户致力于 [帮助他人解决 GitHub 的 issues](help-fastapi.md#github_1){.internal-link target=_blank}。 +这些用户一直以来致力于 [帮助他人解决 GitHub 上的问题](help-fastapi.md#github_1){.internal-link target=_blank}。 🙇 + +他们通过帮助许多人而被证明是 **FastAPI 专家**。 ✨ + +!!! 小提示 + 你也可以成为认可的 FastAPI 专家! + + 只需要 [帮助他人解决 GitHub 上的问题](help-fastapi.md#github_1){.internal-link target=_blank}。 🤓 + +你可以查看不同时期的 **FastAPI 专家**: + +* [上个月](#fastapi-experts-last-month) 🤓 +* [三个月](#fastapi-experts-3-months) 😎 +* [六个月](#fastapi-experts-6-months) 🧐 +* [一年](#fastapi-experts-1-year) 🧑‍🔬 +* [**全部时间**](#fastapi-experts-all-time) 🧙 + +## FastAPI 专家 - 上个月 + +这些是在过去一个月中 [在 GitHub 上帮助他人解答最多问题](help-fastapi.md#github_1){.internal-link target=_blank} 的用户。 🤓 {% if people %}
{% for user in people.last_month_experts[:10] %} -
@{{ user.login }}
Issues replied: {{ user.count }}
+
@{{ user.login }}
回答问题数: {{ user.count }}
+{% endfor %} + +
+{% endif %} + +### FastAPI 专家 - 三个月 + +这些是在过去三个月中 [在 GitHub 上帮助他人解答最多问题](help-fastapi.md#github_1){.internal-link target=_blank} 的用户。 😎 + +{% if people %} +
+{% for user in people.three_months_experts[:10] %} + +
@{{ user.login }}
回答问题数: {{ user.count }}
+{% endfor %} + +
+{% endif %} + +### FastAPI 专家 - 六个月 + +这些是在过去六个月中 [在 GitHub 上帮助他人解答最多问题](help-fastapi.md#github_1){.internal-link target=_blank} 的用户。 🧐 + +{% if people %} +
+{% for user in people.six_months_experts[:10] %} + +
@{{ user.login }}
回答问题数: {{ user.count }}
{% endfor %}
{% endif %} -## 专家组 +### FastAPI 专家 - 一年 + +这些是在过去一年中 [在 GitHub 上帮助他人解答最多问题](help-fastapi.md#github_1){.internal-link target=_blank} 的用户。 🧑‍🔬 + +{% if people %} +
+{% for user in people.one_year_experts[:20] %} + +
@{{ user.login }}
回答问题数: {{ user.count }}
+{% endfor %} + +
+{% endif %} -以下是 **FastAPI 专家**。 🤓 +## FastAPI 专家 - 全部时间 -这些用户一直以来致力于 [帮助他人解决 GitHub 的 issues](help-fastapi.md#github_1){.internal-link target=_blank}。 +以下是全部时间的 **FastAPI 专家**。 🤓🤯 -他们通过帮助许多人而被证明是专家。✨ +这些用户一直以来致力于 [帮助他人解决 GitHub 的 上的问题](help-fastapi.md#github_1){.internal-link target=_blank}。 🧙 {% if people %}
{% for user in people.experts[:50] %} -
@{{ user.login }}
Issues replied: {{ user.count }}
+
@{{ user.login }}
回答问题数: {{ user.count }}
{% endfor %}
@@ -89,25 +148,19 @@ FastAPI 有一个非常棒的社区,它欢迎来自各个领域和背景的朋
{% endif %} -还有很多其他贡献者(超过100个),你可以在 FastAPI GitHub 贡献者页面 中看到他们。👷 - -## 杰出审核者 - -以下用户是「杰出的评审者」。 🕵️ +还有很多别的贡献者(超过100个),你可以在 FastAPI GitHub 贡献者页面 中看到他们。👷 -### 翻译审核 +## 杰出翻译审核者 -我只会说少数几种语言(而且还不是很流利 😅)。所以,具备[能力去批准文档翻译](contributing.md#_8){.internal-link target=_blank} 是这些评审者们。如果没有它们,就不会有多语言文档。 - ---- +以下用户是 **杰出的评审者**。 🕵️ -**杰出的评审者** 🕵️ 评审了最多来自他人的 Pull Requests,他们保证了代码、文档尤其是 **翻译** 的质量。 +我只会说少数几种语言(而且还不是很流利 😅)。所以这些评审者们具备[能力去批准文档翻译](contributing.md#_8){.internal-link target=_blank}。如果没有他们,就不会有多语言文档。 {% if people %}
{% for user in people.top_translations_reviewers[:50] %} -
@{{ user.login }}
Reviews: {{ user.count }}
+
@{{ user.login }}
审核数: {{ user.count }}
{% endfor %}
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..c0d09f943 --- /dev/null +++ b/docs/zh/docs/how-to/configure-swagger-ui.md @@ -0,0 +1,78 @@ +# 配置 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 中的语法高亮: + +```Python hl_lines="3" +{!../../../docs_src/configure_swagger_ui/tutorial001.py!} +``` + +...在此之后,Swagger UI 将不会高亮代码: + + + +## 改变主题 + +同样地,你也可以通过设置键 `"syntaxHighlight.theme"` 来设置语法高亮主题(注意中间有一个点): + +```Python hl_lines="3" +{!../../../docs_src/configure_swagger_ui/tutorial002.py!} +``` + +这个配置会改变语法高亮主题: + + + +## 改变默认 Swagger UI 参数 + +FastAPI 包含了一些默认配置参数,适用于大多数用例。 + +其包括这些默认配置参数: + +```Python +{!../../../fastapi/openapi/docs.py[ln:7-23]!} +``` + +你可以通过在 `swagger_ui_parameters` 中设置不同的值来覆盖它们。 + +比如,如果要禁用 `deepLinking`,你可以像这样传递设置到 `swagger_ui_parameters` 中: + +```Python hl_lines="3" +{!../../../docs_src/configure_swagger_ui/tutorial003.py!} +``` + +## 其他 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/index.md b/docs/zh/docs/index.md index 2a67e8d08..f03a0dd13 100644 --- a/docs/zh/docs/index.md +++ b/docs/zh/docs/index.md @@ -36,7 +36,7 @@ hide: --- -FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框架,使用 Python 3.8+ 并基于标准的 Python 类型提示。 +FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框架,使用 Python 并基于标准的 Python 类型提示。 关键特性: @@ -119,7 +119,7 @@ FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框 ## 依赖 -Python 3.8 及更高版本 +Python 及更高版本 FastAPI 站在以下巨人的肩膀之上: @@ -138,7 +138,7 @@ $ pip install fastapi
-你还会需要一个 ASGI 服务器,生产环境可以使用 Uvicorn 或者 Hypercorn。 +你还会需要一个 ASGI 服务器,生产环境可以使用 Uvicorn 或者 Hypercorn
@@ -335,7 +335,7 @@ def update_item(item_id: int, item: Item): 你不需要去学习新的语法、了解特定库的方法或类,等等。 -只需要使用标准的 **Python 3.8 及更高版本**。 +只需要使用标准的 **Python 及更高版本**。 举个例子,比如声明 `int` 类型: diff --git a/docs/zh/docs/tutorial/security/oauth2-jwt.md b/docs/zh/docs/tutorial/security/oauth2-jwt.md index 33a4d7fc7..117f74d3e 100644 --- a/docs/zh/docs/tutorial/security/oauth2-jwt.md +++ b/docs/zh/docs/tutorial/security/oauth2-jwt.md @@ -26,29 +26,25 @@ 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。 - - 但后来换成了 Python-jose,因为 Python-jose 支持 PyJWT 的所有功能,还支持与其它工具集成时可能会用到的一些其它功能。 + 您可以在 PyJWT Installation docs 获得更多信息。 ## 密码哈希 @@ -62,7 +58,7 @@ $ pip install python-jose[cryptography] 原因很简单,假如数据库被盗,窃贼无法获取用户的明文密码,得到的只是哈希值。 -这样一来,窃贼就无法在其它应用中使用窃取的密码,要知道,很多用户在所有系统中都使用相同的密码,风险超大)。 +这样一来,窃贼就无法在其它应用中使用窃取的密码(要知道,很多用户在所有系统中都使用相同的密码,风险超大)。 ## 安装 `passlib` @@ -112,9 +108,41 @@ $ pip install passlib[bcrypt] 第三个函数用于身份验证,并返回用户。 -```Python hl_lines="7 48 55-56 59-60 69-75" -{!../../../docs_src/security/tutorial004.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="8 49 56-57 60-61 70-76" + {!> ../../../docs_src/security/tutorial004_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="8 49 56-57 60-61 70-76" + {!> ../../../docs_src/security/tutorial004_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="8 50 57-58 61-62 71-77" + {!> ../../../docs_src/security/tutorial004_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip + Prefer to use the `Annotated` version if possible. + + ```Python hl_lines="7 48 55-56 59-60 69-75" + {!> ../../../docs_src/security/tutorial004_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + Prefer to use the `Annotated` version if possible. + + ```Python hl_lines="8 49 56-57 60-61 70-76" + {!> ../../../docs_src/security/tutorial004.py!} + ``` !!! note "笔记" @@ -160,9 +188,41 @@ $ openssl rand -hex 32 如果令牌无效,则直接返回 HTTP 错误。 -```Python hl_lines="89-106" -{!../../../docs_src/security/tutorial004.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="4 7 13-15 29-31 79-87" + {!> ../../../docs_src/security/tutorial004_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="4 7 13-15 29-31 79-87" + {!> ../../../docs_src/security/tutorial004_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="4 7 14-16 30-32 80-88" + {!> ../../../docs_src/security/tutorial004_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip + Prefer to use the `Annotated` version if possible. + + ```Python hl_lines="3 6 12-14 28-30 78-86" + {!> ../../../docs_src/security/tutorial004_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + Prefer to use the `Annotated` version if possible. + + ```Python hl_lines="4 7 13-15 29-31 79-87" + {!> ../../../docs_src/security/tutorial004.py!} + ``` ## 更新 `/token` *路径操作* @@ -170,9 +230,41 @@ $ openssl rand -hex 32 创建并返回真正的 JWT 访问令牌。 -```Python hl_lines="115-130" -{!../../../docs_src/security/tutorial004.py!} -``` +=== "Python 3.10+" + + ```Python hl_lines="118-133" + {!> ../../../docs_src/security/tutorial004_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="118-133" + {!> ../../../docs_src/security/tutorial004_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="119-134" + {!> ../../../docs_src/security/tutorial004_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip + Prefer to use the `Annotated` version if possible. + + ```Python hl_lines="115-130" + {!> ../../../docs_src/security/tutorial004_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + Prefer to use the `Annotated` version if possible. + + ```Python hl_lines="116-131" + {!> ../../../docs_src/security/tutorial004.py!} + ``` ### JWT `sub` 的技术细节 @@ -261,7 +353,7 @@ OAuth2 支持**`scopes`**(作用域)。 开发者可以灵活选择最适合项目的安全机制。 -还可以直接使用 `passlib` 和 `python-jose` 等维护良好、使用广泛的包,这是因为 **FastAPI** 不需要任何复杂机制,就能集成外部的包。 +还可以直接使用 `passlib` 和 `PyJWT` 等维护良好、使用广泛的包,这是因为 **FastAPI** 不需要任何复杂机制,就能集成外部的包。 而且,**FastAPI** 还提供了一些工具,在不影响灵活、稳定和安全的前提下,尽可能地简化安全机制。 diff --git a/docs/zh/docs/tutorial/sql-databases.md b/docs/zh/docs/tutorial/sql-databases.md index be0c76593..8629b23fa 100644 --- a/docs/zh/docs/tutorial/sql-databases.md +++ b/docs/zh/docs/tutorial/sql-databases.md @@ -1,12 +1,19 @@ # SQL (关系型) 数据库 +!!! info + 这些文档即将被更新。🎉 + + 当前版本假设Pydantic v1和SQLAlchemy版本小于2。 + + 新的文档将包括Pydantic v2以及 SQLModel(也是基于SQLAlchemy),一旦SQLModel更新为为使用Pydantic v2。 + **FastAPI**不需要你使用SQL(关系型)数据库。 但是您可以使用任何您想要的关系型数据库。 在这里,让我们看一个使用着[SQLAlchemy](https://www.sqlalchemy.org/)的示例。 -您可以很容易地将SQLAlchemy支持任何数据库,像: +您可以很容易地将其调整为任何SQLAlchemy支持的数据库,如: * PostgreSQL * MySQL @@ -74,13 +81,13 @@ ORM 具有在代码和数据库表(“*关系型”)中的**对象**之间 └── schemas.py ``` -该文件`__init__.py`只是一个空文件,但它告诉 Python 其中`sql_app`的所有模块(Python 文件)都是一个包。 +该文件`__init__.py`只是一个空文件,但它告诉 Python `sql_app` 是一个包。 现在让我们看看每个文件/模块的作用。 ## 安装 SQLAlchemy -先下载`SQLAlchemy`所需要的依赖: +首先你需要安装`SQLAlchemy`:
@@ -152,17 +159,17 @@ connect_args={"check_same_thread": False} 这是为了防止意外地为不同的事物(不同的请求)共享相同的连接。 - 但是在 FastAPI 中,普遍使用def函数,多个线程可以为同一个请求与数据库交互,所以我们需要使用`connect_args={"check_same_thread": False}`来让SQLite允许这样。 + 但是在 FastAPI 中,使用普通函数(def)时,多个线程可以为同一个请求与数据库交互,所以我们需要使用`connect_args={"check_same_thread": False}`来让SQLite允许这样。 此外,我们将确保每个请求都在依赖项中获得自己的数据库连接会话,因此不需要该默认机制。 ### 创建一个`SessionLocal`类 -每个实例`SessionLocal`都会是一个数据库会话。当然该类本身还不是数据库会话。 +每个`SessionLocal`类的实例都会是一个数据库会话。当然该类本身还不是数据库会话。 但是一旦我们创建了一个`SessionLocal`类的实例,这个实例将是实际的数据库会话。 -我们命名它是`SessionLocal`为了将它与我们从 SQLAlchemy 导入的`Session`区别开来。 +我们将它命名为`SessionLocal`是为了将它与我们从 SQLAlchemy 导入的`Session`区别开来。 稍后我们将使用`Session`(从 SQLAlchemy 导入的那个)。 @@ -176,7 +183,7 @@ connect_args={"check_same_thread": False} 现在我们将使用`declarative_base()`返回一个类。 -稍后我们将用这个类继承,来创建每个数据库模型或类(ORM 模型): +稍后我们将继承这个类,来创建每个数据库模型或类(ORM 模型): ```Python hl_lines="13" {!../../../docs_src/sql_databases/sql_app/database.py!} @@ -209,7 +216,7 @@ connect_args={"check_same_thread": False} ### 创建模型属性/列 -现在创建所有模型(类)属性。 +现在创建所有模型(类)的属性。 这些属性中的每一个都代表其相应数据库表中的一列。 @@ -252,13 +259,13 @@ connect_args={"check_same_thread": False} ### 创建初始 Pydantic*模型*/模式 -创建一个`ItemBase`和`UserBase`Pydantic*模型*(或者我们说“schema”)以及在创建或读取数据时具有共同的属性。 +创建一个`ItemBase`和`UserBase`Pydantic*模型*(或者我们说“schema”),他们拥有创建或读取数据时具有的共同属性。 -`ItemCreate`为 创建一个`UserCreate`继承自它们的所有属性(因此它们将具有相同的属性),以及创建所需的任何其他数据(属性)。 +然后创建一个继承自他们的`ItemCreate`和`UserCreate`,并添加创建时所需的其他数据(或属性)。 因此在创建时也应当有一个`password`属性。 -但是为了安全起见,`password`不会出现在其他同类 Pydantic*模型*中,例如用户请求时不应该从 API 返回响应中包含它。 +但是为了安全起见,`password`不会出现在其他同类 Pydantic*模型*中,例如通过API读取一个用户数据时,它不应当包含在内。 === "Python 3.10+" @@ -368,7 +375,7 @@ Pydantic`orm_mode`将告诉 Pydantic*模型*读取数据,即它不是一个`di id = data["id"] ``` -尝试从属性中获取它,如: +它还会尝试从属性中获取它,如: ```Python id = data.id @@ -404,7 +411,7 @@ current_user.items 在这个文件中,我们将编写可重用的函数用来与数据库中的数据进行交互。 -**CRUD**分别为:**增加**、**查询**、**更改**和**删除**,即增删改查。 +**CRUD**分别为:增加(**C**reate)、查询(**R**ead)、更改(**U**pdate)、删除(**D**elete),即增删改查。 ...虽然在这个例子中我们只是新增和查询。 @@ -414,7 +421,7 @@ current_user.items 导入之前的`models`(SQLAlchemy 模型)和`schemas`(Pydantic*模型*/模式)。 -创建一些实用函数来完成: +创建一些工具函数来完成: * 通过 ID 和电子邮件查询单个用户。 * 查询多个用户。 @@ -429,14 +436,14 @@ current_user.items ### 创建数据 -现在创建实用程序函数来创建数据。 +现在创建工具函数来创建数据。 它的步骤是: * 使用您的数据创建一个 SQLAlchemy 模型*实例。* -* 使用`add`来将该实例对象添加到您的数据库。 -* 使用`commit`来对数据库的事务提交(以便保存它们)。 -* 使用`refresh`来刷新您的数据库实例(以便它包含来自数据库的任何新数据,例如生成的 ID)。 +* 使用`add`来将该实例对象添加到数据库会话。 +* 使用`commit`来将更改提交到数据库(以便保存它们)。 +* 使用`refresh`来刷新您的实例对象(以便它包含来自数据库的任何新数据,例如生成的 ID)。 ```Python hl_lines="18-24 31-36" {!../../../docs_src/sql_databases/sql_app/crud.py!} @@ -499,17 +506,17 @@ current_user.items “迁移”是每当您更改 SQLAlchemy 模型的结构、添加新属性等以在数据库中复制这些更改、添加新列、新表等时所需的一组步骤。 -您可以在[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/)。 +您可以在[Full Stack FastAPI Template](https://fastapi.tiangolo.com/zh/project-generation/)的模板中找到一个 FastAPI 项目中的 Alembic 示例。具体在[`alembic`代码目录中](https://github.com/tiangolo/full-stack-fastapi-template/tree/master/backend/app/alembic)。 ### 创建依赖项 现在使用我们在`sql_app/database.py`文件中创建的`SessionLocal`来创建依赖项。 -我们需要每个请求有一个独立的数据库会话/连接(`SessionLocal`),在所有请求中使用相同的会话,然后在请求完成后关闭它。 +我们需要每个请求有一个独立的数据库会话/连接(`SessionLocal`),在整个请求中使用相同的会话,然后在请求完成后关闭它。 然后将为下一个请求创建一个新会话。 -为此,我们将创建一个新的依赖项`yield`,正如前面关于[Dependencies with`yield`](https://fastapi.tiangolo.com/zh/tutorial/dependencies/dependencies-with-yield/)的部分中所解释的那样。 +为此,我们将创建一个包含`yield`的依赖项,正如前面关于[Dependencies with`yield`](https://fastapi.tiangolo.com/zh/tutorial/dependencies/dependencies-with-yield/)的部分中所解释的那样。 我们的依赖项将创建一个新的 SQLAlchemy `SessionLocal`,它将在单个请求中使用,然后在请求完成后关闭它。 @@ -729,13 +736,13 @@ $ uvicorn sql_app.main:app --reload ## 中间件替代数据库会话 -如果你不能使用依赖项`yield`——例如,如果你没有使用**Python 3.7**并且不能安装上面提到的**Python 3.6**的“backports” ——你可以在类似的“中间件”中设置会话方法。 +如果你不能使用带有`yield`的依赖项——例如,如果你没有使用**Python 3.7**并且不能安装上面提到的**Python 3.6**的“backports” ——你可以使用类似的方法在“中间件”中设置会话。 -“中间件”基本功能是一个为每个请求执行的函数在请求之前进行执行相应的代码,以及在请求执行之后执行相应的代码。 +“中间件”基本上是一个对每个请求都执行的函数,其中一些代码在端点函数之前执行,另一些代码在端点函数之后执行。 ### 创建中间件 -我们将添加中间件(只是一个函数)将为每个请求创建一个新的 SQLAlchemy`SessionLocal`,将其添加到请求中,然后在请求完成后关闭它。 +我们要添加的中间件(只是一个函数)将为每个请求创建一个新的 SQLAlchemy`SessionLocal`,将其添加到请求中,然后在请求完成后关闭它。 === "Python 3.9+" @@ -760,7 +767,7 @@ $ uvicorn sql_app.main:app --reload `request.state`是每个`Request`对象的属性。它用于存储附加到请求本身的任意对象,例如本例中的数据库会话。您可以在[Starlette 的关于`Request`state](https://www.starlette.io/requests/#other-state)的文档中了解更多信息。 -对于这种情况下,它帮助我们确保在所有请求中使用单个数据库会话,然后关闭(在中间件中)。 +对于这种情况下,它帮助我们确保在整个请求中使用单个数据库会话,然后关闭(在中间件中)。 ### 使用`yield`依赖项与使用中间件的区别 @@ -776,9 +783,9 @@ $ uvicorn sql_app.main:app --reload * 即使处理该请求的*路径操作*不需要数据库。 !!! tip - `tyield`当依赖项 足以满足用例时,使用`tyield`依赖项方法会更好。 + 最好使用带有yield的依赖项,如果这足够满足用例需求 !!! info - `yield`的依赖项是最近刚加入**FastAPI**中的。 + 带有`yield`的依赖项是最近刚加入**FastAPI**中的。 所以本教程的先前版本只有带有中间件的示例,并且可能有多个应用程序使用中间件进行数据库会话管理。 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/security/tutorial004.py b/docs_src/security/tutorial004.py index d0fbaa572..91d161b8a 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 @@ -98,7 +99,7 @@ async def get_current_user(token: str = Depends(oauth2_scheme)): 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: diff --git a/docs_src/security/tutorial004_an.py b/docs_src/security/tutorial004_an.py index eebd36d64..df50754af 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 @@ -99,7 +100,7 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): 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: diff --git a/docs_src/security/tutorial004_an_py310.py b/docs_src/security/tutorial004_an_py310.py index 4e50ada7c..eff54ef01 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 @@ -98,7 +99,7 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): 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: diff --git a/docs_src/security/tutorial004_an_py39.py b/docs_src/security/tutorial004_an_py39.py index eb49aaa67..0455b500c 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 @@ -98,7 +99,7 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): 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: diff --git a/docs_src/security/tutorial004_py310.py b/docs_src/security/tutorial004_py310.py index 5a905783d..78bee22a3 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 @@ -97,7 +98,7 @@ async def get_current_user(token: str = Depends(oauth2_scheme)): 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: diff --git a/docs_src/security/tutorial005.py b/docs_src/security/tutorial005.py index d4a6975da..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: diff --git a/docs_src/security/tutorial005_an.py b/docs_src/security/tutorial005_an.py index 982daed2f..5b67cb145 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 @@ -121,7 +122,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: diff --git a/docs_src/security/tutorial005_an_py310.py b/docs_src/security/tutorial005_an_py310.py index 79aafbff1..297193e35 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 @@ -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: diff --git a/docs_src/security/tutorial005_an_py39.py b/docs_src/security/tutorial005_an_py39.py index 3bdab5507..1acf47bdc 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 +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: diff --git a/docs_src/security/tutorial005_py310.py b/docs_src/security/tutorial005_py310.py index 9f75aa0be..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: diff --git a/docs_src/security/tutorial005_py39.py b/docs_src/security/tutorial005_py39.py index bac248932..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: diff --git a/fastapi/__init__.py b/fastapi/__init__.py index f28657712..4d60bc7de 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.110.2" +__version__ = "0.111.1" from starlette import status as status diff --git a/fastapi/applications.py b/fastapi/applications.py index 4446cacfb..4f5e6f1d9 100644 --- a/fastapi/applications.py +++ b/fastapi/applications.py @@ -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. diff --git a/fastapi/openapi/docs.py b/fastapi/openapi/docs.py index 67815e0fb..c2ec358d2 100644 --- a/fastapi/openapi/docs.py +++ b/fastapi/openapi/docs.py @@ -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/security/api_key.py b/fastapi/security/api_key.py index b74a017f1..d68bdb037 100644 --- a/fastapi/security/api_key.py +++ b/fastapi/security/api_key.py @@ -76,7 +76,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 diff --git a/pdm_build.py b/pdm_build.py new file mode 100644 index 000000000..45922d471 --- /dev/null +++ b/pdm_build.py @@ -0,0 +1,39 @@ +import os +from typing import Any, Dict, List + +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"][TIANGOLO_BUILD_PACKAGE] + project_config: Dict[str, Any] = config["project"] + # Get main optional dependencies, extras + optional_dependencies: Dict[str, List[str]] = metadata.get( + "optional-dependencies", {} + ) + # Get custom optional dependencies name to always include in this (non-slim) package + include_optional_dependencies: List[str] = config.get( + "include-optional-dependencies", [] + ) + # Override main [project] configs with custom configs for this package + for key, value in project_config.items(): + metadata[key] = value + # Get custom build config for the current package + build_config: Dict[str, Any] = ( + config.get("tool", {}).get("pdm", {}).get("build", {}) + ) + # Override PDM build config with custom build config for this package + for key, value in build_config.items(): + context.config.build_config[key] = value + # Get main dependencies + dependencies: List[str] = metadata.get("dependencies", []) + # Add optional dependencies to the default dependencies for this (non-slim) package + for include_optional in include_optional_dependencies: + optional_dependencies_group = optional_dependencies.get(include_optional, []) + dependencies.extend(optional_dependencies_group) diff --git a/pyproject.toml b/pyproject.toml index 6c3bebf2b..dbaa42149 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" }, ] @@ -45,7 +45,6 @@ dependencies = [ "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" @@ -53,22 +52,97 @@ Documentation = "https://fastapi.tiangolo.com/" Repository = "https://github.com/tiangolo/fastapi" [project.optional-dependencies] + +standard = [ + "fastapi-cli >=0.0.2", + # For the test client + "httpx >=0.23.0", + # For templates + "jinja2 >=2.11.2", + # For forms and file uploads + "python-multipart >=0.0.7", + # 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 >=0.0.2", + # # For the test client "httpx >=0.23.0", + # For templates "jinja2 >=2.11.2", + # For forms and file uploads "python-multipart >=0.0.7", + # 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", + # 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" +[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.tiangolo._internal-slim-build.packages.fastapi] +include-optional-dependencies = ["standard"] + +[tool.tiangolo._internal-slim-build.packages.fastapi.project.optional-dependencies] +all = [ + # # For the test client + "httpx >=0.23.0", + # For templates + "jinja2 >=2.11.2", + # For forms and file uploads + "python-multipart >=0.0.7", + # 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", + # 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.mypy] strict = true diff --git a/requirements-docs.txt b/requirements-docs.txt index 599e01f16..c672f0ef7 100644 --- a/requirements-docs.txt +++ b/requirements-docs.txt @@ -11,7 +11,7 @@ jieba==0.42.1 pillow==10.3.0 # For image processing by Material for MkDocs cairosvg==2.7.0 -mkdocstrings[python]==0.23.0 +mkdocstrings[python]==0.24.3 griffe-typingdoc==0.2.2 # For griffe, it formats with black black==24.3.0 diff --git a/requirements-tests.txt b/requirements-tests.txt index 30762bc64..bfe70f2f5 100644 --- a/requirements-tests.txt +++ b/requirements-tests.txt @@ -1,22 +1,17 @@ --e . +-e .[all] -r requirements-docs-tests.txt -pydantic-settings >=2.0.0 pytest >=7.1.3,<8.0.0 coverage[toml] >= 6.5.0,< 8.0 mypy ==1.8.0 ruff ==0.2.0 -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.7,<0.1.0 flask >=1.1.2,<3.0.0 anyio[trio] >=3.2.1,<4.0.0 -python-jose[cryptography] >=3.3.0,<4.0.0 +PyJWT==2.8.0 pyyaml >=5.3.1,<7.0.0 passlib[bcrypt] >=1.7.2,<2.0.0 diff --git a/requirements.txt b/requirements.txt index ef25ec483..8e1fef341 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 # For generating screenshots playwright diff --git a/scripts/build-docs.sh b/scripts/build-docs.sh deleted file mode 100755 index 7aa0a9a47..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-docs -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/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/format.sh b/scripts/format.sh index 11f25f1ce..45742f79a 100755 --- a/scripts/format.sh +++ b/scripts/format.sh @@ -1,5 +1,5 @@ #!/bin/sh -e 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/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..24ffecf46 100644 --- a/scripts/mkdocs_hooks.py +++ b/scripts/mkdocs_hooks.py @@ -39,7 +39,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 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/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/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):