diff --git a/.github/actions/comment-docs-preview-in-pr/Dockerfile b/.github/actions/comment-docs-preview-in-pr/Dockerfile index 14b0d026956fb..42627fe190ebf 100644 --- a/.github/actions/comment-docs-preview-in-pr/Dockerfile +++ b/.github/actions/comment-docs-preview-in-pr/Dockerfile @@ -1,6 +1,8 @@ -FROM python:3.9 +FROM python:3.10 -RUN pip install httpx "pydantic==1.5.1" pygithub +COPY ./requirements.txt /app/requirements.txt + +RUN pip install -r /app/requirements.txt COPY ./app /app diff --git a/.github/actions/comment-docs-preview-in-pr/app/main.py b/.github/actions/comment-docs-preview-in-pr/app/main.py index 68914fdb9a818..8cc119fe0af8c 100644 --- a/.github/actions/comment-docs-preview-in-pr/app/main.py +++ b/.github/actions/comment-docs-preview-in-pr/app/main.py @@ -6,7 +6,8 @@ import httpx from github import Github from github.PullRequest import PullRequest -from pydantic import BaseModel, BaseSettings, SecretStr, ValidationError +from pydantic import BaseModel, SecretStr, ValidationError +from pydantic_settings import BaseSettings github_api = "https://api.github.com" diff --git a/.github/actions/comment-docs-preview-in-pr/requirements.txt b/.github/actions/comment-docs-preview-in-pr/requirements.txt new file mode 100644 index 0000000000000..74a3631f48fa3 --- /dev/null +++ b/.github/actions/comment-docs-preview-in-pr/requirements.txt @@ -0,0 +1,4 @@ +PyGithub +pydantic>=2.5.3,<3.0.0 +pydantic-settings>=2.1.0,<3.0.0 +httpx diff --git a/.github/dependabot.yml b/.github/dependabot.yml index cd972a0ba4722..0a59adbd6b474 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -11,6 +11,10 @@ updates: - package-ecosystem: "pip" directory: "/" schedule: - interval: "daily" + interval: "monthly" + groups: + python-packages: + patterns: + - "*" commit-message: prefix: ⬆ diff --git a/.github/workflows/build-docs.yml b/.github/workflows/build-docs.yml index 51c069d9ebebb..abf2b90f688b2 100644 --- a/.github/workflows/build-docs.yml +++ b/.github/workflows/build-docs.yml @@ -39,7 +39,7 @@ jobs: steps: - uses: actions/checkout@v4 - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: python-version: "3.11" - uses: actions/cache@v3 @@ -80,7 +80,7 @@ jobs: run: echo "$GITHUB_CONTEXT" - uses: actions/checkout@v4 - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: python-version: "3.11" - uses: actions/cache@v3 diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index 155ebd0a8e86f..2bec6682c1513 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -21,7 +21,7 @@ jobs: mkdir ./site - name: Download Artifact Docs id: download - uses: dawidd6/action-download-artifact@v2.28.0 + uses: dawidd6/action-download-artifact@v3.0.0 with: if_no_artifact_found: ignore github_token: ${{ secrets.FASTAPI_PREVIEW_DOCS_DOWNLOAD_ARTIFACTS }} diff --git a/.github/workflows/issue-manager.yml b/.github/workflows/issue-manager.yml index bb967fa118362..d1aad28fd3160 100644 --- a/.github/workflows/issue-manager.yml +++ b/.github/workflows/issue-manager.yml @@ -31,5 +31,9 @@ jobs: "answered": { "delay": 864000, "message": "Assuming the original need was handled, this will be automatically closed now. But feel free to add more comments or create new issues or PRs." + }, + "changes-requested": { + "delay": 2628000, + "message": "As this PR had requested changes to be applied but has been inactive for a while, it's now going to be closed. But if there's anyone interested, feel free to create a new PR." } } diff --git a/.github/workflows/label-approved.yml b/.github/workflows/label-approved.yml index 2113c468ac835..62daf260805f2 100644 --- a/.github/workflows/label-approved.yml +++ b/.github/workflows/label-approved.yml @@ -3,6 +3,7 @@ name: Label Approved on: schedule: - cron: "0 12 * * *" + workflow_dispatch: jobs: label-approved: @@ -13,6 +14,6 @@ jobs: env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - - uses: docker://tiangolo/label-approved:0.0.2 + - uses: docker://tiangolo/label-approved:0.0.4 with: token: ${{ secrets.FASTAPI_LABEL_APPROVED }} diff --git a/.github/workflows/latest-changes.yml b/.github/workflows/latest-changes.yml index b9b550d5ea807..27e062d090546 100644 --- a/.github/workflows/latest-changes.yml +++ b/.github/workflows/latest-changes.yml @@ -34,7 +34,7 @@ jobs: if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }} with: limit-access-to-actor: true - - uses: docker://tiangolo/latest-changes:0.2.0 + - uses: docker://tiangolo/latest-changes:0.3.0 # - uses: tiangolo/latest-changes@main with: token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 8cbd01b92b098..8ebb28a80fbcf 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -15,7 +15,7 @@ jobs: run: echo "$GITHUB_CONTEXT" - uses: actions/checkout@v4 - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: python-version: "3.10" # Issue ref: https://github.com/actions/setup-python/issues/436 @@ -32,7 +32,7 @@ jobs: - name: Build distribution run: python -m build - name: Publish - uses: pypa/gh-action-pypi-publish@v1.8.10 + uses: pypa/gh-action-pypi-publish@v1.8.11 with: password: ${{ secrets.PYPI_API_TOKEN }} - name: Dump GitHub context diff --git a/.github/workflows/smokeshow.yml b/.github/workflows/smokeshow.yml index 38b44c41300f1..10bff67aeeb62 100644 --- a/.github/workflows/smokeshow.yml +++ b/.github/workflows/smokeshow.yml @@ -18,13 +18,13 @@ jobs: env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - - uses: actions/setup-python@v4 + - uses: actions/setup-python@v5 with: python-version: '3.9' - run: pip install smokeshow - - uses: dawidd6/action-download-artifact@v2.28.0 + - uses: dawidd6/action-download-artifact@v3.0.0 with: github_token: ${{ secrets.FASTAPI_SMOKESHOW_DOWNLOAD_ARTIFACTS }} workflow: test.yml diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 7ebb80efdfc99..b6b1736851e1f 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -19,7 +19,7 @@ jobs: run: echo "$GITHUB_CONTEXT" - uses: actions/checkout@v4 - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: python-version: "3.11" # Issue ref: https://github.com/actions/setup-python/issues/436 @@ -42,7 +42,12 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - python-version: ["3.8", "3.9", "3.10", "3.11"] + python-version: + - "3.12" + - "3.11" + - "3.10" + - "3.9" + - "3.8" pydantic-version: ["pydantic-v1", "pydantic-v2"] fail-fast: false steps: @@ -52,7 +57,7 @@ jobs: run: echo "$GITHUB_CONTEXT" - uses: actions/checkout@v4 - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} # Issue ref: https://github.com/actions/setup-python/issues/436 @@ -93,7 +98,7 @@ jobs: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - uses: actions/checkout@v4 - - uses: actions/setup-python@v4 + - uses: actions/setup-python@v5 with: python-version: '3.8' # Issue ref: https://github.com/actions/setup-python/issues/436 diff --git a/docs/bn/docs/index.md b/docs/bn/docs/index.md new file mode 100644 index 0000000000000..4f778e87352f9 --- /dev/null +++ b/docs/bn/docs/index.md @@ -0,0 +1,464 @@ +

+ FastAPI +

+

+ FastAPI উচ্চক্ষমতা সম্পন্ন, সহজে শেখার এবং দ্রুত কোড করে প্রোডাকশনের জন্য ফ্রামওয়ার্ক। +

+

+ + Test + + + Coverage + + + Package version + +

+ +--- + +**নির্দেশিকা নথি**: https://fastapi.tiangolo.com + +**সোর্স কোড**: https://github.com/tiangolo/fastapi + +--- + +FastAPI একটি আধুনিক, দ্রুত ( বেশি ক্ষমতা ) সম্পন্ন, Python 3.6+ দিয়ে API তৈরির জন্য স্ট্যান্ডার্ড পাইথন টাইপ ইঙ্গিত ভিত্তিক ওয়েব ফ্রেমওয়ার্ক। + +এর মূল বৈশিষ্ট্য গুলো হলঃ + +- **গতি**: এটি **NodeJS** এবং **Go** এর মত কার্যক্ষমতা সম্পন্ন (Starlette এবং Pydantic এর সাহায্যে)। [পাইথন এর দ্রুততম ফ্রেমওয়ার্ক গুলোর মধ্যে এটি একটি](#_11)। +- **দ্রুত কোড করা**:বৈশিষ্ট্য তৈরির গতি ২০০% থেকে ৩০০% বৃদ্ধি করে৷ \* +- **স্বল্প bugs**: মানুব (ডেভেলপার) সৃষ্ট ত্রুটির প্রায় ৪০% হ্রাস করে। \* +- **স্বজ্ঞাত**: দুর্দান্ত এডিটর সাহায্য Completion নামেও পরিচিত। দ্রুত ডিবাগ করা যায়। + +- **সহজ**: এটি এমন ভাবে সজানো হয়েছে যেন নির্দেশিকা নথি পড়ে সহজে শেখা এবং ব্যবহার করা যায়। +- **সংক্ষিপ্ত**: কোড পুনরাবৃত্তি কমানোর পাশাপাশি, bug কমায় এবং প্রতিটি প্যারামিটার ঘোষণা থেকে একাধিক ফিচার পাওয়া যায় । +- **জোরালো**: স্বয়ংক্রিয় ভাবে তৈরি ক্রিয়াশীল নির্দেশনা নথি (documentation) সহ উৎপাদন উপযোগি (Production-ready) কোড পাওয়া যায়। +- **মান-ভিত্তিক**: এর ভিত্তি OpenAPI (যা পুর্বে Swagger নামে পরিচিত ছিল) এবং JSON Schema এর আদর্শের মানের ওপর + +\* উৎপাদনমুখি এপ্লিকেশন বানানোর এক দল ডেভেলপার এর মতামত ভিত্তিক ফলাফল। + +## স্পনসর গণ + + + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} + +{% endfor -%} +{%- for sponsor in sponsors.silver -%} + +{% endfor %} +{% endif %} + + + +অন্যান্য স্পনসর গণ + +## মতামত সমূহ + +"_আমি আজকাল **FastAPI** ব্যবহার করছি। [...] আমরা ভাবছি মাইক্রোসফ্টে **ML সার্ভিস** এ সকল দলের জন্য এটি ব্যবহার করব। যার মধ্যে কিছু পণ্য **Windows** এ সংযোযন হয় এবং কিছু **Office** এর সাথে সংযোযন হচ্ছে।_" + +
কবির খান - মাইক্রোসফ্টে (ref)
+ +--- + +"_আমরা **FastAPI** লাইব্রেরি গ্রহণ করেছি একটি **REST** সার্ভার তৈরি করতে, যা **ভবিষ্যদ্বাণী** পাওয়ার জন্য কুয়েরি করা যেতে পারে। [লুডউইগের জন্য]_" + +
পিয়েরো মোলিনো, ইয়ারোস্লাভ দুদিন, এবং সাই সুমন্থ মিরিয়ালা - উবার (ref)
+ +--- + +"_**Netflix** আমাদের **ক্রাইসিস ম্যানেজমেন্ট** অর্কেস্ট্রেশন ফ্রেমওয়ার্ক: **ডিসপ্যাচ** এর ওপেন সোর্স রিলিজ ঘোষণা করতে পেরে আনন্দিত! [যাকিনা **FastAPI** দিয়ে নির্মিত]_" + +
কেভিন গ্লিসন, মার্ক ভিলানোভা, ফরেস্ট মনসেন - নেটফ্লিক্স (ref)
+ +--- + +"_আমি **FastAPI** নিয়ে চাঁদের সমান উৎসাহিত। এটি খুবই মজার!_" + +
ব্রায়ান ওকেন - পাইথন বাইটস পডকাস্ট হোস্ট (ref)
+ +--- + +"\_সত্যিই, আপনি যা তৈরি করেছেন তা খুব মজবুত এবং পরিপূর্ন৷ অনেক উপায়ে, আমি যা **Hug** এ করতে চেয়েছিলাম - তা কাউকে তৈরি করতে দেখে আমি সত্যিই অনুপ্রানিত৷\_" + +
টিমোথি ক্রসলে - Hug স্রষ্টা (ref)
+ +--- + +"আপনি যদি REST API তৈরির জন্য একটি **আধুনিক ফ্রেমওয়ার্ক** শিখতে চান, তাহলে **FastAPI** দেখুন [...] এটি দ্রুত, ব্যবহার করা সহজ এবং শিখতেও সহজ [...]\_" + +"_আমরা আমাদের **APIs** [...] এর জন্য **FastAPI**- তে এসেছি [...] আমি মনে করি আপনিও এটি পছন্দ করবেন [...]_" + +
ইনেস মন্টানি - ম্যাথিউ হোনিবাল - Explosion AI প্রতিষ্ঠাতা - spaCy স্রষ্টা (ref) - (ref)
+ +--- + +## **Typer**, CLI এর জন্য FastAPI + + + +আপনি যদি CLI অ্যাপ বানাতে চান, যা কিনা ওয়েব API এর পরিবর্তে টার্মিনালে ব্যবহার হবে, তাহলে দেখুন**Typer**. + +**টাইপার** হল FastAPI এর ছোট ভাইয়ের মত। এবং এটির উদ্দেশ্য ছিল **CLIs এর FastAPI** হওয়া। ⌨️ 🚀 + +## প্রয়োজনীয়তা গুলো + +Python 3.7+ + +FastAPI কিছু দানবেদের কাঁধে দাঁড়িয়ে আছে: + +- Starlette ওয়েব অংশের জন্য. +- Pydantic ডেটা অংশগুলির জন্য. + +## ইনস্টলেশন প্রক্রিয়া + +
+ +```console +$ pip install fastapi + +---> 100% +``` + +
+ +আপনার একটি ASGI সার্ভারেরও প্রয়োজন হবে, প্রোডাকশনের জন্য Uvicorn অথবা Hypercorn. + +
+ +```console +$ pip install "uvicorn[standard]" + +---> 100% +``` + +
+ +## উদাহরণ + +### তৈরি + +- `main.py` নামে একটি ফাইল তৈরি করুন: + +```Python +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +
+অথবা ব্যবহার করুন async def... + +যদি আপনার কোড `async` / `await`, ব্যবহার করে তাহলে `async def` ব্যবহার করুন: + +```Python hl_lines="9 14" +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +async def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +async def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +**টীকা**: + +আপনি যদি না জানেন, _"তাড়াহুড়ো?"_ বিভাগটি দেখুন `async` এবং `await` নথির মধ্যে দেখুন . + +
+ +### এটি চালান + +সার্ভার চালু করুন: + +
+ +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [28720] +INFO: Started server process [28722] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +
+নির্দেশনা সম্পর্কে uvicorn main:app --reload... + +`uvicorn main:app` নির্দেশনাটি দ্বারা বোঝায়: + +- `main`: ফাইল `main.py` (পাইথন "মডিউল")। +- `app`: `app = FastAPI()` লাইন দিয়ে `main.py` এর ভিতরে তৈরি করা অবজেক্ট। +- `--reload`: কোড পরিবর্তনের পরে সার্ভার পুনরায় চালু করুন। এটি শুধুমাত্র ডেভেলপমেন্ট এর সময় ব্যবহার করুন। + +
+ +### এটা চেক করুন + +আপনার ব্রাউজার খুলুন http://127.0.0.1:8000/items/5?q=somequery এ। + +আপনি JSON রেসপন্স দেখতে পাবেন: + +```JSON +{"item_id": 5, "q": "somequery"} +``` + +আপনি ইতিমধ্যে একটি API তৈরি করেছেন যা: + +- `/` এবং `/items/{item_id}` _paths_ এ HTTP অনুরোধ গ্রহণ করে। +- উভয় *path*ই `GET` অপারেশন নেয় ( যা HTTP _methods_ নামেও পরিচিত)। +- _path_ `/items/{item_id}`-এ একটি _path প্যারামিটার_ `item_id` আছে যা কিনা `int` হতে হবে। +- _path_ `/items/{item_id}`-এর একটি ঐচ্ছিক `str` _query প্যারামিটার_ `q` আছে। + +### ক্রিয়াশীল API নির্দেশিকা নথি + +এখন যান http://127.0.0.1:8000/docs. + +আপনি স্বয়ংক্রিয় ভাবে প্রস্তুত ক্রিয়াশীল API নির্দেশিকা নথি দেখতে পাবেন (Swagger UI প্রদত্ত): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### বিকল্প API নির্দেশিকা নথি + +এবং এখন http://127.0.0.1:8000/redoc এ যান. + +আপনি স্বয়ংক্রিয় ভাবে প্রস্তুত বিকল্প নির্দেশিকা নথি দেখতে পাবেন (ReDoc প্রদত্ত): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +## উদাহরণস্বরূপ আপগ্রেড + +এখন `main.py` ফাইলটি পরিবর্তন করুন যেন এটি `PUT` রিকুয়েস্ট থেকে বডি পেতে পারে। + +Python স্ট্যান্ডার্ড লাইব্রেরি, Pydantic এর সাহায্যে বডি ঘোষণা করুন। + +```Python hl_lines="4 9-12 25-27" +from typing import Union + +from fastapi import FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Item(BaseModel): + name: str + price: float + is_offer: Union[bool, None] = None + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} + + +@app.put("/items/{item_id}") +def update_item(item_id: int, item: Item): + return {"item_name": item.name, "item_id": item_id} +``` + +সার্ভারটি স্বয়ংক্রিয়ভাবে পুনরায় লোড হওয়া উচিত (কারণ আপনি উপরের `uvicorn` কমান্ডে `--reload` যোগ করেছেন)। + +### ক্রিয়াশীল API নির্দেশিকা নথি উন্নীতকরণ + +এখন http://127.0.0.1:8000/docs এডড্রেসে যান. + +- ক্রিয়াশীল API নির্দেশিকা নথিটি স্বয়ংক্রিয়ভাবে উন্নীত হযে যাবে, নতুন বডি সহ: + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +- "Try it out" বাটনে চাপুন, এটি আপনাকে পেরামিটারগুলো পূরণ করতে এবং API এর সাথে সরাসরি ক্রিয়া-কলাপ করতে দিবে: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) + +- তারপরে "Execute" বাটনে চাপুন, ব্যবহারকারীর ইন্টারফেস আপনার API এর সাথে যোগাযোগ করবে, পেরামিটার পাঠাবে, ফলাফলগুলি পাবে এবং সেগুলি পর্রদায় দেখাবে: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) + +### বিকল্প API নির্দেশিকা নথি আপগ্রেড + +এবং এখন http://127.0.0.1:8000/redoc এ যান। + +- বিকল্প নির্দেশিকা নথিতেও নতুন কুয়েরি প্যারামিটার এবং বডি প্রতিফলিত হবে: + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### সংক্ষিপ্তকরণ + +সংক্ষেপে, আপনি **শুধু একবার** প্যারামিটারের ধরন, বডি ইত্যাদি ফাংশন প্যারামিটার হিসেবে ঘোষণা করেন। + +আপনি সেটি আধুনিক পাইথনের সাথে করেন। + +আপনাকে নতুন করে নির্দিষ্ট কোন লাইব্রেরির বাক্য গঠন, ফাংশন বা ক্লাস কিছুই শিখতে হচ্ছে না। + +শুধুই আধুনিক **Python 3.6+** + +উদাহরণস্বরূপ, `int` এর জন্য: + +```Python +item_id: int +``` + +অথবা আরও জটিল `Item` মডেলের জন্য: + +```Python +item: Item +``` + +...এবং সেই একই ঘোষণার সাথে আপনি পাবেন: + +- এডিটর সাহায্য, যেমন + - সমাপ্তি। + - ধরণ যাচাই +- তথ্য যাচাইকরণ: + - ডেটা অবৈধ হলে স্বয়ংক্রিয় এবং পরিষ্কার ত্রুটির নির্দেশনা। + - এমনকি গভীরভাবে নেস্ট করা JSON অবজেক্টের জন্য বৈধতা। +- প্রেরিত তথ্য রূপান্তর: যা নেটওয়ার্ক থেকে পাইথনের তথ্য এবং ধরনে আসে, এবং সেখান থেকে পড়া: + + - JSON। + - পাথ প্যারামিটার। + - কুয়েরি প্যারামিটার। + - কুকিজ + - হেডার + - ফর্ম + - ফাইল + +- আউটপুট ডেটার রূপান্তর: পাইথন ডেটা এবং টাইপ থেকে নেটওয়ার্ক ডেটাতে রূপান্তর করা (JSON হিসাবে): + -পাইথন টাইপে রূপান্তর করুন (`str`, `int`, `float`, `bool`, `list`, ইত্যাদি)। + - `datetime` অবজেক্ট। + - `UUID` objeঅবজেক্টcts। + - ডাটাবেস মডেল। + - ...এবং আরো অনেক। +- স্বয়ংক্রিয় ক্রিয়াশীল API নির্দেশিকা নথি, 2টি বিকল্প ব্যবহারকারীর ইন্টারফেস সহ: + - সোয়াগার ইউ আই (Swagger UI)। + - রিডক (ReDoc)। + +--- + +পূর্ববর্তী কোড উদাহরণে ফিরে আসা যাক, **FastAPI** যা করবে: + +- `GET` এবং `PUT` অনুরোধের জন্য পথে `item_id` আছে কিনা তা যাচাই করবে। +- `GET` এবং `PUT` অনুরোধের জন্য `item_id` টাইপ `int` এর হতে হবে তা যাচাই করবে। + - যদি না হয় তবে ক্লায়েন্ট একটি উপযুক্ত, পরিষ্কার ত্রুটি দেখতে পাবেন। +- `GET` অনুরোধের জন্য একটি ঐচ্ছিক ক্যুয়েরি প্যারামিটার নামক `q` (যেমন `http://127.0.0.1:8000/items/foo?q=somequery`) আছে কি তা চেক করবে। + - যেহেতু `q` প্যারামিটারটি `= None` দিয়ে ঘোষণা করা হয়েছে, তাই এটি ঐচ্ছিক। + - `None` ছাড়া এটি প্রয়োজনীয় হতো (যেমন `PUT` এর ক্ষেত্রে হয়েছে)। +- `/items/{item_id}` এর জন্য `PUT` অনুরোধের বডি JSON হিসাবে পড়ুন: + - লক্ষ করুন, `name` একটি প্রয়োজনীয় অ্যাট্রিবিউট হিসাবে বিবেচনা করেছে এবং এটি `str` হতে হবে। + - লক্ষ করুন এখানে, `price` অ্যাট্রিবিউটটি আবশ্যক এবং এটি `float` হতে হবে। + - লক্ষ করুন `is_offer` একটি ঐচ্ছিক অ্যাট্রিবিউট এবং এটি `bool` হতে হবে যদি উপস্থিত থাকে। + - এই সবটি গভীরভাবে অবস্থানরত JSON অবজেক্টগুলিতেও কাজ করবে। +- স্বয়ংক্রিয়ভাবে JSON হতে এবং JSON থেকে কনভার্ট করুন। +- OpenAPI দিয়ে সবকিছু ডকুমেন্ট করুন, যা ব্যবহার করা যেতে পারে: + - ক্রিয়াশীল নির্দেশিকা নথি। + - অনেক ভাষার জন্য স্বয়ংক্রিয় ক্লায়েন্ট কোড তৈরির ব্যবস্থা। +- সরাসরি 2টি ক্রিয়াশীল নির্দেশিকা নথি ওয়েব পৃষ্ঠ প্রদান করা হয়েছে। + +--- + +আমরা এতক্ষন শুধু এর পৃষ্ঠ তৈরি করেছি, কিন্তু আপনি ইতমধ্যেই এটি কিভাবে কাজ করে তার ধারণাও পেয়ে গিয়েছেন। + +নিম্নোক্ত লাইন গুলো পরিবর্তন করার চেষ্টা করুন: + +```Python + return {"item_name": item.name, "item_id": item_id} +``` + +...পুর্বে: + +```Python + ... "item_name": item.name ... +``` + +...পরবর্তীতে: + +```Python + ... "item_price": item.price ... +``` + +...এবং দেখুন কিভাবে আপনার এডিটর উপাদানগুলোকে সয়ংক্রিয়ভাবে-সম্পন্ন করবে এবং তাদের ধরন জানতে পারবে: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +আরও বৈশিষ্ট্য সম্পন্ন উদাহরণের জন্য, দেখুন টিউটোরিয়াল - ব্যবহারকারীর গাইড. + +**স্পয়লার সতর্কতা**: টিউটোরিয়াল - ব্যবহারকারীর গাইড নিম্নোক্ত বিষয়গুলি অন্তর্ভুক্ত করে: + +- **হেডার**, **কুকিজ**, **ফর্ম ফিল্ড** এবং **ফাইলগুলি** এমন অন্যান্য জায়গা থেকে প্যারামিটার ঘোষণা করা। +- `maximum_length` বা `regex` এর মতো **যাচাইকরণ বাধামুক্তি** সেট করা হয় কিভাবে, তা নিয়ে আলোচনা করা হবে। +- একটি খুব শক্তিশালী এবং ব্যবহার করা সহজ ডিপেন্ডেন্সি ইনজেকশন পদ্ধতি +- **OAuth2** এবং **JWT টোকেন** এবং **HTTP Basic** auth সহ নিরাপত্তা এবং অনুমোদনপ্রাপ্তি সম্পর্কিত বিষয়সমূহের উপর। +- **গভীরভাবে অবস্থানরত JSON মডেল** ঘোষণা করার জন্য আরও উন্নত (কিন্তু সমান সহজ) কৌশল (Pydantic কে ধন্যবাদ)। +- আরো অতিরিক্ত বৈশিষ্ট্য (স্টারলেটকে ধন্যবাদ) হিসাবে: + - **WebSockets** + - **GraphQL** + - HTTPX এবং `pytest` ভিত্তিক অত্যন্ত সহজ পরীক্ষা + - **CORS** + - **Cookie Sessions** + - ...এবং আরো। + +## কর্মক্ষমতা + +স্বাধীন TechEmpower Benchmarks দেখায় যে **FastAPI** অ্যাপ্লিকেশনগুলি Uvicorn-এর অধীনে চলমান দ্রুততমপাইথন ফ্রেমওয়ার্কগুলির মধ্যে একটি, শুধুমাত্র Starlette এবং Uvicorn-এর পর (FastAPI দ্বারা অভ্যন্তরীণভাবে ব্যবহৃত)। (\*) + +এটি সম্পর্কে আরও বুঝতে, দেখুন Benchmarks. + +## ঐচ্ছিক নির্ভরশীলতা + +Pydantic দ্বারা ব্যবহৃত: + +- ujson - দ্রুত JSON এর জন্য "parsing". +- email_validator - ইমেল যাচাইকরণের জন্য। + +স্টারলেট দ্বারা ব্যবহৃত: + +- httpx - আপনি যদি `TestClient` ব্যবহার করতে চান তাহলে আবশ্যক। +- jinja2 - আপনি যদি প্রদত্ত টেমপ্লেট রূপরেখা ব্যবহার করতে চান তাহলে প্রয়োজন। +- python-multipart - আপনি যদি ফর্ম সহায়তা করতে চান তাহলে প্রয়োজন "parsing", `request.form()` সহ। +- itsdangerous - `SessionMiddleware` সহায়তার জন্য প্রয়োজন। +- pyyaml - স্টারলেটের SchemaGenerator সাপোর্ট এর জন্য প্রয়োজন (আপনার সম্ভাবত FastAPI প্রয়োজন নেই)। +- graphene - `GraphQLApp` সহায়তার জন্য প্রয়োজন। +- ujson - আপনি `UJSONResponse` ব্যবহার করতে চাইলে প্রয়োজন। + +FastAPI / Starlette দ্বারা ব্যবহৃত: + +- uvicorn - সার্ভারের জন্য যা আপনার অ্যাপ্লিকেশন লোড করে এবং পরিবেশন করে। +- orjson - আপনি `ORJSONResponse` ব্যবহার করতে চাইলে প্রয়োজন। + +আপনি এই সব ইনস্টল করতে পারেন `pip install fastapi[all]` দিয়ে. + +## লাইসেন্স + +এই প্রজেক্ট MIT লাইসেন্স নীতিমালার অধীনে শর্তায়িত। diff --git a/docs/bn/mkdocs.yml b/docs/bn/mkdocs.yml new file mode 100644 index 0000000000000..de18856f445aa --- /dev/null +++ b/docs/bn/mkdocs.yml @@ -0,0 +1 @@ +INHERIT: ../en/mkdocs.yml diff --git a/docs/de/docs/tutorial/background-tasks.md b/docs/de/docs/tutorial/background-tasks.md new file mode 100644 index 0000000000000..a7bfd55a7dae8 --- /dev/null +++ b/docs/de/docs/tutorial/background-tasks.md @@ -0,0 +1,126 @@ +# Hintergrundtasks + +Sie können Hintergrundtasks (Hintergrund-Aufgaben) definieren, die *nach* der Rückgabe einer Response ausgeführt werden sollen. + +Das ist nützlich für Vorgänge, die nach einem Request ausgeführt werden müssen, bei denen der Client jedoch nicht unbedingt auf den Abschluss des Vorgangs warten muss, bevor er die Response erhält. + +Hierzu zählen beispielsweise: + +* E-Mail-Benachrichtigungen, die nach dem Ausführen einer Aktion gesendet werden: + * Da die Verbindung zu einem E-Mail-Server und das Senden einer E-Mail in der Regel „langsam“ ist (einige Sekunden), können Sie die Response sofort zurücksenden und die E-Mail-Benachrichtigung im Hintergrund senden. +* Daten verarbeiten: + * Angenommen, Sie erhalten eine Datei, die einen langsamen Prozess durchlaufen muss. Sie können als Response „Accepted“ (HTTP 202) zurückgeben und die Datei im Hintergrund verarbeiten. + +## `BackgroundTasks` verwenden + +Importieren Sie zunächst `BackgroundTasks` und definieren Sie einen Parameter in Ihrer *Pfadoperation-Funktion* mit der Typdeklaration `BackgroundTasks`: + +```Python hl_lines="1 13" +{!../../../docs_src/background_tasks/tutorial001.py!} +``` + +**FastAPI** erstellt für Sie das Objekt vom Typ `BackgroundTasks` und übergibt es als diesen Parameter. + +## Eine Taskfunktion erstellen + +Erstellen Sie eine Funktion, die als Hintergrundtask ausgeführt werden soll. + +Es handelt sich schlicht um eine Standard-Funktion, die Parameter empfangen kann. + +Es kann sich um eine `async def`- oder normale `def`-Funktion handeln. **FastAPI** weiß, wie damit zu verfahren ist. + +In diesem Fall schreibt die Taskfunktion in eine Datei (den Versand einer E-Mail simulierend). + +Und da der Schreibvorgang nicht `async` und `await` verwendet, definieren wir die Funktion mit normalem `def`: + +```Python hl_lines="6-9" +{!../../../docs_src/background_tasks/tutorial001.py!} +``` + +## Den Hintergrundtask hinzufügen + +Übergeben Sie innerhalb Ihrer *Pfadoperation-Funktion* Ihre Taskfunktion mit der Methode `.add_task()` an das *Hintergrundtasks*-Objekt: + +```Python hl_lines="14" +{!../../../docs_src/background_tasks/tutorial001.py!} +``` + +`.add_task()` erhält als Argumente: + +* Eine Taskfunktion, die im Hintergrund ausgeführt wird (`write_notification`). +* Eine beliebige Folge von Argumenten, die der Reihe nach an die Taskfunktion übergeben werden sollen (`email`). +* Alle Schlüsselwort-Argumente, die an die Taskfunktion übergeben werden sollen (`message="some notification"`). + +## Dependency Injection + +Die Verwendung von `BackgroundTasks` funktioniert auch mit dem Dependency Injection System. Sie können einen Parameter vom Typ `BackgroundTasks` auf mehreren Ebenen deklarieren: in einer *Pfadoperation-Funktion*, in einer Abhängigkeit (Dependable), in einer Unterabhängigkeit usw. + +**FastAPI** weiß, was jeweils zu tun ist und wie dasselbe Objekt wiederverwendet werden kann, sodass alle Hintergrundtasks zusammengeführt und anschließend im Hintergrund ausgeführt werden: + +=== "Python 3.10+" + + ```Python hl_lines="13 15 22 25" + {!> ../../../docs_src/background_tasks/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="13 15 22 25" + {!> ../../../docs_src/background_tasks/tutorial002_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="14 16 23 26" + {!> ../../../docs_src/background_tasks/tutorial002_an.py!} + ``` + +=== "Python 3.10+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="11 13 20 23" + {!> ../../../docs_src/background_tasks/tutorial002_py310.py!} + ``` + +=== "Python 3.8+ nicht annotiert" + + !!! tip "Tipp" + Bevorzugen Sie die `Annotated`-Version, falls möglich. + + ```Python hl_lines="13 15 22 25" + {!> ../../../docs_src/background_tasks/tutorial002.py!} + ``` + +In obigem Beispiel werden die Nachrichten, *nachdem* die Response gesendet wurde, in die Datei `log.txt` geschrieben. + +Wenn im Request ein Query-Parameter enthalten war, wird dieser in einem Hintergrundtask in das Log geschrieben. + +Und dann schreibt ein weiterer Hintergrundtask, der in der *Pfadoperation-Funktion* erstellt wird, eine Nachricht unter Verwendung des Pfad-Parameters `email`. + +## Technische Details + +Die Klasse `BackgroundTasks` stammt direkt von `starlette.background`. + +Sie wird direkt in FastAPI importiert/inkludiert, sodass Sie sie von `fastapi` importieren können und vermeiden, versehentlich das alternative `BackgroundTask` (ohne das `s` am Ende) von `starlette.background` zu importieren. + +Indem Sie nur `BackgroundTasks` (und nicht `BackgroundTask`) verwenden, ist es dann möglich, es als *Pfadoperation-Funktion*-Parameter zu verwenden und **FastAPI** den Rest für Sie erledigen zu lassen, genau wie bei der direkten Verwendung des `Request`-Objekts. + +Es ist immer noch möglich, `BackgroundTask` allein in FastAPI zu verwenden, aber Sie müssen das Objekt in Ihrem Code erstellen und eine Starlette-`Response` zurückgeben, die es enthält. + +Weitere Details finden Sie in der offiziellen Starlette-Dokumentation für Hintergrundtasks. + +## Vorbehalt + +Wenn Sie umfangreiche Hintergrundberechnungen durchführen müssen und diese nicht unbedingt vom selben Prozess ausgeführt werden müssen (z. B. müssen Sie Speicher, Variablen, usw. nicht gemeinsam nutzen), könnte die Verwendung anderer größerer Tools wie z. B. Celery von Vorteil sein. + +Sie erfordern in der Regel komplexere Konfigurationen und einen Nachrichten-/Job-Queue-Manager wie RabbitMQ oder Redis, ermöglichen Ihnen jedoch die Ausführung von Hintergrundtasks in mehreren Prozessen und insbesondere auf mehreren Servern. + +Um ein Beispiel zu sehen, sehen Sie sich die [Projektgeneratoren](../project-generation.md){.internal-link target=_blank} an. Sie alle enthalten Celery, bereits konfiguriert. + +Wenn Sie jedoch über dieselbe **FastAPI**-Anwendung auf Variablen und Objekte zugreifen oder kleine Hintergrundtasks ausführen müssen (z. B. das Senden einer E-Mail-Benachrichtigung), können Sie einfach `BackgroundTasks` verwenden. + +## Zusammenfassung + +Importieren und verwenden Sie `BackgroundTasks` mit Parametern in *Pfadoperation-Funktionen* und Abhängigkeiten, um Hintergrundtasks hinzuzufügen. diff --git a/docs/de/docs/tutorial/first-steps.md b/docs/de/docs/tutorial/first-steps.md new file mode 100644 index 0000000000000..27ba3ec16795e --- /dev/null +++ b/docs/de/docs/tutorial/first-steps.md @@ -0,0 +1,333 @@ +# Erste Schritte + +Die einfachste FastAPI-Datei könnte wie folgt aussehen: + +```Python +{!../../../docs_src/first_steps/tutorial001.py!} +``` + +Kopieren Sie dies in eine Datei `main.py`. + +Starten Sie den 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. +``` + +
+ +!!! note "Hinweis" + Der Befehl `uvicorn main:app` bezieht sich auf: + + * `main`: die Datei `main.py` (das sogenannte Python-„Modul“). + * `app`: das Objekt, welches in der Datei `main.py` mit der Zeile `app = FastAPI()` erzeugt wurde. + * `--reload`: lässt den Server nach Codeänderungen neu starten. Verwenden Sie das nur während der Entwicklung. + +In der Konsolenausgabe sollte es eine Zeile geben, die ungefähr so aussieht: + +```hl_lines="4" +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +Diese Zeile zeigt die URL, unter der Ihre Anwendung auf Ihrem lokalen Computer bereitgestellt wird. + +### Testen Sie es + +Öffnen Sie Ihren Browser unter http://127.0.0.1:8000. + +Sie werden folgende JSON-Response sehen: + +```JSON +{"message": "Hello World"} +``` + +### Interaktive API-Dokumentation + +Gehen Sie als Nächstes auf http://127.0.0.1:8000/docs . + +Sie werden die automatisch erzeugte, interaktive API-Dokumentation sehen (bereitgestellt durch Swagger UI): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### Alternative API-Dokumentation + +Gehen Sie nun auf http://127.0.0.1:8000/redoc. + +Dort sehen Sie die alternative, automatische Dokumentation (bereitgestellt durch ReDoc): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +### OpenAPI + +**FastAPI** generiert ein „Schema“ mit all Ihren APIs unter Verwendung des **OpenAPI**-Standards zur Definition von APIs. + +#### „Schema“ + +Ein „Schema“ ist eine Definition oder Beschreibung von etwas. Nicht der eigentliche Code, der es implementiert, sondern lediglich eine abstrakte Beschreibung. + +#### API-„Schema“ + +In diesem Fall ist OpenAPI eine Spezifikation, die vorschreibt, wie ein Schema für Ihre API zu definieren ist. + +Diese Schemadefinition enthält Ihre API-Pfade, die möglichen Parameter, welche diese entgegennehmen, usw. + +#### Daten-„Schema“ + +Der Begriff „Schema“ kann sich auch auf die Form von Daten beziehen, wie z. B. einen JSON-Inhalt. + +In diesem Fall sind die JSON-Attribute und deren Datentypen, usw. gemeint. + +#### OpenAPI und JSON Schema + +OpenAPI definiert ein API-Schema für Ihre API. Dieses Schema enthält Definitionen (oder „Schemas“) der Daten, die von Ihrer API unter Verwendung von **JSON Schema**, dem Standard für JSON-Datenschemata, gesendet und empfangen werden. + +#### Überprüfen Sie die `openapi.json` + +Falls Sie wissen möchten, wie das rohe OpenAPI-Schema aussieht: FastAPI generiert automatisch ein JSON (Schema) mit den Beschreibungen Ihrer gesamten API. + +Sie können es direkt einsehen unter: http://127.0.0.1:8000/openapi.json. + +Es wird ein JSON angezeigt, welches ungefähr so aussieht: + +```JSON +{ + "openapi": "3.1.0", + "info": { + "title": "FastAPI", + "version": "0.1.0" + }, + "paths": { + "/items/": { + "get": { + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + + + +... +``` + +#### Wofür OpenAPI gedacht ist + +Das OpenAPI-Schema ist die Grundlage für die beiden enthaltenen interaktiven Dokumentationssysteme. + +Es gibt dutzende Alternativen, die alle auf OpenAPI basieren. Sie können jede dieser Alternativen problemlos zu Ihrer mit **FastAPI** erstellten Anwendung hinzufügen. + +Ebenfalls können Sie es verwenden, um automatisch Code für Clients zu generieren, die mit Ihrer API kommunizieren. Zum Beispiel für Frontend-, Mobile- oder IoT-Anwendungen. + +## Rückblick, Schritt für Schritt + +### Schritt 1: Importieren von `FastAPI` + +```Python hl_lines="1" +{!../../../docs_src/first_steps/tutorial001.py!} +``` + +`FastAPI` ist eine Python-Klasse, die die gesamte Funktionalität für Ihre API bereitstellt. + +!!! note "Technische Details" + `FastAPI` ist eine Klasse, die direkt von `Starlette` erbt. + + Sie können alle Starlette-Funktionalitäten auch mit `FastAPI` nutzen. + +### Schritt 2: Erzeugen einer `FastAPI`-„Instanz“ + +```Python hl_lines="3" +{!../../../docs_src/first_steps/tutorial001.py!} +``` + +In diesem Beispiel ist die Variable `app` eine „Instanz“ der Klasse `FastAPI`. + +Dies wird der Hauptinteraktionspunkt für die Erstellung all Ihrer APIs sein. + +Die Variable `app` ist dieselbe, auf die sich der Befehl `uvicorn` bezieht: + +
+ +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +Wenn Sie Ihre Anwendung wie folgt erstellen: + +```Python hl_lines="3" +{!../../../docs_src/first_steps/tutorial002.py!} +``` + +Und in eine Datei `main.py` einfügen, dann würden Sie `uvicorn` wie folgt aufrufen: + +
+ +```console +$ uvicorn main:my_awesome_api --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +### Schritt 3: Erstellen einer *Pfadoperation* + +#### Pfad + +„Pfad“ bezieht sich hier auf den letzten Teil der URL, beginnend mit dem ersten `/`. + +In einer URL wie: + +``` +https://example.com/items/foo +``` + +... wäre der Pfad folglich: + +``` +/items/foo +``` + +!!! info + Ein „Pfad“ wird häufig auch als „Endpunkt“ oder „Route“ bezeichnet. + +Bei der Erstellung einer API ist der „Pfad“ die wichtigste Möglichkeit zur Trennung von „Anliegen“ und „Ressourcen“. + +#### Operation + +„Operation“ bezieht sich hier auf eine der HTTP-„Methoden“. + +Eine von diesen: + +* `POST` +* `GET` +* `PUT` +* `DELETE` + +... und die etwas Exotischeren: + +* `OPTIONS` +* `HEAD` +* `PATCH` +* `TRACE` + +Im HTTP-Protokoll können Sie mit jedem Pfad über eine (oder mehrere) dieser „Methoden“ kommunizieren. + +--- + +Bei der Erstellung von APIs verwenden Sie normalerweise diese spezifischen HTTP-Methoden, um eine bestimmte Aktion durchzuführen. + +Normalerweise verwenden Sie: + +* `POST`: um Daten zu erzeugen (create). +* `GET`: um Daten zu lesen (read). +* `PUT`: um Daten zu aktualisieren (update). +* `DELETE`: um Daten zu löschen (delete). + +In OpenAPI wird folglich jede dieser HTTP-Methoden als „Operation“ bezeichnet. + +Wir werden sie auch „**Operationen**“ nennen. + +#### Definieren eines *Pfadoperation-Dekorators* + +```Python hl_lines="6" +{!../../../docs_src/first_steps/tutorial001.py!} +``` + +Das `@app.get("/")` sagt **FastAPI**, dass die Funktion direkt darunter für die Bearbeitung von Anfragen zuständig ist, die an: + + * den Pfad `/` + * unter der Verwendung der get-Operation gehen + +!!! info "`@decorator` Information" + Diese `@something`-Syntax wird in Python „Dekorator“ genannt. + + Sie platzieren ihn über einer Funktion. Wie ein hübscher, dekorativer Hut (daher kommt wohl der Begriff). + + Ein „Dekorator“ nimmt die darunter stehende Funktion und macht etwas damit. + + In unserem Fall teilt dieser Dekorator **FastAPI** mit, dass die folgende Funktion mit dem **Pfad** `/` und der **Operation** `get` zusammenhängt. + + Dies ist der „**Pfadoperation-Dekorator**“. + +Sie können auch die anderen Operationen verwenden: + +* `@app.post()` +* `@app.put()` +* `@app.delete()` + +Oder die exotischeren: + +* `@app.options()` +* `@app.head()` +* `@app.patch()` +* `@app.trace()` + +!!! tip "Tipp" + Es steht Ihnen frei, jede Operation (HTTP-Methode) so zu verwenden, wie Sie es möchten. + + **FastAPI** erzwingt keine bestimmte Bedeutung. + + Die hier aufgeführten Informationen dienen als Leitfaden und sind nicht verbindlich. + + Wenn Sie beispielsweise GraphQL verwenden, führen Sie normalerweise alle Aktionen nur mit „POST“-Operationen durch. + +### Schritt 4: Definieren der **Pfadoperation-Funktion** + +Das ist unsere „**Pfadoperation-Funktion**“: + +* **Pfad**: ist `/`. +* **Operation**: ist `get`. +* **Funktion**: ist die Funktion direkt unter dem „Dekorator“ (unter `@app.get("/")`). + +```Python hl_lines="7" +{!../../../docs_src/first_steps/tutorial001.py!} +``` + +Dies ist eine Python-Funktion. + +Sie wird von **FastAPI** immer dann aufgerufen, wenn sie eine Anfrage an die URL "`/`" mittels einer `GET`-Operation erhält. + +In diesem Fall handelt es sich um eine `async`-Funktion. + +--- + +Sie könnten sie auch als normale Funktion anstelle von `async def` definieren: + +```Python hl_lines="7" +{!../../../docs_src/first_steps/tutorial003.py!} +``` + +!!! note "Hinweis" + Wenn Sie den Unterschied nicht kennen, lesen Sie [Async: *„In Eile?“*](../async.md#in-eile){.internal-link target=_blank}. + +### Schritt 5: den Inhalt zurückgeben + +```Python hl_lines="8" +{!../../../docs_src/first_steps/tutorial001.py!} +``` + +Sie können ein `dict`, eine `list`, einzelne Werte wie `str`, `int`, usw. zurückgeben. + +Sie können auch Pydantic-Modelle zurückgeben (dazu später mehr). + +Es gibt viele andere Objekte und Modelle, die automatisch zu JSON konvertiert werden (einschließlich ORMs usw.). Versuchen Sie, Ihre Lieblingsobjekte zu verwenden. Es ist sehr wahrscheinlich, dass sie bereits unterstützt werden. + +## Zusammenfassung + +* Importieren Sie `FastAPI`. +* Erstellen Sie eine `app` Instanz. +* Schreiben Sie einen **Pfadoperation-Dekorator** (wie z. B. `@app.get("/")`). +* Schreiben Sie eine **Pfadoperation-Funktion** (wie z. B. oben `def root(): ...`). +* Starten Sie den Entwicklungsserver (z. B. `uvicorn main:app --reload`). diff --git a/docs/de/docs/tutorial/index.md b/docs/de/docs/tutorial/index.md new file mode 100644 index 0000000000000..dd7ed43bdab62 --- /dev/null +++ b/docs/de/docs/tutorial/index.md @@ -0,0 +1,80 @@ +# Tutorial - Benutzerhandbuch - Intro + +Diese Anleitung zeigt Ihnen Schritt für Schritt, wie Sie **FastAPI** mit den meisten Funktionen nutzen können. + +Jeder Abschnitt baut schrittweise auf den vorhergehenden auf. Diese Abschnitte sind aber nach einzelnen Themen gegliedert, sodass Sie direkt zu einem bestimmten Thema übergehen können, um Ihre speziellen API-Anforderungen zu lösen. + +Außerdem dienen diese als zukünftige Referenz. + +Dadurch können Sie jederzeit zurückkommen und sehen genau das, was Sie benötigen. + +## Den Code ausführen + +Alle Codeblöcke können kopiert und direkt verwendet werden (da es sich um getestete Python-Dateien handelt). + +Um eines der Beispiele auszuführen, kopieren Sie den Code in die Datei `main.py`, und starten Sie `uvicorn` mit: + +
+ +```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. +``` + +
+ +Es wird **ausdrücklich empfohlen**, dass Sie den Code schreiben oder kopieren, ihn bearbeiten und lokal ausführen. + +Die Verwendung in Ihrem eigenen Editor zeigt Ihnen die Vorteile von FastAPI am besten, wenn Sie sehen, wie wenig Code Sie schreiben müssen, all die Typprüfungen, die automatische Vervollständigung usw. + +--- + +## FastAPI installieren + +Der erste Schritt besteht aus der Installation von FastAPI. + +Für dieses Tutorial empfiehlt es sich, FastAPI mit allen optionalen Abhängigkeiten und Funktionen zu installieren: + +
+ +```console +$ pip install "fastapi[all]" + +---> 100% +``` + +
+ +...dies beinhaltet auch `uvicorn`, das Sie als Server verwenden können, auf dem Ihr Code läuft. + +!!! Hinweis + Sie können die Installation auch in einzelnen Schritten ausführen. + + Dies werden Sie wahrscheinlich tun, wenn Sie Ihre Anwendung produktiv einsetzen möchten: + + ``` + pip install fastapi + ``` + + Installieren Sie auch `uvicorn`, dies arbeitet als Server: + + ``` + pip install "uvicorn[standard]" + ``` + + Dasselbe gilt für jede der optionalen Abhängigkeiten, die Sie verwenden möchten. + +## Erweitertes Benutzerhandbuch + +Zusätzlich gibt es ein **Erweitertes Benutzerhandbuch**, dies können Sie später nach diesem **Tutorial - Benutzerhandbuch** lesen. + +Das **Erweiterte Benutzerhandbuch** baut auf dieses Tutorial auf, verwendet dieselben Konzepte und bringt Ihnen zusätzliche Funktionen bei. + +Allerdings sollten Sie zuerst das **Tutorial - Benutzerhandbuch** lesen (was Sie gerade lesen). + +Es ist so konzipiert, dass Sie nur mit dem **Tutorial - Benutzerhandbuch** eine vollständige Anwendung erstellen können und diese dann je nach Bedarf mit einigen der zusätzlichen Ideen aus dem **Erweiterten Benutzerhandbuch** erweitern können. diff --git a/docs/em/docs/advanced/security/oauth2-scopes.md b/docs/em/docs/advanced/security/oauth2-scopes.md index a4684352ccd4d..d82fe152bef31 100644 --- a/docs/em/docs/advanced/security/oauth2-scopes.md +++ b/docs/em/docs/advanced/security/oauth2-scopes.md @@ -56,7 +56,7 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀. 🥇, ➡️ 🔜 👀 🍕 👈 🔀 ⚪️➡️ 🖼 👑 **🔰 - 👩‍💻 🦮** [Oauth2️⃣ ⏮️ 🔐 (& 🔁), 📨 ⏮️ 🥙 🤝](../../tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. 🔜 ⚙️ Oauth2️⃣ ↔: -```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 153" +```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" {!../../../docs_src/security/tutorial005.py!} ``` @@ -93,7 +93,7 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀. ✋️ 👆 🈸, 💂‍♂, 👆 🔜 ⚒ 💭 👆 🕴 🚮 ↔ 👈 👩‍💻 🤙 💪 ✔️, ⚖️ 🕐 👆 ✔️ 🔁. -```Python hl_lines="153" +```Python hl_lines="155" {!../../../docs_src/security/tutorial005.py!} ``` @@ -118,7 +118,7 @@ Oauth2️⃣ 🔧 🔬 "↔" 📇 🎻 🎏 🚀. 👥 🔨 ⚫️ 📥 🎦 ❔ **FastAPI** 🍵 ↔ 📣 🎏 🎚. -```Python hl_lines="4 139 166" +```Python hl_lines="4 139 168" {!../../../docs_src/security/tutorial005.py!} ``` diff --git a/docs/em/docs/advanced/templates.md b/docs/em/docs/advanced/templates.md index 1fb57725af175..0a73a4f47e811 100644 --- a/docs/em/docs/advanced/templates.md +++ b/docs/em/docs/advanced/templates.md @@ -27,7 +27,7 @@ $ pip install jinja2 * 📣 `Request` 🔢 *➡ 🛠️* 👈 🔜 📨 📄. * ⚙️ `templates` 👆 ✍ ✍ & 📨 `TemplateResponse`, 🚶‍♀️ `request` 1️⃣ 🔑-💲 👫 Jinja2️⃣ "🔑". -```Python hl_lines="4 11 15-16" +```Python hl_lines="4 11 15-18" {!../../../docs_src/templates/tutorial001.py!} ``` diff --git a/docs/em/docs/tutorial/bigger-applications.md b/docs/em/docs/tutorial/bigger-applications.md index 7b4694387dd9b..c30bba106afa4 100644 --- a/docs/em/docs/tutorial/bigger-applications.md +++ b/docs/em/docs/tutorial/bigger-applications.md @@ -79,7 +79,7 @@ 👆 🗄 ⚫️ & ✍ "👐" 🎏 🌌 👆 🔜 ⏮️ 🎓 `FastAPI`: -```Python hl_lines="1 3" +```Python hl_lines="1 3" title="app/routers/users.py" {!../../../docs_src/bigger_applications/app/routers/users.py!} ``` @@ -89,7 +89,7 @@ ⚙️ ⚫️ 🎏 🌌 👆 🔜 ⚙️ `FastAPI` 🎓: -```Python hl_lines="6 11 16" +```Python hl_lines="6 11 16" title="app/routers/users.py" {!../../../docs_src/bigger_applications/app/routers/users.py!} ``` @@ -112,7 +112,7 @@ 👥 🔜 🔜 ⚙️ 🙅 🔗 ✍ 🛃 `X-Token` 🎚: -```Python hl_lines="1 4-6" +```Python hl_lines="1 4-6" title="app/dependencies.py" {!../../../docs_src/bigger_applications/app/dependencies.py!} ``` @@ -143,7 +143,7 @@ , ↩️ ❎ 🌐 👈 🔠 *➡ 🛠️*, 👥 💪 🚮 ⚫️ `APIRouter`. -```Python hl_lines="5-10 16 21" +```Python hl_lines="5-10 16 21" title="app/routers/items.py" {!../../../docs_src/bigger_applications/app/routers/items.py!} ``` @@ -195,7 +195,7 @@ async def read_item(item_id: str): 👥 ⚙️ ⚖ 🗄 ⏮️ `..` 🔗: -```Python hl_lines="3" +```Python hl_lines="3" title="app/routers/items.py" {!../../../docs_src/bigger_applications/app/routers/items.py!} ``` @@ -265,7 +265,7 @@ that 🔜 ⛓: ✋️ 👥 💪 🚮 _🌅_ `tags` 👈 🔜 ✔ 🎯 *➡ 🛠️*, & ➕ `responses` 🎯 👈 *➡ 🛠️*: -```Python hl_lines="30-31" +```Python hl_lines="30-31" title="app/routers/items.py" {!../../../docs_src/bigger_applications/app/routers/items.py!} ``` @@ -290,7 +290,7 @@ that 🔜 ⛓: & 👥 💪 📣 [🌐 🔗](dependencies/global-dependencies.md){.internal-link target=_blank} 👈 🔜 🌀 ⏮️ 🔗 🔠 `APIRouter`: -```Python hl_lines="1 3 7" +```Python hl_lines="1 3 7" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -298,7 +298,7 @@ that 🔜 ⛓: 🔜 👥 🗄 🎏 🔁 👈 ✔️ `APIRouter`Ⓜ: -```Python hl_lines="5" +```Python hl_lines="5" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -360,7 +360,7 @@ from .routers.users import router , 💪 ⚙️ 👯‍♂️ 👫 🎏 📁, 👥 🗄 🔁 🔗: -```Python hl_lines="4" +```Python hl_lines="5" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -368,7 +368,7 @@ from .routers.users import router 🔜, ➡️ 🔌 `router`Ⓜ ⚪️➡️ 🔁 `users` & `items`: -```Python hl_lines="10-11" +```Python hl_lines="10-11" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -401,7 +401,7 @@ from .routers.users import router 👉 🖼 ⚫️ 🔜 💎 🙅. ✋️ ➡️ 💬 👈 ↩️ ⚫️ 💰 ⏮️ 🎏 🏗 🏢, 👥 🚫🔜 🔀 ⚫️ & 🚮 `prefix`, `dependencies`, `tags`, ♒️. 🔗 `APIRouter`: -```Python hl_lines="3" +```Python hl_lines="3" title="app/internal/admin.py" {!../../../docs_src/bigger_applications/app/internal/admin.py!} ``` @@ -409,7 +409,7 @@ from .routers.users import router 👥 💪 📣 🌐 👈 🍵 ✔️ 🔀 ⏮️ `APIRouter` 🚶‍♀️ 👈 🔢 `app.include_router()`: -```Python hl_lines="14-17" +```Python hl_lines="14-17" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -432,7 +432,7 @@ from .routers.users import router 📥 👥 ⚫️... 🎦 👈 👥 💪 🤷: -```Python hl_lines="21-23" +```Python hl_lines="21-23" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` diff --git a/docs/em/docs/tutorial/security/oauth2-jwt.md b/docs/em/docs/tutorial/security/oauth2-jwt.md index bc207c5666d90..bc3c943f86dc6 100644 --- a/docs/em/docs/tutorial/security/oauth2-jwt.md +++ b/docs/em/docs/tutorial/security/oauth2-jwt.md @@ -192,13 +192,13 @@ $ openssl rand -hex 32 === "🐍 3️⃣.6️⃣ & 🔛" - ```Python hl_lines="115-128" + ```Python hl_lines="115-130" {!> ../../../docs_src/security/tutorial004.py!} ``` === "🐍 3️⃣.1️⃣0️⃣ & 🔛" - ```Python hl_lines="114-127" + ```Python hl_lines="114-129" {!> ../../../docs_src/security/tutorial004_py310.py!} ``` diff --git a/docs/em/docs/tutorial/sql-databases.md b/docs/em/docs/tutorial/sql-databases.md index 9d46c2460843a..e3ced7ef4c890 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 726e7eae7ec73..00d6f696dea73 100644 --- a/docs/en/data/external_links.yml +++ b/docs/en/data/external_links.yml @@ -1,5 +1,33 @@ Articles: English: + - author: Ankit Anchlia + author_link: https://linkedin.com/in/aanchlia21 + link: https://hackernoon.com/explore-how-to-effectively-use-jwt-with-fastapi + title: Explore How to Effectively Use JWT With FastAPI + - 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 + - author: Mikhail Rozhkov, Elena Samuylova + author_link: https://www.linkedin.com/in/mnrozhkov/ + link: https://www.evidentlyai.com/blog/fastapi-tutorial + title: ML serving and monitoring with FastAPI and Evidently + - author: Visual Studio Code Team + author_link: https://code.visualstudio.com/ + link: https://code.visualstudio.com/docs/python/tutorial-fastapi + title: FastAPI Tutorial in Visual Studio Code + - author: Apitally + author_link: https://apitally.io + link: https://blog.apitally.io/fastapi-application-monitoring-made-easy + title: FastAPI application monitoring made easy + - author: John Philip + author_link: https://medium.com/@amjohnphilip + link: https://python.plainenglish.io/building-a-restful-api-with-fastapi-secure-signup-and-login-functionality-included-45cdbcb36106 + title: "Building a RESTful API with FastAPI: Secure Signup and Login Functionality Included" + - author: Keshav Malik + author_link: https://theinfosecguy.xyz/ + link: https://blog.theinfosecguy.xyz/building-a-crud-api-with-fastapi-and-supabase-a-step-by-step-guide + title: Building a CRUD API with FastAPI and Supabase - author: Adejumo Ridwan Suleiman author_link: https://www.linkedin.com/in/adejumoridwan/ link: https://medium.com/python-in-plain-english/build-an-sms-spam-classifier-serverless-database-with-faunadb-and-fastapi-23dbb275bc5b @@ -12,10 +40,6 @@ Articles: author_link: https://dev.to/ link: https://dev.to/teresafds/authorization-on-fastapi-with-casbin-41og title: Authorization on FastAPI with Casbin - - author: WayScript - author_link: https://www.wayscript.com - link: https://blog.wayscript.com/fast-api-quickstart/ - title: Quickstart Guide to Build and Host Responsive APIs with Fast API and WayScript - author: New Relic author_link: https://newrelic.com link: https://newrelic.com/instant-observability/fastapi/e559ec64-f765-4470-a15f-1901fcebb468 @@ -68,10 +92,6 @@ Articles: author_link: https://dev.to/factorlive link: https://dev.to/factorlive/python-facebook-messenger-webhook-with-fastapi-on-glitch-4n90 title: Python Facebook messenger webhook with FastAPI on Glitch - - author: Dom Patmore - author_link: https://twitter.com/dompatmore - link: https://dompatmore.com/blog/authenticate-your-fastapi-app-with-auth0 - title: Authenticate Your FastAPI App with auth0 - author: Valon Januzaj author_link: https://www.linkedin.com/in/valon-januzaj-b02692187/ link: https://valonjanuzaj.medium.com/deploy-a-dockerized-fastapi-application-to-aws-cc757830ba1b @@ -84,10 +104,6 @@ Articles: author_link: https://twitter.com/louis_guitton link: https://guitton.co/posts/fastapi-monitoring/ title: How to monitor your FastAPI service - - author: Julien Harbulot - author_link: https://julienharbulot.com/ - link: https://julienharbulot.com/notification-server.html - title: HTTP server to display desktop notifications - author: Precious Ndubueze author_link: https://medium.com/@gabbyprecious2000 link: https://medium.com/@gabbyprecious2000/creating-a-crud-app-with-fastapi-part-one-7c049292ad37 @@ -136,18 +152,10 @@ Articles: author_link: https://wuilly.com/ link: https://wuilly.com/2019/10/real-time-notifications-with-python-and-postgres/ title: Real-time Notifications with Python and Postgres - - author: Benjamin Ramser - author_link: https://iwpnd.pw - link: https://iwpnd.pw/articles/2020-03/apache-kafka-fastapi-geostream - title: Apache Kafka producer and consumer with FastAPI and aiokafka - author: Navule Pavan Kumar Rao author_link: https://www.linkedin.com/in/navule/ link: https://www.tutlinks.com/create-and-deploy-fastapi-app-to-heroku/ title: Create and Deploy FastAPI app to Heroku without using Docker - - author: Benjamin Ramser - author_link: https://iwpnd.pw - link: https://iwpnd.pw/articles/2020-01/deploy-fastapi-to-aws-lambda - title: How to continuously deploy a FastAPI to AWS Lambda with AWS SAM - author: Arthur Henrique author_link: https://twitter.com/arthurheinrique link: https://medium.com/@arthur393/another-boilerplate-to-fastapi-azure-pipeline-ci-pytest-3c8d9a4be0bb @@ -172,10 +180,6 @@ Articles: author_link: https://dev.to/dbanty link: https://dev.to/dbanty/why-i-m-leaving-flask-3ki6 title: Why I'm Leaving Flask - - author: Rob Wagner - author_link: https://robwagner.dev/ - link: https://robwagner.dev/tortoise-fastapi-setup/ - title: Setting up Tortoise ORM with FastAPI - author: Mike Moritz author_link: https://medium.com/@mike.p.moritz link: https://medium.com/@mike.p.moritz/using-docker-compose-to-deploy-a-lightweight-python-rest-api-with-a-job-queue-37e6072a209b @@ -333,6 +337,10 @@ Podcasts: title: FastAPI on PythonBytes Talks: English: + - author: Jeny Sadadia + author_link: https://github.com/JenySadadia + link: https://www.youtube.com/watch?v=uZdTe8_Z6BQ + title: 'PyCon AU 2023: Testing asynchronous applications with FastAPI and pytest' - author: Sebastián Ramírez (tiangolo) author_link: https://twitter.com/tiangolo link: https://www.youtube.com/watch?v=PnpTY1f4k2U diff --git a/docs/en/data/github_sponsors.yml b/docs/en/data/github_sponsors.yml index b9d74ea7b1db3..713f229cf4de2 100644 --- a/docs/en/data/github_sponsors.yml +++ b/docs/en/data/github_sponsors.yml @@ -1,19 +1,25 @@ sponsors: -- - login: bump-sh +- - login: scalar + avatarUrl: https://avatars.githubusercontent.com/u/301879?v=4 + url: https://github.com/scalar + - login: codacy + avatarUrl: https://avatars.githubusercontent.com/u/1834093?v=4 + url: https://github.com/codacy + - login: bump-sh avatarUrl: https://avatars.githubusercontent.com/u/33217836?v=4 url: https://github.com/bump-sh + - login: Alek99 + avatarUrl: https://avatars.githubusercontent.com/u/38776361?u=bd6c163fe787c2de1a26c881598e54b67e2482dd&v=4 + url: https://github.com/Alek99 - login: cryptapi avatarUrl: https://avatars.githubusercontent.com/u/44925437?u=61369138589bc7fee6c417f3fbd50fbd38286cc4&v=4 url: https://github.com/cryptapi - login: porter-dev avatarUrl: https://avatars.githubusercontent.com/u/62078005?v=4 url: https://github.com/porter-dev - - login: fern-api - avatarUrl: https://avatars.githubusercontent.com/u/102944815?v=4 - url: https://github.com/fern-api - - login: nanram22 - avatarUrl: https://avatars.githubusercontent.com/u/116367316?v=4 - url: https://github.com/nanram22 + - login: andrew-propelauth + avatarUrl: https://avatars.githubusercontent.com/u/89474256?u=1188c27cb744bbec36447a2cfd4453126b2ddb5c&v=4 + url: https://github.com/andrew-propelauth - - login: nihpo avatarUrl: https://avatars.githubusercontent.com/u/1841030?u=0264956d7580f7e46687a762a7baa629f84cf97c&v=4 url: https://github.com/nihpo @@ -21,7 +27,7 @@ sponsors: avatarUrl: https://avatars.githubusercontent.com/u/65656077?v=4 url: https://github.com/ObliviousAI - - login: mikeckennedy - avatarUrl: https://avatars.githubusercontent.com/u/2035561?u=1bb18268bcd4d9249e1f783a063c27df9a84c05b&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/2035561?u=ce6165b799ea3164cb6f5ff54ea08042057442af&v=4 url: https://github.com/mikeckennedy - login: ndimares avatarUrl: https://avatars.githubusercontent.com/u/6267663?u=cfb27efde7a7212be8142abb6c058a1aeadb41b1&v=4 @@ -32,12 +38,12 @@ sponsors: - login: deepset-ai avatarUrl: https://avatars.githubusercontent.com/u/51827949?v=4 url: https://github.com/deepset-ai + - login: databento + avatarUrl: https://avatars.githubusercontent.com/u/64141749?v=4 + url: https://github.com/databento - login: svix avatarUrl: https://avatars.githubusercontent.com/u/80175132?v=4 url: https://github.com/svix - - login: databento-bot - avatarUrl: https://avatars.githubusercontent.com/u/98378480?u=494f679996e39427f7ddb1a7de8441b7c96fb670&v=4 - url: https://github.com/databento-bot - login: VincentParedes avatarUrl: https://avatars.githubusercontent.com/u/103889729?v=4 url: https://github.com/VincentParedes @@ -59,16 +65,10 @@ sponsors: - login: jina-ai avatarUrl: https://avatars.githubusercontent.com/u/60539444?v=4 url: https://github.com/jina-ai -- - login: HiredScore - avatarUrl: https://avatars.githubusercontent.com/u/3908850?v=4 - url: https://github.com/HiredScore - - login: Trivie +- - login: Trivie avatarUrl: https://avatars.githubusercontent.com/u/8161763?v=4 url: https://github.com/Trivie -- - login: moellenbeck - avatarUrl: https://avatars.githubusercontent.com/u/169372?v=4 - url: https://github.com/moellenbeck - - login: birkjernstrom +- - login: birkjernstrom avatarUrl: https://avatars.githubusercontent.com/u/281715?u=4be14b43f76b4bd497b1941309bb390250b405e6&v=4 url: https://github.com/birkjernstrom - login: yasyf @@ -83,27 +83,39 @@ sponsors: - login: mainframeindustries avatarUrl: https://avatars.githubusercontent.com/u/55092103?v=4 url: https://github.com/mainframeindustries + - login: doseiai + avatarUrl: https://avatars.githubusercontent.com/u/57115726?v=4 + url: https://github.com/doseiai + - login: CanoaPBC + avatarUrl: https://avatars.githubusercontent.com/u/64223768?v=4 + url: https://github.com/CanoaPBC - - login: povilasb avatarUrl: https://avatars.githubusercontent.com/u/1213442?u=b11f58ed6ceea6e8297c9b310030478ebdac894d&v=4 url: https://github.com/povilasb - login: primer-io avatarUrl: https://avatars.githubusercontent.com/u/62146168?v=4 url: https://github.com/primer-io -- - login: NateXVI - avatarUrl: https://avatars.githubusercontent.com/u/48195620?u=4bc8751ae50cb087c40c1fe811764aa070b9eea6&v=4 - url: https://github.com/NateXVI +- - login: upciti + avatarUrl: https://avatars.githubusercontent.com/u/43346262?v=4 + url: https://github.com/upciti - - login: Kludex avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex - login: samuelcolvin avatarUrl: https://avatars.githubusercontent.com/u/4039449?u=42eb3b833047c8c4b4f647a031eaef148c16d93f&v=4 url: https://github.com/samuelcolvin + - login: koconder + avatarUrl: https://avatars.githubusercontent.com/u/25068?u=582657b23622aaa3dfe68bd028a780f272f456fa&v=4 + url: https://github.com/koconder - login: jefftriplett avatarUrl: https://avatars.githubusercontent.com/u/50527?u=af1ddfd50f6afd6d99f333ba2ac8d0a5b245ea74&v=4 url: https://github.com/jefftriplett - login: jstanden avatarUrl: https://avatars.githubusercontent.com/u/63288?u=c3658d57d2862c607a0e19c2101c3c51876e36ad&v=4 url: https://github.com/jstanden + - login: andreaso + avatarUrl: https://avatars.githubusercontent.com/u/285964?u=837265cc7562c0685f25b2d81cd9de0434fe107c&v=4 + url: https://github.com/andreaso - login: pamelafox avatarUrl: https://avatars.githubusercontent.com/u/297042?v=4 url: https://github.com/pamelafox @@ -119,18 +131,21 @@ sponsors: - login: falkben avatarUrl: https://avatars.githubusercontent.com/u/653031?u=ad9838e089058c9e5a0bab94c0eec7cc181e0cd0&v=4 url: https://github.com/falkben - - login: jqueguiner - avatarUrl: https://avatars.githubusercontent.com/u/690878?u=bd65cc1f228ce6455e56dfaca3ef47c33bc7c3b0&v=4 - url: https://github.com/jqueguiner + - login: mintuhouse + avatarUrl: https://avatars.githubusercontent.com/u/769950?u=ecfbd79a97d33177e0d093ddb088283cf7fe8444&v=4 + url: https://github.com/mintuhouse - login: tcsmith avatarUrl: https://avatars.githubusercontent.com/u/989034?u=7d8d741552b3279e8f4d3878679823a705a46f8f&v=4 url: https://github.com/tcsmith - - login: mrkmcknz - avatarUrl: https://avatars.githubusercontent.com/u/1089376?u=2b9b8a8c25c33a4f6c220095638bd821cdfd13a3&v=4 - url: https://github.com/mrkmcknz - login: mickaelandrieu avatarUrl: https://avatars.githubusercontent.com/u/1247388?u=599f6e73e452a9453f2bd91e5c3100750e731ad4&v=4 url: https://github.com/mickaelandrieu + - login: knallgelb + avatarUrl: https://avatars.githubusercontent.com/u/2358812?u=c48cb6362b309d74cbf144bd6ad3aed3eb443e82&v=4 + url: https://github.com/knallgelb + - login: johannquerne + avatarUrl: https://avatars.githubusercontent.com/u/2736484?u=9b3381546a25679913a2b08110e4373c98840821&v=4 + url: https://github.com/johannquerne - login: Shark009 avatarUrl: https://avatars.githubusercontent.com/u/3163309?u=0c6f4091b0eda05c44c390466199826e6dc6e431&v=4 url: https://github.com/Shark009 @@ -150,7 +165,7 @@ sponsors: avatarUrl: https://avatars.githubusercontent.com/u/3654837?v=4 url: https://github.com/anomaly - login: jgreys - avatarUrl: https://avatars.githubusercontent.com/u/4136890?u=c66ae617d614f6c886f1f1c1799d22100b3c848d&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/4136890?u=096820d1ef89877d57d0f68e669ead8b0fde84df&v=4 url: https://github.com/jgreys - login: jaredtrog avatarUrl: https://avatars.githubusercontent.com/u/4381365?v=4 @@ -174,7 +189,7 @@ sponsors: avatarUrl: https://avatars.githubusercontent.com/u/6152183?u=c485eefca5c6329600cae63dd35e4f5682ce6924&v=4 url: https://github.com/iwpnd - login: FernandoCelmer - avatarUrl: https://avatars.githubusercontent.com/u/6262214?u=ab6108a843a2fb9df0934f482375d2907609f3ff&v=4 + 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 @@ -188,6 +203,9 @@ sponsors: - login: wdwinslow avatarUrl: https://avatars.githubusercontent.com/u/11562137?u=dc01daafb354135603a263729e3d26d939c0c452&v=4 url: https://github.com/wdwinslow + - login: drcat101 + avatarUrl: https://avatars.githubusercontent.com/u/11951946?u=e714b957185b8cf3d301cced7fc3ad2842122c6a&v=4 + url: https://github.com/drcat101 - login: jsoques avatarUrl: https://avatars.githubusercontent.com/u/12414216?u=620921d94196546cc8b9eae2cc4cbc3f95bab42f&v=4 url: https://github.com/jsoques @@ -212,45 +230,48 @@ sponsors: - login: Filimoa avatarUrl: https://avatars.githubusercontent.com/u/21352040?u=0be845711495bbd7b756e13fcaeb8efc1ebd78ba&v=4 url: https://github.com/Filimoa - - login: rahulsalgare - avatarUrl: https://avatars.githubusercontent.com/u/21974430?u=ade6f182b94554ab8491d7421de5e78f711dcaf8&v=4 - url: https://github.com/rahulsalgare + - login: ehaca + avatarUrl: https://avatars.githubusercontent.com/u/25950317?u=cec1a3e0643b785288ae8260cc295a85ab344995&v=4 + url: https://github.com/ehaca + - login: timlrx + avatarUrl: https://avatars.githubusercontent.com/u/28362229?u=9a745ca31372ee324af682715ae88ce8522f9094&v=4 + url: https://github.com/timlrx - login: BrettskiPy avatarUrl: https://avatars.githubusercontent.com/u/30988215?u=d8a94a67e140d5ee5427724b292cc52d8827087a&v=4 url: https://github.com/BrettskiPy - - login: mauroalejandrojm - avatarUrl: https://avatars.githubusercontent.com/u/31569442?u=cdada990a1527926a36e95f62c30a8b48bbc49a1&v=4 - url: https://github.com/mauroalejandrojm - login: Leay15 avatarUrl: https://avatars.githubusercontent.com/u/32212558?u=c4aa9c1737e515959382a5515381757b1fd86c53&v=4 url: https://github.com/Leay15 - - login: dvlpjrs - avatarUrl: https://avatars.githubusercontent.com/u/32254642?u=fbd6ad0324d4f1eb6231cf775be1c7bd4404e961&v=4 - url: https://github.com/dvlpjrs - login: ygorpontelo avatarUrl: https://avatars.githubusercontent.com/u/32963605?u=35f7103f9c4c4c2589ae5737ee882e9375ef072e&v=4 url: https://github.com/ygorpontelo - login: ProteinQure avatarUrl: https://avatars.githubusercontent.com/u/33707203?v=4 url: https://github.com/ProteinQure + - login: RafaelWO + avatarUrl: https://avatars.githubusercontent.com/u/38643099?u=56c676f024667ee416dc8b1cdf0c2611b9dc994f&v=4 + url: https://github.com/RafaelWO - login: arleybri18 avatarUrl: https://avatars.githubusercontent.com/u/39681546?u=5c028f81324b0e8c73b3c15bc4e7b0218d2ba0c3&v=4 url: https://github.com/arleybri18 - login: thenickben avatarUrl: https://avatars.githubusercontent.com/u/40610922?u=1e907d904041b7c91213951a3cb344cd37c14aaf&v=4 url: https://github.com/thenickben - - login: adtalos - avatarUrl: https://avatars.githubusercontent.com/u/40748353?v=4 - url: https://github.com/adtalos - - login: ybressler - avatarUrl: https://avatars.githubusercontent.com/u/40807730?u=41e2c00f1eebe3c402635f0325e41b4e6511462c&v=4 - url: https://github.com/ybressler - login: ddilidili avatarUrl: https://avatars.githubusercontent.com/u/42176885?u=c0a849dde06987434653197b5f638d3deb55fc6c&v=4 url: https://github.com/ddilidili + - login: ramonalmeidam + avatarUrl: https://avatars.githubusercontent.com/u/45269580?u=3358750b3a5854d7c3ed77aaca7dd20a0f529d32&v=4 + url: https://github.com/ramonalmeidam - login: dudikbender avatarUrl: https://avatars.githubusercontent.com/u/53487583?u=3a57542938ebfd57579a0111db2b297e606d9681&v=4 url: https://github.com/dudikbender + - login: Amirshox + avatarUrl: https://avatars.githubusercontent.com/u/56707784?u=2a2f8cc243d6f5b29cd63fd2772f7a97aadc6c6b&v=4 + url: https://github.com/Amirshox + - login: prodhype + avatarUrl: https://avatars.githubusercontent.com/u/60444672?u=3f278cff25ea37ead487d7861d4a984795de819e&v=4 + url: https://github.com/prodhype - login: yakkonaut avatarUrl: https://avatars.githubusercontent.com/u/60633704?u=90a71fd631aa998ba4a96480788f017c9904e07b&v=4 url: https://github.com/yakkonaut @@ -260,18 +281,24 @@ sponsors: - login: anthonycepeda avatarUrl: https://avatars.githubusercontent.com/u/72019805?u=4252c6b6dc5024af502a823a3ac5e7a03a69963f&v=4 url: https://github.com/anthonycepeda + - login: patricioperezv + avatarUrl: https://avatars.githubusercontent.com/u/73832292?u=5f471f156e19ee7920e62ae0f4a47b95580e61cf&v=4 + url: https://github.com/patricioperezv + - login: kaoru0310 + avatarUrl: https://avatars.githubusercontent.com/u/80977929?u=1b61d10142b490e56af932ddf08a390fae8ee94f&v=4 + url: https://github.com/kaoru0310 - login: DelfinaCare avatarUrl: https://avatars.githubusercontent.com/u/83734439?v=4 url: https://github.com/DelfinaCare - login: osawa-koki avatarUrl: https://avatars.githubusercontent.com/u/94336223?u=59c6fe6945bcbbaff87b2a794238671b060620d2&v=4 url: https://github.com/osawa-koki - - login: pyt3h - avatarUrl: https://avatars.githubusercontent.com/u/99658549?v=4 - url: https://github.com/pyt3h -- - login: SebTota - avatarUrl: https://avatars.githubusercontent.com/u/25122511?v=4 - url: https://github.com/SebTota + - login: apitally + avatarUrl: https://avatars.githubusercontent.com/u/138365043?v=4 + url: https://github.com/apitally +- - login: getsentry + avatarUrl: https://avatars.githubusercontent.com/u/1396951?v=4 + url: https://github.com/getsentry - - login: pawamoy avatarUrl: https://avatars.githubusercontent.com/u/3999221?u=b030e4c89df2f3a36bc4710b925bdeb6745c9856&v=4 url: https://github.com/pawamoy @@ -281,9 +308,6 @@ sponsors: - login: bryanculbertson avatarUrl: https://avatars.githubusercontent.com/u/144028?u=defda4f90e93429221cc667500944abde60ebe4a&v=4 url: https://github.com/bryanculbertson - - login: yourkin - avatarUrl: https://avatars.githubusercontent.com/u/178984?u=b43a7e5f8818f7d9083d3b110118d9c27d48a794&v=4 - url: https://github.com/yourkin - login: slafs avatarUrl: https://avatars.githubusercontent.com/u/210173?v=4 url: https://github.com/slafs @@ -299,15 +323,18 @@ sponsors: - login: securancy avatarUrl: https://avatars.githubusercontent.com/u/606673?v=4 url: https://github.com/securancy + - login: natehouk + avatarUrl: https://avatars.githubusercontent.com/u/805439?u=d8e4be629dc5d7efae7146157e41ee0bd129d9bc&v=4 + url: https://github.com/natehouk - login: browniebroke avatarUrl: https://avatars.githubusercontent.com/u/861044?u=5abfca5588f3e906b31583d7ee62f6de4b68aa24&v=4 url: https://github.com/browniebroke - - login: janfilips - avatarUrl: https://avatars.githubusercontent.com/u/870699?u=80702ec63f14e675cd4cdcc6ce3821d2ed207fd7&v=4 - url: https://github.com/janfilips - login: dodo5522 avatarUrl: https://avatars.githubusercontent.com/u/1362607?u=9bf1e0e520cccc547c046610c468ce6115bbcf9f&v=4 url: https://github.com/dodo5522 + - login: miguelgr + avatarUrl: https://avatars.githubusercontent.com/u/1484589?u=54556072b8136efa12ae3b6902032ea2a39ace4b&v=4 + url: https://github.com/miguelgr - login: WillHogan avatarUrl: https://avatars.githubusercontent.com/u/1661551?u=7036c064cf29781470573865264ec8e60b6b809f&v=4 url: https://github.com/WillHogan @@ -323,15 +350,12 @@ sponsors: - login: anthonycorletti avatarUrl: https://avatars.githubusercontent.com/u/3477132?v=4 url: https://github.com/anthonycorletti - - login: nikeee - avatarUrl: https://avatars.githubusercontent.com/u/4068864?u=bbe73151f2b409c120160d032dc9aa6875ef0c4b&v=4 - url: https://github.com/nikeee - login: Alisa-lisa avatarUrl: https://avatars.githubusercontent.com/u/4137964?u=e7e393504f554f4ff15863a1e01a5746863ef9ce&v=4 url: https://github.com/Alisa-lisa - - login: piotrgredowski - avatarUrl: https://avatars.githubusercontent.com/u/4294480?v=4 - url: https://github.com/piotrgredowski + - login: gowikel + avatarUrl: https://avatars.githubusercontent.com/u/4339072?u=0e325ffcc539c38f89d9aa876bd87f9ec06ce0ee&v=4 + url: https://github.com/gowikel - login: danielunderwood avatarUrl: https://avatars.githubusercontent.com/u/4472301?v=4 url: https://github.com/danielunderwood @@ -347,6 +371,9 @@ sponsors: - login: Baghdady92 avatarUrl: https://avatars.githubusercontent.com/u/5708590?v=4 url: https://github.com/Baghdady92 + - login: jakeecolution + avatarUrl: https://avatars.githubusercontent.com/u/5884696?u=4a7c7883fb064b593b50cb6697b54687e6f7aafe&v=4 + url: https://github.com/jakeecolution - login: KentShikama avatarUrl: https://avatars.githubusercontent.com/u/6329898?u=8b236810db9b96333230430837e1f021f9246da1&v=4 url: https://github.com/KentShikama @@ -366,7 +393,7 @@ sponsors: avatarUrl: https://avatars.githubusercontent.com/u/8574425?u=aad2a9674273c9275fe414d99269b7418d144089&v=4 url: https://github.com/albertkun - login: xncbf - avatarUrl: https://avatars.githubusercontent.com/u/9462045?u=866a1311e4bd3ec5ae84185c4fcc99f397c883d7&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/9462045?u=ee91e210ae93b9cdd8f248b21cb028316cc0b747&v=4 url: https://github.com/xncbf - login: DMantis avatarUrl: https://avatars.githubusercontent.com/u/9536869?v=4 @@ -386,30 +413,42 @@ sponsors: - login: pheanex avatarUrl: https://avatars.githubusercontent.com/u/10408624?u=5b6bab6ee174aa6e991333e06eb29f628741013d&v=4 url: https://github.com/pheanex + - login: dzoladz + avatarUrl: https://avatars.githubusercontent.com/u/10561752?u=5ee314d54aa79592c18566827ad8914debd5630d&v=4 + url: https://github.com/dzoladz - login: JimFawkes avatarUrl: https://avatars.githubusercontent.com/u/12075115?u=dc58ecfd064d72887c34bf500ddfd52592509acd&v=4 url: https://github.com/JimFawkes + - login: artempronevskiy + avatarUrl: https://avatars.githubusercontent.com/u/12235104?u=03df6e1e55c9c6fe5d230adabb8dd7d43d8bbe8f&v=4 + url: https://github.com/artempronevskiy - login: giuliano-oliveira avatarUrl: https://avatars.githubusercontent.com/u/13181797?u=0ef2dfbf7fc9a9726d45c21d32b5d1038a174870&v=4 url: https://github.com/giuliano-oliveira - login: TheR1D avatarUrl: https://avatars.githubusercontent.com/u/16740832?u=b0dfdbdb27b79729430c71c6128962f77b7b53f7&v=4 url: https://github.com/TheR1D + - login: joshuatz + avatarUrl: https://avatars.githubusercontent.com/u/17817563?u=f1bf05b690d1fc164218f0b420cdd3acb7913e21&v=4 + url: https://github.com/joshuatz - login: jangia avatarUrl: https://avatars.githubusercontent.com/u/17927101?u=9261b9bb0c3e3bb1ecba43e8915dc58d8c9a077e&v=4 url: https://github.com/jangia - - login: timzaz - avatarUrl: https://avatars.githubusercontent.com/u/19709244?u=264d7db95c28156363760229c30ee1116efd4eeb&v=4 - url: https://github.com/timzaz - login: shuheng-liu avatarUrl: https://avatars.githubusercontent.com/u/22414322?u=813c45f30786c6b511b21a661def025d8f7b609e&v=4 url: https://github.com/shuheng-liu + - login: salahelfarissi + avatarUrl: https://avatars.githubusercontent.com/u/23387408?u=73222a4be627c1a3dee9736e0da22224eccdc8f6&v=4 + url: https://github.com/salahelfarissi - login: pers0n4 avatarUrl: https://avatars.githubusercontent.com/u/24864600?u=f211a13a7b572cbbd7779b9c8d8cb428cc7ba07e&v=4 url: https://github.com/pers0n4 - login: kxzk avatarUrl: https://avatars.githubusercontent.com/u/25046261?u=e185e58080090f9e678192cd214a14b14a2b232b&v=4 url: https://github.com/kxzk + - login: SebTota + avatarUrl: https://avatars.githubusercontent.com/u/25122511?v=4 + url: https://github.com/SebTota - login: nisutec avatarUrl: https://avatars.githubusercontent.com/u/25281462?u=e562484c451fdfc59053163f64405f8eb262b8b0&v=4 url: https://github.com/nisutec @@ -419,15 +458,12 @@ sponsors: - login: joerambo avatarUrl: https://avatars.githubusercontent.com/u/26282974?v=4 url: https://github.com/joerambo - - login: msniezynski - avatarUrl: https://avatars.githubusercontent.com/u/27588547?u=0e3be5ac57dcfdf124f470bcdf74b5bf79af1b6c&v=4 - url: https://github.com/msniezynski - login: rlnchow avatarUrl: https://avatars.githubusercontent.com/u/28018479?u=a93ca9cf1422b9ece155784a72d5f2fdbce7adff&v=4 url: https://github.com/rlnchow - - login: mertguvencli - avatarUrl: https://avatars.githubusercontent.com/u/29762151?u=16a906d90df96c8cff9ea131a575c4bc171b1523&v=4 - url: https://github.com/mertguvencli + - login: White-Mask + avatarUrl: https://avatars.githubusercontent.com/u/31826970?u=8625355dc25ddf9c85a8b2b0b9932826c4c8f44c&v=4 + url: https://github.com/White-Mask - login: HosamAlmoghraby avatarUrl: https://avatars.githubusercontent.com/u/32025281?u=aa1b09feabccbf9dc506b81c71155f32d126cefa&v=4 url: https://github.com/HosamAlmoghraby @@ -435,17 +471,11 @@ sponsors: 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=1a104991a2ea90bfe304bc0b9ef191c7e4891a0e&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/34930566?u=fa1dc8db3e920cf5c5636b97180a6f811fa01aaf&v=4 url: https://github.com/bnkc - login: declon avatarUrl: https://avatars.githubusercontent.com/u/36180226?v=4 url: https://github.com/declon - - login: miraedbswo - avatarUrl: https://avatars.githubusercontent.com/u/36796047?u=9e7a5b3e558edc61d35d0f9dfac37541bae7f56d&v=4 - url: https://github.com/miraedbswo - - login: DSMilestone6538 - avatarUrl: https://avatars.githubusercontent.com/u/37230924?u=f299dce910366471523155e0cb213356d34aadc1&v=4 - url: https://github.com/DSMilestone6538 - login: curegit avatarUrl: https://avatars.githubusercontent.com/u/37978051?u=1733c322079118c0cdc573c03d92813f50a9faec&v=4 url: https://github.com/curegit @@ -458,51 +488,51 @@ sponsors: - login: ArtyomVancyan avatarUrl: https://avatars.githubusercontent.com/u/44609997?v=4 url: https://github.com/ArtyomVancyan - - login: josehenriqueroveda - avatarUrl: https://avatars.githubusercontent.com/u/46685746?u=2e672057a7dbe1dba47e57c378fc0cac336022eb&v=4 - url: https://github.com/josehenriqueroveda - login: hgalytoby avatarUrl: https://avatars.githubusercontent.com/u/50397689?u=f4888c2c54929bd86eed0d3971d09fcb306e5088&v=4 url: https://github.com/hgalytoby - - login: eladgunders - avatarUrl: https://avatars.githubusercontent.com/u/52347338?u=83d454817cf991a035c8827d46ade050c813e2d6&v=4 - url: https://github.com/eladgunders - login: conservative-dude avatarUrl: https://avatars.githubusercontent.com/u/55538308?u=f250c44942ea6e73a6bd90739b381c470c192c11&v=4 url: https://github.com/conservative-dude + - login: Calesi19 + avatarUrl: https://avatars.githubusercontent.com/u/58052598?u=273d4fc364c004602c93dd6adeaf5cc915b93cd2&v=4 + url: https://github.com/Calesi19 - login: 0417taehyun avatarUrl: https://avatars.githubusercontent.com/u/63915557?u=47debaa860fd52c9b98c97ef357ddcec3b3fb399&v=4 url: https://github.com/0417taehyun + - login: fernandosmither + avatarUrl: https://avatars.githubusercontent.com/u/66154723?u=a76a037b5d674938a75d2cff862fb6dfd63ec214&v=4 + url: https://github.com/fernandosmither - login: romabozhanovgithub avatarUrl: https://avatars.githubusercontent.com/u/67696229?u=e4b921eef096415300425aca249348f8abb78ad7&v=4 url: https://github.com/romabozhanovgithub - login: mbukeRepo avatarUrl: https://avatars.githubusercontent.com/u/70356088?u=d2eb23e2b222a3b316c4183b05a3236b32819dc2&v=4 url: https://github.com/mbukeRepo + - login: adriiamontoto + avatarUrl: https://avatars.githubusercontent.com/u/75563346?u=eeb1350b82ecb4d96592f9b6cd1a16870c355e38&v=4 + url: https://github.com/adriiamontoto + - login: PelicanQ + avatarUrl: https://avatars.githubusercontent.com/u/77930606?v=4 + url: https://github.com/PelicanQ + - login: tahmarrrr23 + avatarUrl: https://avatars.githubusercontent.com/u/138208610?u=465a46b0ff72a74252d3e3a71ac7d2f1919cda28&v=4 + url: https://github.com/tahmarrrr23 - - login: ssbarnea avatarUrl: https://avatars.githubusercontent.com/u/102495?u=b4bf6818deefe59952ac22fec6ed8c76de1b8f7c&v=4 url: https://github.com/ssbarnea - login: Patechoc avatarUrl: https://avatars.githubusercontent.com/u/2376641?u=23b49e9eda04f078cb74fa3f93593aa6a57bb138&v=4 url: https://github.com/Patechoc - - login: LanceMoe - avatarUrl: https://avatars.githubusercontent.com/u/18505474?u=7fd3ead4364bdf215b6d75cb122b3811c391ef6b&v=4 - url: https://github.com/LanceMoe + - login: DazzyMlv + avatarUrl: https://avatars.githubusercontent.com/u/23006212?u=df429da52882b0432e5ac81d4f1b489abc86433c&v=4 + url: https://github.com/DazzyMlv - login: sadikkuzu avatarUrl: https://avatars.githubusercontent.com/u/23168063?u=d179c06bb9f65c4167fcab118526819f8e0dac17&v=4 url: https://github.com/sadikkuzu - - login: samnimoh - avatarUrl: https://avatars.githubusercontent.com/u/33413170?u=147bc516be6cb647b28d7e3b3fea3a018a331145&v=4 - url: https://github.com/samnimoh - login: danburonline - avatarUrl: https://avatars.githubusercontent.com/u/34251194?u=2cad4388c1544e539ecb732d656e42fb07b4ff2d&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/34251194?u=94935cccfbec58083ab1e535212d54f1bf2c978a&v=4 url: https://github.com/danburonline - login: rwxd avatarUrl: https://avatars.githubusercontent.com/u/40308458?u=cd04a39e3655923be4f25c2ba8a5a07b3da3230a&v=4 url: https://github.com/rwxd - - login: shywn-mrk - avatarUrl: https://avatars.githubusercontent.com/u/51455763?u=389e2608e4056fe5e1f23e9ad56a9415277504d3&v=4 - url: https://github.com/shywn-mrk - - login: almeida-matheus - avatarUrl: https://avatars.githubusercontent.com/u/66216198?u=54335eaa0ced626be5c1ff52fead1ebc032286ec&v=4 - url: https://github.com/almeida-matheus diff --git a/docs/en/data/people.yml b/docs/en/data/people.yml index db06cbdafcc6e..2877e7938c2ca 100644 --- a/docs/en/data/people.yml +++ b/docs/en/data/people.yml @@ -1,16 +1,16 @@ maintainers: - login: tiangolo - answers: 1868 - prs: 496 + answers: 1870 + prs: 523 avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=740f11212a731f56798f558ceddb0bd07642afa7&v=4 url: https://github.com/tiangolo experts: - login: Kludex - count: 501 + count: 522 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex - login: dmontagu - count: 240 + count: 241 avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 url: https://github.com/dmontagu - login: Mause @@ -21,26 +21,26 @@ experts: count: 217 avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=bba5af018423a2858d49309bed2a899bb5c34ac5&v=4 url: https://github.com/ycd +- login: jgould22 + count: 205 + avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 + url: https://github.com/jgould22 - login: JarroVGIT count: 193 avatarUrl: https://avatars.githubusercontent.com/u/13659033?u=e8bea32d07a5ef72f7dde3b2079ceb714923ca05&v=4 url: https://github.com/JarroVGIT -- login: jgould22 - count: 168 - avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 - url: https://github.com/jgould22 - login: euri10 count: 153 avatarUrl: https://avatars.githubusercontent.com/u/1104190?u=321a2e953e6645a7d09b732786c7a8061e0f8a8b&v=4 url: https://github.com/euri10 +- login: iudeen + count: 127 + avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 + url: https://github.com/iudeen - login: phy25 count: 126 avatarUrl: https://avatars.githubusercontent.com/u/331403?v=4 url: https://github.com/phy25 -- login: iudeen - count: 122 - avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 - url: https://github.com/iudeen - login: raphaelauv count: 83 avatarUrl: https://avatars.githubusercontent.com/u/10202690?u=e6f86f5c0c3026a15d6b51792fa3e532b12f1371&v=4 @@ -61,26 +61,26 @@ experts: count: 49 avatarUrl: https://avatars.githubusercontent.com/u/516999?u=437c0c5038558c67e887ccd863c1ba0f846c03da&v=4 url: https://github.com/sm-Fifteen -- login: acidjunk - count: 45 - avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 - url: https://github.com/acidjunk +- login: yinziyan1206 + count: 48 + avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4 + url: https://github.com/yinziyan1206 - login: insomnes count: 45 avatarUrl: https://avatars.githubusercontent.com/u/16958893?u=f8be7088d5076d963984a21f95f44e559192d912&v=4 url: https://github.com/insomnes -- login: Dustyposa - count: 45 - avatarUrl: https://avatars.githubusercontent.com/u/27180793?u=5cf2877f50b3eb2bc55086089a78a36f07042889&v=4 - url: https://github.com/Dustyposa - login: adriangb count: 45 avatarUrl: https://avatars.githubusercontent.com/u/1755071?u=612704256e38d6ac9cbed24f10e4b6ac2da74ecb&v=4 url: https://github.com/adriangb -- login: yinziyan1206 - count: 44 - avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4 - url: https://github.com/yinziyan1206 +- login: acidjunk + count: 45 + avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 + url: https://github.com/acidjunk +- login: Dustyposa + count: 45 + avatarUrl: https://avatars.githubusercontent.com/u/27180793?u=5cf2877f50b3eb2bc55086089a78a36f07042889&v=4 + url: https://github.com/Dustyposa - login: odiseo0 count: 43 avatarUrl: https://avatars.githubusercontent.com/u/87550035?u=241a71f6b7068738b81af3e57f45ffd723538401&v=4 @@ -93,6 +93,10 @@ experts: count: 40 avatarUrl: https://avatars.githubusercontent.com/u/11836741?u=8bd5ef7e62fe6a82055e33c4c0e0a7879ff8cfb6&v=4 url: https://github.com/includeamin +- login: n8sty + count: 40 + avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 + url: https://github.com/n8sty - login: chbndrhnns count: 38 avatarUrl: https://avatars.githubusercontent.com/u/7534547?v=4 @@ -105,14 +109,14 @@ experts: count: 35 avatarUrl: https://avatars.githubusercontent.com/u/31960541?u=47f4829c77f4962ab437ffb7995951e41eeebe9b&v=4 url: https://github.com/krishnardt -- login: n8sty - count: 32 - avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 - url: https://github.com/n8sty - login: panla count: 32 avatarUrl: https://avatars.githubusercontent.com/u/41326348?u=ba2fda6b30110411ecbf406d187907e2b420ac19&v=4 url: https://github.com/panla +- login: JavierSanchezCastro + count: 30 + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro - login: prostomarkeloff count: 28 avatarUrl: https://avatars.githubusercontent.com/u/28061158?u=72309cc1f2e04e40fa38b29969cb4e9d3f722e7b&v=4 @@ -125,22 +129,22 @@ experts: count: 25 avatarUrl: https://avatars.githubusercontent.com/u/365303?u=07ca03c5ee811eb0920e633cc3c3db73dbec1aa5&v=4 url: https://github.com/wshayes -- login: SirTelemak - count: 23 - avatarUrl: https://avatars.githubusercontent.com/u/9435877?u=719327b7d2c4c62212456d771bfa7c6b8dbb9eac&v=4 - url: https://github.com/SirTelemak - login: acnebs count: 23 avatarUrl: https://avatars.githubusercontent.com/u/9054108?v=4 url: https://github.com/acnebs +- login: SirTelemak + count: 23 + avatarUrl: https://avatars.githubusercontent.com/u/9435877?u=719327b7d2c4c62212456d771bfa7c6b8dbb9eac&v=4 + url: https://github.com/SirTelemak - login: rafsaf count: 21 avatarUrl: https://avatars.githubusercontent.com/u/51059348?u=5fe59a56e1f2f9ccd8005d71752a8276f133ae1a&v=4 url: https://github.com/rafsaf -- login: JavierSanchezCastro +- login: nymous count: 20 - avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 - url: https://github.com/JavierSanchezCastro + avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 + url: https://github.com/nymous - login: nsidnev count: 20 avatarUrl: https://avatars.githubusercontent.com/u/22559461?u=a9cc3238217e21dc8796a1a500f01b722adb082c&v=4 @@ -150,21 +154,21 @@ experts: avatarUrl: https://avatars.githubusercontent.com/u/565544?v=4 url: https://github.com/chris-allnutt - login: chrisK824 - count: 19 + count: 20 avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 url: https://github.com/chrisK824 -- login: zoliknemet - count: 18 - avatarUrl: https://avatars.githubusercontent.com/u/22326718?u=31ba446ac290e23e56eea8e4f0c558aaf0b40779&v=4 - url: https://github.com/zoliknemet +- login: ebottos94 + count: 20 + avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=e2c672da5a7977fd24d87ce6ab35f8bf5b1ed9fa&v=4 + url: https://github.com/ebottos94 - login: retnikt count: 18 avatarUrl: https://avatars.githubusercontent.com/u/24581770?v=4 url: https://github.com/retnikt -- login: ebottos94 - count: 17 - avatarUrl: https://avatars.githubusercontent.com/u/100039558?u=e2c672da5a7977fd24d87ce6ab35f8bf5b1ed9fa&v=4 - url: https://github.com/ebottos94 +- login: zoliknemet + count: 18 + avatarUrl: https://avatars.githubusercontent.com/u/22326718?u=31ba446ac290e23e56eea8e4f0c558aaf0b40779&v=4 + url: https://github.com/zoliknemet - login: Hultner count: 17 avatarUrl: https://avatars.githubusercontent.com/u/2669034?u=115e53df959309898ad8dc9443fbb35fee71df07&v=4 @@ -181,39 +185,39 @@ experts: count: 17 avatarUrl: https://avatars.githubusercontent.com/u/16540232?u=05d2beb8e034d584d0a374b99d8826327bd7f614&v=4 url: https://github.com/caeser1996 -- login: nymous +- login: dstlny count: 16 - avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 - url: https://github.com/nymous + avatarUrl: https://avatars.githubusercontent.com/u/41964673?u=9f2174f9d61c15c6e3a4c9e3aeee66f711ce311f&v=4 + url: https://github.com/dstlny - login: jonatasoli count: 16 avatarUrl: https://avatars.githubusercontent.com/u/26334101?u=071c062d2861d3dd127f6b4a5258cd8ef55d4c50&v=4 url: https://github.com/jonatasoli -- login: dstlny - count: 16 - avatarUrl: https://avatars.githubusercontent.com/u/41964673?u=9f2174f9d61c15c6e3a4c9e3aeee66f711ce311f&v=4 - url: https://github.com/dstlny -- login: abhint +- login: ghost count: 15 - avatarUrl: https://avatars.githubusercontent.com/u/25699289?u=b5d219277b4d001ac26fb8be357fddd88c29d51b&v=4 - url: https://github.com/abhint + avatarUrl: https://avatars.githubusercontent.com/u/10137?u=b1951d34a583cf12ec0d3b0781ba19be97726318&v=4 + url: https://github.com/ghost last_month_active: +- login: Ventura94 + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/43103937?u=ccb837005aaf212a449c374618c4339089e2f733&v=4 + url: https://github.com/Ventura94 +- login: JavierSanchezCastro + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro +- login: jgould22 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 + url: https://github.com/jgould22 - login: Kludex - count: 8 + count: 3 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex - login: n8sty - count: 7 + count: 3 avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 url: https://github.com/n8sty -- login: chrisK824 - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 - url: https://github.com/chrisK824 -- login: danielfcollier - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/38995330?u=5799be795fc310f75f3a5fe9242307d59b194520&v=4 - url: https://github.com/danielfcollier top_contributors: - login: waynerv count: 25 @@ -331,6 +335,10 @@ top_contributors: count: 4 avatarUrl: https://avatars.githubusercontent.com/u/61513630?u=320e43fe4dc7bc6efc64e9b8f325f8075634fd20&v=4 url: https://github.com/lsglucas +- login: adriangb + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/1755071?u=612704256e38d6ac9cbed24f10e4b6ac2da74ecb&v=4 + url: https://github.com/adriangb - login: iudeen count: 4 avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 @@ -349,25 +357,29 @@ top_contributors: url: https://github.com/rostik1410 top_reviewers: - login: Kludex - count: 139 + count: 145 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex -- login: yezz123 - count: 80 - avatarUrl: https://avatars.githubusercontent.com/u/52716203?u=d7062cbc6eb7671d5dc9cc0e32a24ae335e0f225&v=4 - url: https://github.com/yezz123 - login: BilalAlpaslan - count: 79 + count: 86 avatarUrl: https://avatars.githubusercontent.com/u/47563997?u=63ed66e304fe8d765762c70587d61d9196e5c82d&v=4 url: https://github.com/BilalAlpaslan +- login: yezz123 + count: 82 + avatarUrl: https://avatars.githubusercontent.com/u/52716203?u=d7062cbc6eb7671d5dc9cc0e32a24ae335e0f225&v=4 + url: https://github.com/yezz123 - login: iudeen - count: 54 + count: 55 avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 url: https://github.com/iudeen - login: tokusumi count: 51 avatarUrl: https://avatars.githubusercontent.com/u/41147016?u=55010621aece725aa702270b54fed829b6a1fe60&v=4 url: https://github.com/tokusumi +- login: Xewus + count: 50 + avatarUrl: https://avatars.githubusercontent.com/u/85196001?u=f8e2dc7e5104f109cef944af79050ea8d1b8f914&v=4 + url: https://github.com/Xewus - login: waynerv count: 47 avatarUrl: https://avatars.githubusercontent.com/u/39515546?u=ec35139777597cdbbbddda29bf8b9d4396b429a9&v=4 @@ -380,10 +392,6 @@ top_reviewers: count: 45 avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=bba5af018423a2858d49309bed2a899bb5c34ac5&v=4 url: https://github.com/ycd -- login: Xewus - count: 44 - avatarUrl: https://avatars.githubusercontent.com/u/85196001?u=f8e2dc7e5104f109cef944af79050ea8d1b8f914&v=4 - url: https://github.com/Xewus - login: cikay count: 41 avatarUrl: https://avatars.githubusercontent.com/u/24587499?u=e772190a051ab0eaa9c8542fcff1892471638f2b&v=4 @@ -404,22 +412,22 @@ top_reviewers: count: 28 avatarUrl: https://avatars.githubusercontent.com/u/3127847?u=b0a652331da17efeb85cd6e3a4969182e5004804&v=4 url: https://github.com/cassiobotaro +- login: lsglucas + count: 27 + avatarUrl: https://avatars.githubusercontent.com/u/61513630?u=320e43fe4dc7bc6efc64e9b8f325f8075634fd20&v=4 + url: https://github.com/lsglucas - login: komtaki count: 27 avatarUrl: https://avatars.githubusercontent.com/u/39375566?u=260ad6b1a4b34c07dbfa728da5e586f16f6d1824&v=4 url: https://github.com/komtaki -- login: lsglucas - count: 26 - avatarUrl: https://avatars.githubusercontent.com/u/61513630?u=320e43fe4dc7bc6efc64e9b8f325f8075634fd20&v=4 - url: https://github.com/lsglucas +- login: Ryandaydev + count: 25 + avatarUrl: https://avatars.githubusercontent.com/u/4292423?u=48f68868db8886fce31a1d802c1003914c6cd7c6&v=4 + url: https://github.com/Ryandaydev - login: LorhanSohaky count: 24 avatarUrl: https://avatars.githubusercontent.com/u/16273730?u=095b66f243a2cd6a0aadba9a095009f8aaf18393&v=4 url: https://github.com/LorhanSohaky -- login: Ryandaydev - count: 24 - avatarUrl: https://avatars.githubusercontent.com/u/4292423?u=809f3d1074d04bbc28012a7f17f06ea56f5bd71a&v=4 - url: https://github.com/Ryandaydev - login: dmontagu count: 23 avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 @@ -448,6 +456,10 @@ top_reviewers: count: 17 avatarUrl: https://avatars.githubusercontent.com/u/67154681?u=5d634834cc514028ea3f9115f7030b99a1f4d5a4&v=4 url: https://github.com/zy7y +- login: peidrao + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/32584628?u=a66902b40c13647d0ed0e573d598128240a4dd04&v=4 + url: https://github.com/peidrao - login: yanever count: 16 avatarUrl: https://avatars.githubusercontent.com/u/21978760?v=4 @@ -456,6 +468,10 @@ top_reviewers: count: 16 avatarUrl: https://avatars.githubusercontent.com/u/52768429?u=6a3aa15277406520ad37f6236e89466ed44bc5b8&v=4 url: https://github.com/SwftAlpc +- login: nilslindemann + count: 16 + avatarUrl: https://avatars.githubusercontent.com/u/6892179?u=1dca6a22195d6cd1ab20737c0e19a4c55d639472&v=4 + url: https://github.com/nilslindemann - login: axel584 count: 16 avatarUrl: https://avatars.githubusercontent.com/u/1334088?u=9667041f5b15dc002b6f9665fda8c0412933ac04&v=4 @@ -468,6 +484,10 @@ top_reviewers: count: 16 avatarUrl: https://avatars.githubusercontent.com/u/87962045?u=08e10fa516e844934f4b3fc7c38b33c61697e4a1&v=4 url: https://github.com/DevDae +- login: hasansezertasan + count: 16 + avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 + url: https://github.com/hasansezertasan - login: pedabraham count: 15 avatarUrl: https://avatars.githubusercontent.com/u/16860088?u=abf922a7b920bf8fdb7867d8b43e091f1e796178&v=4 @@ -480,10 +500,6 @@ top_reviewers: count: 13 avatarUrl: https://avatars.githubusercontent.com/u/6478810?u=af15d724875cec682ed8088a86d36b2798f981c0&v=4 url: https://github.com/sh0nk -- login: peidrao - count: 13 - avatarUrl: https://avatars.githubusercontent.com/u/32584628?u=a66902b40c13647d0ed0e573d598128240a4dd04&v=4 - url: https://github.com/peidrao - login: wdh99 count: 13 avatarUrl: https://avatars.githubusercontent.com/u/108172295?u=8a8fb95d5afe3e0fa33257b2aecae88d436249eb&v=4 @@ -524,6 +540,10 @@ top_reviewers: count: 10 avatarUrl: https://avatars.githubusercontent.com/u/43503750?u=f440bc9062afb3c43b9b9c6cdfdcfe31d58699ef&v=4 url: https://github.com/ComicShrimp +- login: romashevchenko + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/132477732?v=4 + url: https://github.com/romashevchenko - login: izaguerreiro count: 9 avatarUrl: https://avatars.githubusercontent.com/u/2241504?v=4 @@ -532,15 +552,3 @@ top_reviewers: count: 9 avatarUrl: https://avatars.githubusercontent.com/u/413772?u=64b77b6aa405c68a9c6bcf45f84257c66eea5f32&v=4 url: https://github.com/graingert -- login: PandaHun - count: 9 - avatarUrl: https://avatars.githubusercontent.com/u/13096845?u=646eba44db720e37d0dbe8e98e77ab534ea78a20&v=4 - url: https://github.com/PandaHun -- login: kty4119 - count: 9 - avatarUrl: https://avatars.githubusercontent.com/u/49435654?v=4 - url: https://github.com/kty4119 -- login: bezaca - count: 9 - avatarUrl: https://avatars.githubusercontent.com/u/69092910?u=4ac58eab99bd37d663f3d23551df96d4fbdbf760&v=4 - url: https://github.com/bezaca diff --git a/docs/en/docs/advanced/additional-responses.md b/docs/en/docs/advanced/additional-responses.md index 624036ce974c5..41b39c18e6bc1 100644 --- a/docs/en/docs/advanced/additional-responses.md +++ b/docs/en/docs/advanced/additional-responses.md @@ -28,7 +28,7 @@ For example, to declare another response with a status code `404` and a Pydantic ``` !!! note - Have in mind that you have to return the `JSONResponse` directly. + Keep in mind that you have to return the `JSONResponse` directly. !!! info The `model` key is not part of OpenAPI. diff --git a/docs/en/docs/advanced/async-tests.md b/docs/en/docs/advanced/async-tests.md index 9b39d70fca6a8..f9c82e6ab4602 100644 --- a/docs/en/docs/advanced/async-tests.md +++ b/docs/en/docs/advanced/async-tests.md @@ -84,6 +84,9 @@ response = client.get('/') !!! tip Note that we're using async/await with the new `AsyncClient` - the request is asynchronous. +!!! warning + If your application relies on lifespan events, the `AsyncClient` won't trigger these events. To ensure they are triggered, use `LifespanManager` from florimondmanca/asgi-lifespan. + ## Other Asynchronous Function Calls As the testing function is now asynchronous, you can now also call (and `await`) other `async` functions apart from sending requests to your FastAPI application in your tests, exactly as you would call them anywhere else in your code. diff --git a/docs/en/docs/advanced/behind-a-proxy.md b/docs/en/docs/advanced/behind-a-proxy.md index e7af77f3da1af..01998cc912626 100644 --- a/docs/en/docs/advanced/behind-a-proxy.md +++ b/docs/en/docs/advanced/behind-a-proxy.md @@ -125,7 +125,7 @@ Passing the `root_path` to `FastAPI` would be the equivalent of passing the `--r ### About `root_path` -Have in mind that the server (Uvicorn) won't use that `root_path` for anything else than passing it to the app. +Keep in mind that the server (Uvicorn) won't use that `root_path` for anything else than passing it to the app. But if you go with your browser to http://127.0.0.1:8000/app you will see the normal response: @@ -142,7 +142,7 @@ Uvicorn will expect the proxy to access Uvicorn at `http://127.0.0.1:8000/app`, ## About proxies with a stripped path prefix -Have in mind that a proxy with stripped path prefix is only one of the ways to configure it. +Keep in mind that a proxy with stripped path prefix is only one of the ways to configure it. Probably in many cases the default will be that the proxy doesn't have a stripped path prefix. diff --git a/docs/en/docs/advanced/custom-response.md b/docs/en/docs/advanced/custom-response.md index ce2619e8de5fc..827776f5e52b6 100644 --- a/docs/en/docs/advanced/custom-response.md +++ b/docs/en/docs/advanced/custom-response.md @@ -101,7 +101,7 @@ But as you passed the `HTMLResponse` in the `response_class` too, **FastAPI** wi Here are some of the available responses. -Have in mind that you can use `Response` to return anything else, or even create a custom sub-class. +Keep in mind that you can use `Response` to return anything else, or even create a custom sub-class. !!! note "Technical Details" You could also use `from starlette.responses import HTMLResponse`. diff --git a/docs/en/docs/advanced/dataclasses.md b/docs/en/docs/advanced/dataclasses.md index 72daca06ad9f7..ed1d5610fc279 100644 --- a/docs/en/docs/advanced/dataclasses.md +++ b/docs/en/docs/advanced/dataclasses.md @@ -21,7 +21,7 @@ And of course, it supports the same: This works the same way as with Pydantic models. And it is actually achieved in the same way underneath, using Pydantic. !!! info - Have in mind that dataclasses can't do everything Pydantic models can do. + Keep in mind that dataclasses can't do everything Pydantic models can do. So, you might still need to use Pydantic models. diff --git a/docs/en/docs/advanced/events.md b/docs/en/docs/advanced/events.md index 6b7de41309bbe..ca9d86ae41e99 100644 --- a/docs/en/docs/advanced/events.md +++ b/docs/en/docs/advanced/events.md @@ -92,7 +92,7 @@ The `lifespan` parameter of the `FastAPI` app takes an **async context manager** ## Alternative Events (deprecated) !!! warning - The recommended way to handle the *startup* and *shutdown* is using the `lifespan` parameter of the `FastAPI` app as described above. + The recommended way to handle the *startup* and *shutdown* is using the `lifespan` parameter of the `FastAPI` app as described above. If you provide a `lifespan` parameter, `startup` and `shutdown` event handlers will no longer be called. It's all `lifespan` or all events, not both. You can probably skip this part. @@ -159,4 +159,4 @@ Underneath, in the ASGI technical specification, this is part of the ../../../docs_src/generate_clients/tutorial004.py!} + ``` + +=== "Node.js" + + ```Python + {!> ../../../docs_src/generate_clients/tutorial004.js!} + ``` With that, the operation IDs would be renamed from things like `items-get_items` to just `get_items`, that way the client generator can generate simpler method names. diff --git a/docs/en/docs/advanced/openapi-callbacks.md b/docs/en/docs/advanced/openapi-callbacks.md index 37339eae575cf..03429b187fe55 100644 --- a/docs/en/docs/advanced/openapi-callbacks.md +++ b/docs/en/docs/advanced/openapi-callbacks.md @@ -38,7 +38,7 @@ This part is pretty normal, most of the code is probably already familiar to you !!! tip The `callback_url` query parameter uses a Pydantic URL type. -The only new thing is the `callbacks=messages_callback_router.routes` as an argument to the *path operation decorator*. We'll see what that is next. +The only new thing is the `callbacks=invoices_callback_router.routes` as an argument to the *path operation decorator*. We'll see what that is next. ## Documenting the callback diff --git a/docs/en/docs/advanced/path-operation-advanced-configuration.md b/docs/en/docs/advanced/path-operation-advanced-configuration.md index 7ca88d43ed277..8b79bfe22a213 100644 --- a/docs/en/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/en/docs/advanced/path-operation-advanced-configuration.md @@ -163,7 +163,7 @@ For example, in this application we don't use FastAPI's integrated functionality ``` !!! info - In Pydantic version 1 the method to get the JSON Schema for a model was called `Item.schema()`, in Pydantic version 2, the method is called `Item.model_schema_json()`. + In Pydantic version 1 the method to get the JSON Schema for a model was called `Item.schema()`, in Pydantic version 2, the method is called `Item.model_json_schema()`. Nevertheless, although we are not using the default integrated functionality, we are still using a Pydantic model to manually generate the JSON Schema for the data that we want to receive in YAML. diff --git a/docs/en/docs/advanced/response-change-status-code.md b/docs/en/docs/advanced/response-change-status-code.md index 979cef3f05367..b88d74a8af62e 100644 --- a/docs/en/docs/advanced/response-change-status-code.md +++ b/docs/en/docs/advanced/response-change-status-code.md @@ -30,4 +30,4 @@ And if you declared a `response_model`, it will still be used to filter and conv **FastAPI** will use that *temporal* response to extract the status code (also cookies and headers), and will put them in the final response that contains the value you returned, filtered by any `response_model`. -You can also declare the `Response` parameter in dependencies, and set the status code in them. But have in mind that the last one to be set will win. +You can also declare the `Response` parameter in dependencies, and set the status code in them. But keep in mind that the last one to be set will win. diff --git a/docs/en/docs/advanced/response-cookies.md b/docs/en/docs/advanced/response-cookies.md index 9178ef81621db..d53985dbba3f4 100644 --- a/docs/en/docs/advanced/response-cookies.md +++ b/docs/en/docs/advanced/response-cookies.md @@ -31,7 +31,7 @@ Then set Cookies in it, and then return it: ``` !!! tip - Have in mind that if you return a response directly instead of using the `Response` parameter, FastAPI will return it directly. + Keep in mind that if you return a response directly instead of using the `Response` parameter, FastAPI will return it directly. So, you will have to make sure your data is of the correct type. E.g. it is compatible with JSON, if you are returning a `JSONResponse`. diff --git a/docs/en/docs/advanced/response-headers.md b/docs/en/docs/advanced/response-headers.md index 758bd64556c85..49b5fe4766f3a 100644 --- a/docs/en/docs/advanced/response-headers.md +++ b/docs/en/docs/advanced/response-headers.md @@ -37,6 +37,6 @@ Create a response as described in [Return a Response Directly](response-directly ## Custom Headers -Have in mind that custom proprietary headers can be added using the 'X-' prefix. +Keep in mind that custom proprietary headers can be added using the 'X-' prefix. But if you have custom headers that you want a client in a browser to be able to see, you need to add them to your CORS configurations (read more in [CORS (Cross-Origin Resource Sharing)](../tutorial/cors.md){.internal-link target=_blank}), using the parameter `expose_headers` documented in Starlette's CORS docs. diff --git a/docs/en/docs/advanced/security/http-basic-auth.md b/docs/en/docs/advanced/security/http-basic-auth.md index 6f9002f608022..680f4dff53e6c 100644 --- a/docs/en/docs/advanced/security/http-basic-auth.md +++ b/docs/en/docs/advanced/security/http-basic-auth.md @@ -105,7 +105,7 @@ if "johndoe" == "stanleyjobson" and "love123" == "swordfish": ... ``` -But right at the moment Python compares the first `j` in `johndoe` to the first `s` in `stanleyjobson`, it will return `False`, because it already knows that those two strings are not the same, thinking that "there's no need to waste more computation comparing the rest of the letters". And your application will say "incorrect user or password". +But right at the moment Python compares the first `j` in `johndoe` to the first `s` in `stanleyjobson`, it will return `False`, because it already knows that those two strings are not the same, thinking that "there's no need to waste more computation comparing the rest of the letters". And your application will say "Incorrect username or password". But then the attackers try with username `stanleyjobsox` and password `love123`. @@ -116,11 +116,11 @@ if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish": ... ``` -Python will have to compare the whole `stanleyjobso` in both `stanleyjobsox` and `stanleyjobson` before realizing that both strings are not the same. So it will take some extra microseconds to reply back "incorrect user or password". +Python will have to compare the whole `stanleyjobso` in both `stanleyjobsox` and `stanleyjobson` before realizing that both strings are not the same. So it will take some extra microseconds to reply back "Incorrect username or password". #### The time to answer helps the attackers -At that point, by noticing that the server took some microseconds longer to send the "incorrect user or password" response, the attackers will know that they got _something_ right, some of the initial letters were right. +At that point, by noticing that the server took some microseconds longer to send the "Incorrect username or password" response, the attackers will know that they got _something_ right, some of the initial letters were right. And then they can try again knowing that it's probably something more similar to `stanleyjobsox` than to `johndoe`. diff --git a/docs/en/docs/advanced/security/oauth2-scopes.md b/docs/en/docs/advanced/security/oauth2-scopes.md index 304a46090e1d7..b93d2991c4dcb 100644 --- a/docs/en/docs/advanced/security/oauth2-scopes.md +++ b/docs/en/docs/advanced/security/oauth2-scopes.md @@ -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 152" + ```Python hl_lines="3 7 11 45 63 104 106-114 120-123 127-133 138 154" {!> ../../../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 153" + ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" {!> ../../../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 153" + ```Python hl_lines="2 4 8 12 46 64 105 107-115 121-124 128-134 139 155" {!> ../../../docs_src/security/tutorial005.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="152" + ```Python hl_lines="154" {!> ../../../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="153" + ```Python hl_lines="155" {!> ../../../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="153" + ```Python hl_lines="155" {!> ../../../docs_src/security/tutorial005.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 165" + ```Python hl_lines="3 138 167" {!> ../../../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 166" + ```Python hl_lines="4 139 168" {!> ../../../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 166" + ```Python hl_lines="4 139 168" {!> ../../../docs_src/security/tutorial005.py!} ``` diff --git a/docs/en/docs/advanced/templates.md b/docs/en/docs/advanced/templates.md index 38618aeeb09cd..6055b30170db6 100644 --- a/docs/en/docs/advanced/templates.md +++ b/docs/en/docs/advanced/templates.md @@ -25,14 +25,16 @@ $ pip install jinja2 * Import `Jinja2Templates`. * Create a `templates` object that you can re-use 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`, passing the `request` as one of the key-value pairs in the Jinja2 "context". +* Use the `templates` you created to render and return a `TemplateResponse`, pass the name of the template, the request object, and a "context" dictionary with key-value pairs to be used inside of the Jinja2 template. -```Python hl_lines="4 11 15-16" +```Python hl_lines="4 11 15-18" {!../../../docs_src/templates/tutorial001.py!} ``` !!! note - Notice that you have to pass the `request` as part of the key-value pairs in the context for Jinja2. So, you also have to declare it in your *path operation*. + Before FastAPI 0.108.0, Starlette 0.29.0, the `name` was the first parameter. + + Also, before that, in previous versions, the `request` object was passed as part of the key-value pairs in the context for Jinja2. !!! tip By declaring `response_class=HTMLResponse` the docs UI will be able to know that the response will be HTML. @@ -44,21 +46,61 @@ $ pip install jinja2 ## Writing templates -Then you can write a template at `templates/item.html` with: +Then you can write a template at `templates/item.html` with, for example: ```jinja hl_lines="7" {!../../../docs_src/templates/templates/item.html!} ``` -It will show the `id` taken from the "context" `dict` you passed: +### Template Context Values + +In the HTML that contains: + +{% raw %} + +```jinja +Item ID: {{ id }} +``` + +{% endraw %} + +...it will show the `id` taken from the "context" `dict` you passed: ```Python -{"request": request, "id": id} +{"id": id} +``` + +For example, with an ID of `42`, this would render: + +```html +Item ID: 42 +``` + +### Template `url_for` Arguments + +You can also use `url_for()` inside of the template, it takes as arguments the same arguments that would be used by your *path operation function*. + +So, the section with: + +{% raw %} + +```jinja + +``` + +{% endraw %} + +...will generate a link to the same URL that would be handled by the *path operation function* `read_item(id=id)`. + +For example, with an ID of `42`, this would render: + +```html + ``` ## Templates and static files -And you can also use `url_for()` inside of the template, and use it, for example, with the `StaticFiles` you mounted. +You can also use `url_for()` inside of the template, and use it, for example, with the `StaticFiles` you mounted with the `name="static"`. ```jinja hl_lines="4" {!../../../docs_src/templates/templates/item.html!} diff --git a/docs/en/docs/advanced/websockets.md b/docs/en/docs/advanced/websockets.md index 49b8fba899015..b8dfab1d1f69f 100644 --- a/docs/en/docs/advanced/websockets.md +++ b/docs/en/docs/advanced/websockets.md @@ -212,7 +212,7 @@ Client #1596980209979 left the chat !!! tip The app above is a minimal and simple example to demonstrate how to handle and broadcast messages to several WebSocket connections. - But have in mind that, as everything is handled in memory, in a single list, it will only work while the process is running, and will only work with a single process. + But keep in mind that, as everything is handled in memory, in a single list, it will only work while the process is running, and will only work with a single process. If you need something easy to integrate with FastAPI but that is more robust, supported by Redis, PostgreSQL or others, check encode/broadcaster. diff --git a/docs/en/docs/alternatives.md b/docs/en/docs/alternatives.md index 0f074ccf32dcc..70bbcac91c3cb 100644 --- a/docs/en/docs/alternatives.md +++ b/docs/en/docs/alternatives.md @@ -185,13 +185,13 @@ It's a Flask plug-in, that ties together Webargs, Marshmallow and APISpec. It uses the information from Webargs and Marshmallow to automatically generate OpenAPI schemas, using APISpec. -It's a great tool, very under-rated. It should be way more popular than many Flask plug-ins out there. It might be due to its documentation being too concise and abstract. +It's a great tool, very underrated. It should be way more popular than many Flask plug-ins out there. It might be due to its documentation being too concise and abstract. This solved having to write YAML (another syntax) inside of Python docstrings. This combination of Flask, Flask-apispec with Marshmallow and Webargs was my favorite backend stack until building **FastAPI**. -Using it led to the creation of several Flask full-stack generators. These are the main stack I (and several external teams) have been using up to now: +Using it led to the creation of several Flask full-stack generators. These are the main stacks I (and several external teams) have been using up to now: * https://github.com/tiangolo/full-stack * https://github.com/tiangolo/full-stack-flask-couchbase @@ -211,7 +211,7 @@ This isn't even Python, NestJS is a JavaScript (TypeScript) NodeJS framework ins It achieves something somewhat similar to what can be done with Flask-apispec. -It has an integrated dependency injection system, inspired by Angular two. It requires pre-registering the "injectables" (like all the other dependency injection systems I know), so, it adds to the verbosity and code repetition. +It has an integrated dependency injection system, inspired by Angular 2. It requires pre-registering the "injectables" (like all the other dependency injection systems I know), so, it adds to the verbosity and code repetition. As the parameters are described with TypeScript types (similar to Python type hints), editor support is quite good. @@ -263,7 +263,7 @@ I discovered Molten in the first stages of building **FastAPI**. And it has quit It doesn't use a data validation, serialization and documentation third-party library like Pydantic, it has its own. So, these data type definitions would not be reusable as easily. -It requires a little bit more verbose configurations. And as it is based on WSGI (instead of ASGI), it is not designed to take advantage of the high-performance provided by tools like Uvicorn, Starlette and Sanic. +It requires a little bit more verbose configurations. And as it is based on WSGI (instead of ASGI), it is not designed to take advantage of the high performance provided by tools like Uvicorn, Starlette and Sanic. The dependency injection system requires pre-registration of the dependencies and the dependencies are solved based on the declared types. So, it's not possible to declare more than one "component" that provides a certain type. @@ -357,7 +357,7 @@ It is comparable to Marshmallow. Although it's faster than Marshmallow in benchm ### Starlette -Starlette is a lightweight ASGI framework/toolkit, which is ideal for building high-performance asyncio services. +Starlette is a lightweight ASGI framework/toolkit, which is ideal for building high-performance asyncio services. It is very simple and intuitive. It's designed to be easily extensible, and have modular components. diff --git a/docs/en/docs/benchmarks.md b/docs/en/docs/benchmarks.md index e05fec8406621..d746b6d7c4e24 100644 --- a/docs/en/docs/benchmarks.md +++ b/docs/en/docs/benchmarks.md @@ -2,7 +2,7 @@ Independent TechEmpower benchmarks show **FastAPI** applications running under Uvicorn as one of the fastest Python frameworks available, only below Starlette and Uvicorn themselves (used internally by FastAPI). (*) -But when checking benchmarks and comparisons you should have the following in mind. +But when checking benchmarks and comparisons you should keep the following in mind. ## Benchmarks and speed diff --git a/docs/en/docs/contributing.md b/docs/en/docs/contributing.md index cfdb607d772e0..2d308a9dbd801 100644 --- a/docs/en/docs/contributing.md +++ b/docs/en/docs/contributing.md @@ -4,11 +4,11 @@ First, you might want to see the basic ways to [help FastAPI and get help](help- ## Developing -If you already cloned the repository and you know that you need to deep dive in the code, here are some guidelines to set up your environment. +If you already cloned the fastapi repository and you want to deep dive in the code, here are some guidelines to set up your environment. ### Virtual environment with `venv` -You can create a virtual environment in a directory using Python's `venv` module: +You can create an isolated virtual local environment in a directory using Python's `venv` module. Let's do this in the cloned repository (where the `requirements.txt` is):
@@ -18,7 +18,7 @@ $ python -m venv env
-That will create a directory `./env/` with the Python binaries and then you will be able to install packages for that isolated environment. +That will create a directory `./env/` with the Python binaries, and then you will be able to install packages for that local environment. ### Activate the environment @@ -84,7 +84,7 @@ To check it worked, use: If it shows the `pip` binary at `env/bin/pip` then it worked. 🎉 -Make sure you have the latest pip version on your virtual environment to avoid errors on the next steps: +Make sure you have the latest pip version on your local environment to avoid errors on the next steps:
@@ -101,7 +101,7 @@ $ python -m pip install --upgrade pip This makes sure that if you use a terminal program installed by that package, you use the one from your local environment and not any other that could be installed globally. -### pip +### Install requirements using pip After activating the environment as described above: @@ -117,20 +117,20 @@ $ pip install -r requirements.txt It will install all the dependencies and your local FastAPI in your local environment. -#### Using your local FastAPI +### Using your local FastAPI -If you create a Python file that imports and uses FastAPI, and run it with the Python from your local environment, it will use your local FastAPI source code. +If you create a Python file that imports and uses FastAPI, and run it with the Python from your local environment, it will use your cloned local FastAPI source code. And if you update that local FastAPI source code when you run that Python file again, it will use the fresh version of FastAPI you just edited. That way, you don't have to "install" your local version to be able to test every change. !!! note "Technical Details" - This only happens when you install using this included `requirements.txt` instead of installing `pip install fastapi` directly. + This only happens when you install using this included `requirements.txt` instead of running `pip install fastapi` directly. - That is because inside of the `requirements.txt` file, the local version of FastAPI is marked to be installed in "editable" mode, with the `-e` option. + That is because inside the `requirements.txt` file, the local version of FastAPI is marked to be installed in "editable" mode, with the `-e` option. -### Format +### Format the code There is a script that you can run that will format and clean all your code: @@ -150,32 +150,7 @@ For it to sort them correctly, you need to have FastAPI installed locally in you First, make sure you set up your environment as described above, that will install all the requirements. -The documentation uses MkDocs. - -And there are extra tools/scripts in place to handle translations in `./scripts/docs.py`. - -!!! tip - You don't need to see the code in `./scripts/docs.py`, you just use it in the command line. - -All the documentation is in Markdown format in the directory `./docs/en/`. - -Many of the tutorials have blocks of code. - -In most of the cases, these blocks of code are actual complete applications that can be run as is. - -In fact, those blocks of code are not written inside the Markdown, they are Python files in the `./docs_src/` directory. - -And those Python files are included/injected in the documentation when generating the site. - -### Docs for tests - -Most of the tests actually run against the example source files in the documentation. - -This helps making sure that: - -* The documentation is up to date. -* The documentation examples can be run as is. -* Most of the features are covered by the documentation, ensured by test coverage. +### Docs live During local development, there is a script that builds the site and checks for any changes, live-reloading: @@ -229,7 +204,36 @@ Completion will take effect once you restart the terminal.
-### Apps and docs at the same time +### Docs Structure + +The documentation uses MkDocs. + +And there are extra tools/scripts in place to handle translations in `./scripts/docs.py`. + +!!! tip + You don't need to see the code in `./scripts/docs.py`, you just use it in the command line. + +All the documentation is in Markdown format in the directory `./docs/en/`. + +Many of the tutorials have blocks of code. + +In most of the cases, these blocks of code are actual complete applications that can be run as is. + +In fact, those blocks of code are not written inside the Markdown, they are Python files in the `./docs_src/` directory. + +And those Python files are included/injected in the documentation when generating the site. + +### Docs for tests + +Most of the tests actually run against the example source files in the documentation. + +This helps to make sure that: + +* The documentation is up-to-date. +* The documentation examples can be run as is. +* Most of the features are covered by the documentation, ensured by test coverage. + +#### Apps and docs at the same time If you run the examples with, e.g.: @@ -253,7 +257,9 @@ Here are the steps to help with translations. #### Tips and guidelines -* Check the currently existing pull requests for your language and add reviews requesting changes or approving them. +* Check the currently existing pull requests for your language. You can filter the pull requests by the ones with the label for your language. For example, for Spanish, the label is `lang-es`. + +* Review those pull requests, requesting changes or approving them. For the languages I don't speak, I'll wait for several others to review the translation before merging. !!! tip You can add comments with change suggestions to existing pull requests. @@ -262,19 +268,9 @@ Here are the steps to help with translations. * Check if there's a GitHub Discussion to coordinate translations for your language. You can subscribe to it, and when there's a new pull request to review, an automatic comment will be added to the discussion. -* Add a single pull request per page translated. That will make it much easier for others to review it. - -For the languages I don't speak, I'll wait for several others to review the translation before merging. +* If you translate pages, add a single pull request per page translated. That will make it much easier for others to review it. -* You can also check if there are translations for your language and add a review to them, that will help me know that the translation is correct and I can merge it. - * You could check in the GitHub Discussions for your language. - * Or you can filter the existing PRs by the ones with the label for your language, for example, for Spanish, the label is `lang-es`. - -* Use the same Python examples and only translate the text in the docs. You don't have to change anything for this to work. - -* Use the same images, file names, and links. You don't have to change anything for it to work. - -* To check the 2-letter code for the language you want to translate you can use the table List of ISO 639-1 codes. +* To check the 2-letter code for the language you want to translate, you can use the table List of ISO 639-1 codes. #### Existing language @@ -317,7 +313,7 @@ $ python ./scripts/docs.py live es Now you can go to http://127.0.0.1:8008 and see your changes live. -You will see that every language has all the pages. But some pages are not translated and have a notification about the missing translation. +You will see that every language has all the pages. But some pages are not translated and have an info box at the top, about the missing translation. Now let's say that you want to add a translation for the section [Features](features.md){.internal-link target=_blank}. @@ -336,7 +332,7 @@ docs/es/docs/features.md !!! tip Notice that the only change in the path and file name is the language code, from `en` to `es`. -If you go to your browser you will see that now the docs show your new section. 🎉 +If you go to your browser you will see that now the docs show your new section (the info box at the top is gone). 🎉 Now you can translate it all and see how it looks as you save the file. @@ -380,7 +376,7 @@ You can make the first pull request with those two files, `docs/ht/mkdocs.yml` a #### Preview the result -You can use the `./scripts/docs.py` with the `live` command to preview the results (or `mkdocs serve`). +As already mentioned above, you can use the `./scripts/docs.py` with the `live` command to preview the results (or `mkdocs serve`). Once you are done, you can also test it all as it would look online, including all the other languages. @@ -417,6 +413,25 @@ Serving at: http://127.0.0.1:8008 +#### Translation specific tips and guidelines + +* Translate only the Markdown documents (`.md`). Do not translate the code examples at `./docs_src`. + +* In code blocks within the Markdown document, translate comments (`# a comment`), but leave the rest unchanged. + +* Do not change anything enclosed in "``" (inline code). + +* In lines starting with `===` or `!!!`, translate only the ` "... Text ..."` part. Leave the rest unchanged. + +* You can translate info boxes like `!!! warning` with for example `!!! warning "Achtung"`. But do not change the word immediately after the `!!!`, it determines the color of the info box. + +* Do not change the paths in links to images, code files, Markdown documents. + +* However, when a Markdown document is translated, the `#hash-parts` in links to its headings may change. Update these links if possible. + * Search for such links in the translated document using the regex `#[^# ]`. + * Search in all documents already translated into your language for `your-translated-document.md`. For example VS Code has an option "Edit" -> "Find in Files". + * When translating a document, do not "pre-translate" `#hash-parts` that link to headings in untranslated documents. + ## Tests There is a script that you can run locally to test all the code and generate coverage reports in HTML: diff --git a/docs/en/docs/deployment/concepts.md b/docs/en/docs/deployment/concepts.md index 77419f8b0dfd9..cc01fb24e1584 100644 --- a/docs/en/docs/deployment/concepts.md +++ b/docs/en/docs/deployment/concepts.md @@ -258,7 +258,7 @@ And you will have to make sure that it's a single process running those previous Of course, there are some cases where there's no problem in running the previous steps multiple times, in that case, it's a lot easier to handle. !!! tip - Also, have in mind that depending on your setup, in some cases you **might not even need any previous steps** before starting your application. + Also, keep in mind that depending on your setup, in some cases you **might not even need any previous steps** before starting your application. In that case, you wouldn't have to worry about any of this. 🤷 @@ -297,7 +297,7 @@ You can use simple tools like `htop` to see the CPU and RAM used in your server ## Recap -You have been reading here some of the main concepts that you would probably need to have in mind when deciding how to deploy your application: +You have been reading here some of the main concepts that you would probably need to keep in mind when deciding how to deploy your application: * Security - HTTPS * Running on startup diff --git a/docs/en/docs/deployment/https.md b/docs/en/docs/deployment/https.md index 790976a718f78..5cf76c1111d6e 100644 --- a/docs/en/docs/deployment/https.md +++ b/docs/en/docs/deployment/https.md @@ -9,7 +9,7 @@ But it is way more complex than that. To **learn the basics of HTTPS**, from a consumer perspective, check https://howhttps.works/. -Now, from a **developer's perspective**, here are several things to have in mind while thinking about HTTPS: +Now, from a **developer's perspective**, here are several things to keep in mind while thinking about HTTPS: * For HTTPS, **the server** needs to **have "certificates"** generated by a **third party**. * Those certificates are actually **acquired** from the third party, not "generated". diff --git a/docs/en/docs/deployment/index.md b/docs/en/docs/deployment/index.md index 6c43d8abbe4db..b43bd050a37ab 100644 --- a/docs/en/docs/deployment/index.md +++ b/docs/en/docs/deployment/index.md @@ -16,6 +16,6 @@ There are several ways to do it depending on your specific use case and the tool You could **deploy a server** yourself using a combination of tools, you could use a **cloud service** that does part of the work for you, or other possible options. -I will show you some of the main concepts you should probably have in mind when deploying a **FastAPI** application (although most of it applies to any other type of web application). +I will show you some of the main concepts you should probably keep in mind when deploying a **FastAPI** application (although most of it applies to any other type of web application). -You will see more details to have in mind and some of the techniques to do it in the next sections. ✨ +You will see more details to keep in mind and some of the techniques to do it in the next sections. ✨ diff --git a/docs/en/docs/deployment/manually.md b/docs/en/docs/deployment/manually.md index d6892b2c14ad6..b10a3686d7565 100644 --- a/docs/en/docs/deployment/manually.md +++ b/docs/en/docs/deployment/manually.md @@ -10,11 +10,11 @@ There are 3 main alternatives: ## Server Machine and Server Program -There's a small detail about names to have in mind. 💡 +There's a small detail about names to keep in mind. 💡 The word "**server**" is commonly used to refer to both the remote/cloud computer (the physical or virtual machine) and also the program that is running on that machine (e.g. Uvicorn). -Just have that in mind when you read "server" in general, it could refer to one of those two things. +Just keep in mind that when you read "server" in general, it could refer to one of those two things. When referring to the remote machine, it's common to call it **server**, but also **machine**, **VM** (virtual machine), **node**. Those all refer to some type of remote machine, normally running Linux, where you run programs. diff --git a/docs/en/docs/help-fastapi.md b/docs/en/docs/help-fastapi.md index 8199c9b9a9b1b..71c580409708c 100644 --- a/docs/en/docs/help-fastapi.md +++ b/docs/en/docs/help-fastapi.md @@ -106,7 +106,7 @@ In many cases they will only copy a fragment of the code, but that's not enough * You can ask them to provide a minimal, reproducible, example, that you can **copy-paste** and run locally to see the same error or behavior they are seeing, or to understand their use case better. -* If you are feeling too generous, you can try to **create an example** like that yourself, just based on the description of the problem. Just have in mind that this might take a lot of time and it might be better to ask them to clarify the problem first. +* If you are feeling too generous, you can try to **create an example** like that yourself, just based on the description of the problem. Just keep in mind that this might take a lot of time and it might be better to ask them to clarify the problem first. ### Suggest solutions @@ -148,7 +148,7 @@ Again, please try your best to be kind. 🤗 --- -Here's what to have in mind and how to review a pull request: +Here's what to keep in mind and how to review a pull request: ### Understand the problem @@ -233,7 +233,7 @@ Join the 👥 `contextvars` that can create a local variable very similar to `threading.local`, but also supporting these async features. -There are several things to have in mind. +There are several things to keep in mind. The `ContextVar` has to be created at the top of the module, like: diff --git a/docs/en/docs/reference/exceptions.md b/docs/en/docs/reference/exceptions.md index adc9b91ce5659..7c480834928f9 100644 --- a/docs/en/docs/reference/exceptions.md +++ b/docs/en/docs/reference/exceptions.md @@ -3,7 +3,7 @@ These are the exceptions that you can raise to show errors to the client. When you raise an exception, as would happen with normal Python, the rest of the -excecution is aborted. This way you can raise these exceptions from anywhere in the +execution is aborted. This way you can raise these exceptions from anywhere in the code to abort a request and show the error to the client. You can use: diff --git a/docs/en/docs/reference/status.md b/docs/en/docs/reference/status.md index 54fba9387e664..a238007923be8 100644 --- a/docs/en/docs/reference/status.md +++ b/docs/en/docs/reference/status.md @@ -8,7 +8,7 @@ from fastapi import status `status` is provided directly by Starlette. -It containes a group of named constants (variables) with integer status codes. +It contains a group of named constants (variables) with integer status codes. For example: diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 835df984ce4c1..a23d367e97e21 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,270 @@ hide: ## Latest Changes +* ✏️ Fix Pydantic method name in `docs/en/docs/advanced/path-operation-advanced-configuration.md`. PR [#10826](https://github.com/tiangolo/fastapi/pull/10826) by [@ahmedabdou14](https://github.com/ahmedabdou14). + +### Features + +* ✨ Include HTTP 205 in status codes with no body. PR [#10969](https://github.com/tiangolo/fastapi/pull/10969) by [@tiangolo](https://github.com/tiangolo). + +### Refactors + +* ✅ Refactor tests for duplicate operation ID generation for compatibility with other tools running the FastAPI test suite. PR [#10876](https://github.com/tiangolo/fastapi/pull/10876) by [@emmettbutler](https://github.com/emmettbutler). +* ♻️ Simplify string format with f-strings in `fastapi/utils.py`. PR [#10576](https://github.com/tiangolo/fastapi/pull/10576) by [@eukub](https://github.com/eukub). +* 🔧 Fix Ruff configuration unintentionally enabling and re-disabling mccabe complexity check. PR [#10893](https://github.com/tiangolo/fastapi/pull/10893) by [@jiridanek](https://github.com/jiridanek). +* ✅ Re-enable test in `tests/test_tutorial/test_header_params/test_tutorial003.py` after fix in Starlette. PR [#10904](https://github.com/tiangolo/fastapi/pull/10904) by [@ooknimm](https://github.com/ooknimm). + +### Docs + +* 📝 Update `HTTPException` details in `docs/en/docs/tutorial/handling-errors.md`. PR [#5418](https://github.com/tiangolo/fastapi/pull/5418) by [@papb](https://github.com/papb). +* ✏️ A few tweaks in `docs/de/docs/tutorial/first-steps.md`. PR [#10959](https://github.com/tiangolo/fastapi/pull/10959) by [@nilslindemann](https://github.com/nilslindemann). +* ✏️ Fix link in `docs/en/docs/advanced/async-tests.md`. PR [#10960](https://github.com/tiangolo/fastapi/pull/10960) by [@nilslindemann](https://github.com/nilslindemann). +* ✏️ Fix typos for Spanish documentation. PR [#10957](https://github.com/tiangolo/fastapi/pull/10957) by [@jlopezlira](https://github.com/jlopezlira). +* 📝 Add warning about lifespan functions and backwards compatibility with events. PR [#10734](https://github.com/tiangolo/fastapi/pull/10734) by [@jacob-indigo](https://github.com/jacob-indigo). +* ✏️ Fix broken link in `docs/tutorial/sql-databases.md` in several languages. PR [#10716](https://github.com/tiangolo/fastapi/pull/10716) by [@theoohoho](https://github.com/theoohoho). +* ✏️ Remove broken links from `external_links.yml`. PR [#10943](https://github.com/tiangolo/fastapi/pull/10943) by [@Torabek](https://github.com/Torabek). +* 📝 Update template docs with more info about `url_for`. PR [#5937](https://github.com/tiangolo/fastapi/pull/5937) by [@EzzEddin](https://github.com/EzzEddin). +* 📝 Update usage of Token model in security docs. PR [#9313](https://github.com/tiangolo/fastapi/pull/9313) by [@piotrszacilowski](https://github.com/piotrszacilowski). +* ✏️ Update highlighted line in `docs/en/docs/tutorial/bigger-applications.md`. PR [#5490](https://github.com/tiangolo/fastapi/pull/5490) by [@papb](https://github.com/papb). +* 📝 Add External Link: Explore How to Effectively Use JWT With FastAPI. PR [#10212](https://github.com/tiangolo/fastapi/pull/10212) by [@aanchlia](https://github.com/aanchlia). +* 📝 Add hyperlink to `docs/en/docs/tutorial/static-files.md`. PR [#10243](https://github.com/tiangolo/fastapi/pull/10243) by [@hungtsetse](https://github.com/hungtsetse). +* 📝 Add External Link: Instrument a FastAPI service adding tracing with OpenTelemetry and send/show traces in Grafana Tempo. PR [#9440](https://github.com/tiangolo/fastapi/pull/9440) by [@softwarebloat](https://github.com/softwarebloat). +* 📝 Review and rewording of `en/docs/contributing.md`. PR [#10480](https://github.com/tiangolo/fastapi/pull/10480) by [@nilslindemann](https://github.com/nilslindemann). +* 📝 Add External Link: ML serving and monitoring with FastAPI and Evidently. PR [#9701](https://github.com/tiangolo/fastapi/pull/9701) by [@mnrozhkov](https://github.com/mnrozhkov). +* 📝 Reword in docs, from "have in mind" to "keep in mind". PR [#10376](https://github.com/tiangolo/fastapi/pull/10376) by [@malicious](https://github.com/malicious). +* 📝 Add External Link: Talk by Jeny Sadadia. PR [#10265](https://github.com/tiangolo/fastapi/pull/10265) by [@JenySadadia](https://github.com/JenySadadia). +* 📝 Add location info to `tutorial/bigger-applications.md`. PR [#10552](https://github.com/tiangolo/fastapi/pull/10552) by [@nilslindemann](https://github.com/nilslindemann). + +### Translations + +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/response-model.md`. PR [#1938](https://github.com/tiangolo/fastapi/pull/1938) by [@SwftAlpc](https://github.com/SwftAlpc). +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/body-multiple-params.md`. PR [#1903](https://github.com/tiangolo/fastapi/pull/1903) by [@SwftAlpc](https://github.com/SwftAlpc). +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/path-params-numeric-validations.md`. PR [#1902](https://github.com/tiangolo/fastapi/pull/1902) by [@SwftAlpc](https://github.com/SwftAlpc). +* 🌐 Add Japanese translation for `docs/ja/docs/python-types.md`. PR [#1899](https://github.com/tiangolo/fastapi/pull/1899) by [@SwftAlpc](https://github.com/SwftAlpc). +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/handling-errors.md`. PR [#1953](https://github.com/tiangolo/fastapi/pull/1953) by [@SwftAlpc](https://github.com/SwftAlpc). +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/response-status-code.md`. PR [#1942](https://github.com/tiangolo/fastapi/pull/1942) by [@SwftAlpc](https://github.com/SwftAlpc). +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/extra-models.md`. PR [#1941](https://github.com/tiangolo/fastapi/pull/1941) by [@SwftAlpc](https://github.com/SwftAlpc). +* 🌐 Add Japanese tranlsation for `docs/ja/docs/tutorial/schema-extra-example.md`. PR [#1931](https://github.com/tiangolo/fastapi/pull/1931) by [@SwftAlpc](https://github.com/SwftAlpc). +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/body-nested-models.md`. PR [#1930](https://github.com/tiangolo/fastapi/pull/1930) by [@SwftAlpc](https://github.com/SwftAlpc). +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/body-fields.md`. PR [#1923](https://github.com/tiangolo/fastapi/pull/1923) by [@SwftAlpc](https://github.com/SwftAlpc). +* 🌐 Add German translation for `docs/de/docs/tutorial/index.md`. PR [#9502](https://github.com/tiangolo/fastapi/pull/9502) by [@fhabers21](https://github.com/fhabers21). +* 🌐 Add German translation for `docs/de/docs/tutorial/background-tasks.md`. PR [#10566](https://github.com/tiangolo/fastapi/pull/10566) by [@nilslindemann](https://github.com/nilslindemann). +* ✏️ Fix typo in `docs/ru/docs/index.md`. PR [#10672](https://github.com/tiangolo/fastapi/pull/10672) by [@Delitel-WEB](https://github.com/Delitel-WEB). +* ✏️ Fix typos in `docs/zh/docs/tutorial/extra-data-types.md`. PR [#10727](https://github.com/tiangolo/fastapi/pull/10727) by [@HiemalBeryl](https://github.com/HiemalBeryl). +* 🌐 Add Russian translation for `docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md`. PR [#10410](https://github.com/tiangolo/fastapi/pull/10410) by [@AlertRED](https://github.com/AlertRED). + +### Internal + +* 👷 Add changes-requested handling in GitHub Action issue manager. PR [#10971](https://github.com/tiangolo/fastapi/pull/10971) by [@tiangolo](https://github.com/tiangolo). +* 🔧 Group dependencies on dependabot updates. PR [#10952](https://github.com/tiangolo/fastapi/pull/10952) by [@Kludex](https://github.com/Kludex). +* ⬆ Bump actions/setup-python from 4 to 5. PR [#10764](https://github.com/tiangolo/fastapi/pull/10764) by [@dependabot[bot]](https://github.com/apps/dependabot). +* ⬆ Bump pypa/gh-action-pypi-publish from 1.8.10 to 1.8.11. PR [#10731](https://github.com/tiangolo/fastapi/pull/10731) by [@dependabot[bot]](https://github.com/apps/dependabot). +* ⬆ Bump dawidd6/action-download-artifact from 2.28.0 to 3.0.0. PR [#10777](https://github.com/tiangolo/fastapi/pull/10777) by [@dependabot[bot]](https://github.com/apps/dependabot). +* 🔧 Add support for translations to languages with a longer code name, like `zh-hant`. PR [#10950](https://github.com/tiangolo/fastapi/pull/10950) by [@tiangolo](https://github.com/tiangolo). + +## 0.109.0 + +### Features + +* ✨ Add support for Python 3.12. PR [#10666](https://github.com/tiangolo/fastapi/pull/10666) by [@Jamim](https://github.com/Jamim). + +### Upgrades + +* ⬆️ Upgrade Starlette to >=0.35.0,<0.36.0. PR [#10938](https://github.com/tiangolo/fastapi/pull/10938) by [@tiangolo](https://github.com/tiangolo). + +### Docs + +* ✏️ Fix typo in `docs/en/docs/alternatives.md`. PR [#10931](https://github.com/tiangolo/fastapi/pull/10931) by [@s111d](https://github.com/s111d). +* 📝 Replace `email` with `username` in `docs_src/security/tutorial007` code examples. PR [#10649](https://github.com/tiangolo/fastapi/pull/10649) by [@nilslindemann](https://github.com/nilslindemann). +* 📝 Add VS Code tutorial link. PR [#10592](https://github.com/tiangolo/fastapi/pull/10592) by [@nilslindemann](https://github.com/nilslindemann). +* 📝 Add notes about Pydantic v2's new `.model_dump()`. PR [#10929](https://github.com/tiangolo/fastapi/pull/10929) by [@tiangolo](https://github.com/tiangolo). +* 📝 Fix broken link in `docs/en/docs/tutorial/sql-databases.md`. PR [#10765](https://github.com/tiangolo/fastapi/pull/10765) by [@HurSungYun](https://github.com/HurSungYun). +* 📝 Add External Link: FastAPI application monitoring made easy. PR [#10917](https://github.com/tiangolo/fastapi/pull/10917) by [@tiangolo](https://github.com/tiangolo). +* ✨ Generate automatic language names for docs translations. PR [#5354](https://github.com/tiangolo/fastapi/pull/5354) by [@jakul](https://github.com/jakul). +* ✏️ Fix typos in `docs/en/docs/alternatives.md` and `docs/en/docs/tutorial/dependencies/index.md`. PR [#10906](https://github.com/tiangolo/fastapi/pull/10906) by [@s111d](https://github.com/s111d). +* ✏️ Fix typos in `docs/en/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#10834](https://github.com/tiangolo/fastapi/pull/10834) by [@Molkree](https://github.com/Molkree). +* 📝 Add article: "Building a RESTful API with FastAPI: Secure Signup and Login Functionality Included". PR [#9733](https://github.com/tiangolo/fastapi/pull/9733) by [@dxphilo](https://github.com/dxphilo). +* 📝 Add warning about lifecycle events with `AsyncClient`. PR [#4167](https://github.com/tiangolo/fastapi/pull/4167) by [@andrew-chang-dewitt](https://github.com/andrew-chang-dewitt). +* ✏️ Fix typos in `/docs/reference/exceptions.md` and `/en/docs/reference/status.md`. PR [#10809](https://github.com/tiangolo/fastapi/pull/10809) by [@clarencepenz](https://github.com/clarencepenz). +* ✏️ Fix typo in `openapi-callbacks.md`. PR [#10673](https://github.com/tiangolo/fastapi/pull/10673) by [@kayjan](https://github.com/kayjan). +* ✏️ Fix typo in `fastapi/routing.py` . PR [#10520](https://github.com/tiangolo/fastapi/pull/10520) by [@sepsh](https://github.com/sepsh). +* 📝 Replace HTTP code returned in case of existing user error in docs for testing. PR [#4482](https://github.com/tiangolo/fastapi/pull/4482) by [@TristanMarion](https://github.com/TristanMarion). +* 📝 Add blog for FastAPI & Supabase. PR [#6018](https://github.com/tiangolo/fastapi/pull/6018) by [@theinfosecguy](https://github.com/theinfosecguy). +* 📝 Update example source files for SQL databases with SQLAlchemy. PR [#9508](https://github.com/tiangolo/fastapi/pull/9508) by [@s-mustafa](https://github.com/s-mustafa). +* 📝 Update code examples in docs for body, replace name `create_item` with `update_item` when appropriate. PR [#5913](https://github.com/tiangolo/fastapi/pull/5913) by [@OttoAndrey](https://github.com/OttoAndrey). +* ✏️ Fix typo in dependencies with yield source examples. PR [#10847](https://github.com/tiangolo/fastapi/pull/10847) by [@tiangolo](https://github.com/tiangolo). + +### Translations + +* 🌐 Add Bengali translation for `docs/bn/docs/index.md`. PR [#9177](https://github.com/tiangolo/fastapi/pull/9177) by [@Fahad-Md-Kamal](https://github.com/Fahad-Md-Kamal). +* ✏️ Update Python version in `index.md` in several languages. PR [#10711](https://github.com/tiangolo/fastapi/pull/10711) by [@tamago3keran](https://github.com/tamago3keran). +* 🌐 Add Russian translation for `docs/ru/docs/tutorial/request-forms-and-files.md`. PR [#10347](https://github.com/tiangolo/fastapi/pull/10347) by [@AlertRED](https://github.com/AlertRED). +* 🌐 Add Ukrainian translation for `docs/uk/docs/index.md`. PR [#10362](https://github.com/tiangolo/fastapi/pull/10362) by [@rostik1410](https://github.com/rostik1410). +* ✏️ Update Python version in `docs/ko/docs/index.md`. PR [#10680](https://github.com/tiangolo/fastapi/pull/10680) by [@Eeap](https://github.com/Eeap). +* 🌐 Add Persian translation for `docs/fa/docs/features.md`. PR [#5887](https://github.com/tiangolo/fastapi/pull/5887) by [@amirilf](https://github.com/amirilf). +* 🌐 Add Chinese translation for `docs/zh/docs/advanced/additional-responses.md`. PR [#10325](https://github.com/tiangolo/fastapi/pull/10325) by [@ShuibeiC](https://github.com/ShuibeiC). +* 🌐 Fix typos in Russian translations for `docs/ru/docs/tutorial/background-tasks.md`, `docs/ru/docs/tutorial/body-nested-models.md`, `docs/ru/docs/tutorial/debugging.md`, `docs/ru/docs/tutorial/testing.md`. PR [#10311](https://github.com/tiangolo/fastapi/pull/10311) by [@AlertRED](https://github.com/AlertRED). +* 🌐 Add Russian translation for `docs/ru/docs/tutorial/request-files.md`. PR [#10332](https://github.com/tiangolo/fastapi/pull/10332) by [@AlertRED](https://github.com/AlertRED). +* 🌐 Add Chinese translation for `docs/zh/docs/deployment/server-workers.md`. PR [#10292](https://github.com/tiangolo/fastapi/pull/10292) by [@xzmeng](https://github.com/xzmeng). +* 🌐 Add Chinese translation for `docs/zh/docs/deployment/cloud.md`. PR [#10291](https://github.com/tiangolo/fastapi/pull/10291) by [@xzmeng](https://github.com/xzmeng). +* 🌐 Add Chinese translation for `docs/zh/docs/deployment/manually.md`. PR [#10279](https://github.com/tiangolo/fastapi/pull/10279) by [@xzmeng](https://github.com/xzmeng). +* 🌐 Add Chinese translation for `docs/zh/docs/deployment/https.md`. PR [#10277](https://github.com/tiangolo/fastapi/pull/10277) by [@xzmeng](https://github.com/xzmeng). +* 🌐 Add Chinese translation for `docs/zh/docs/deployment/index.md`. PR [#10275](https://github.com/tiangolo/fastapi/pull/10275) by [@xzmeng](https://github.com/xzmeng). +* 🌐 Add German translation for `docs/de/docs/tutorial/first-steps.md`. PR [#9530](https://github.com/tiangolo/fastapi/pull/9530) by [@fhabers21](https://github.com/fhabers21). +* 🌐 Update Turkish translation for `docs/tr/docs/index.md`. PR [#10444](https://github.com/tiangolo/fastapi/pull/10444) by [@hasansezertasan](https://github.com/hasansezertasan). +* 🌐 Add Chinese translation for `docs/zh/docs/learn/index.md`. PR [#10479](https://github.com/tiangolo/fastapi/pull/10479) by [@KAZAMA-DREAM](https://github.com/KAZAMA-DREAM). +* 🌐 Add Russian translation for `docs/ru/docs/learn/index.md`. PR [#10539](https://github.com/tiangolo/fastapi/pull/10539) by [@AlertRED](https://github.com/AlertRED). +* 🌐 Update SQLAlchemy instruction in Chinese translation `docs/zh/docs/tutorial/sql-databases.md`. PR [#9712](https://github.com/tiangolo/fastapi/pull/9712) by [@Royc30ne](https://github.com/Royc30ne). +* 🌐 Add Turkish translation for `docs/tr/docs/external-links.md`. PR [#10549](https://github.com/tiangolo/fastapi/pull/10549) by [@hasansezertasan](https://github.com/hasansezertasan). +* 🌐 Add Spanish translation for `docs/es/docs/learn/index.md`. PR [#10885](https://github.com/tiangolo/fastapi/pull/10885) by [@pablocm83](https://github.com/pablocm83). +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/body-fields.md`. PR [#10670](https://github.com/tiangolo/fastapi/pull/10670) by [@ArtemKhymenko](https://github.com/ArtemKhymenko). +* 🌐 Add Hungarian translation for `/docs/hu/docs/index.md`. PR [#10812](https://github.com/tiangolo/fastapi/pull/10812) by [@takacs](https://github.com/takacs). +* 🌐 Add Turkish translation for `docs/tr/docs/newsletter.md`. PR [#10550](https://github.com/tiangolo/fastapi/pull/10550) by [@hasansezertasan](https://github.com/hasansezertasan). +* 🌐 Add Spanish translation for `docs/es/docs/help/index.md`. PR [#10907](https://github.com/tiangolo/fastapi/pull/10907) by [@pablocm83](https://github.com/pablocm83). +* 🌐 Add Spanish translation for `docs/es/docs/about/index.md`. PR [#10908](https://github.com/tiangolo/fastapi/pull/10908) by [@pablocm83](https://github.com/pablocm83). +* 🌐 Add Spanish translation for `docs/es/docs/resources/index.md`. PR [#10909](https://github.com/tiangolo/fastapi/pull/10909) by [@pablocm83](https://github.com/pablocm83). + +### Internal + +* 👥 Update FastAPI People. PR [#10871](https://github.com/tiangolo/fastapi/pull/10871) by [@tiangolo](https://github.com/tiangolo). +* 👷 Upgrade custom GitHub Action comment-docs-preview-in-pr. PR [#10916](https://github.com/tiangolo/fastapi/pull/10916) by [@tiangolo](https://github.com/tiangolo). +* ⬆️ Upgrade GitHub Action latest-changes. PR [#10915](https://github.com/tiangolo/fastapi/pull/10915) by [@tiangolo](https://github.com/tiangolo). +* 👷 Upgrade GitHub Action label-approved. PR [#10913](https://github.com/tiangolo/fastapi/pull/10913) by [@tiangolo](https://github.com/tiangolo). +* ⬆️ Upgrade GitHub Action label-approved. PR [#10905](https://github.com/tiangolo/fastapi/pull/10905) by [@tiangolo](https://github.com/tiangolo). + +## 0.108.0 + +### Upgrades + +* ⬆️ Upgrade Starlette to `>=0.29.0,<0.33.0`, update docs and usage of templates with new Starlette arguments. PR [#10846](https://github.com/tiangolo/fastapi/pull/10846) by [@tiangolo](https://github.com/tiangolo). + +## 0.107.0 + +### Upgrades + +* ⬆️ Upgrade Starlette to 0.28.0. PR [#9636](https://github.com/tiangolo/fastapi/pull/9636) by [@adriangb](https://github.com/adriangb). + +### Docs + +* 📝 Add docs: Node.js script alternative to update OpenAPI for generated clients. PR [#10845](https://github.com/tiangolo/fastapi/pull/10845) by [@alejsdev](https://github.com/alejsdev). +* 📝 Restructure Docs section in Contributing page. PR [#10844](https://github.com/tiangolo/fastapi/pull/10844) by [@alejsdev](https://github.com/alejsdev). + +## 0.106.0 + +### Breaking Changes + +Using resources from dependencies with `yield` in background tasks is no longer supported. + +This change is what supports the new features, read below. 🤓 + +### Dependencies with `yield`, `HTTPException` and Background Tasks + +Dependencies with `yield` now can raise `HTTPException` and other exceptions after `yield`. 🎉 + +Read the new docs here: [Dependencies with `yield` and `HTTPException`](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield-and-httpexception). + +```Python +from fastapi import Depends, FastAPI, HTTPException +from typing_extensions import Annotated + +app = FastAPI() + + +data = { + "plumbus": {"description": "Freshly pickled plumbus", "owner": "Morty"}, + "portal-gun": {"description": "Gun to create portals", "owner": "Rick"}, +} + + +class OwnerError(Exception): + pass + + +def get_username(): + try: + yield "Rick" + except OwnerError as e: + raise HTTPException(status_code=400, detail=f"Owner error: {e}") + + +@app.get("/items/{item_id}") +def get_item(item_id: str, username: Annotated[str, Depends(get_username)]): + if item_id not in data: + raise HTTPException(status_code=404, detail="Item not found") + item = data[item_id] + if item["owner"] != username: + raise OwnerError(username) + return item +``` + +--- + +Before FastAPI 0.106.0, raising exceptions after `yield` was not possible, the exit code in dependencies with `yield` was executed *after* the response was sent, so [Exception Handlers](https://fastapi.tiangolo.com/tutorial/handling-errors/#install-custom-exception-handlers) would have already run. + +This was designed this way mainly to allow using the same objects "yielded" by dependencies inside of background tasks, because the exit code would be executed after the background tasks were finished. + +Nevertheless, as this would mean waiting for the response to travel through the network while unnecessarily holding a resource in a dependency with yield (for example a database connection), this was changed in FastAPI 0.106.0. + +Additionally, a background task is normally an independent set of logic that should be handled separately, with its own resources (e.g. its own database connection). + +If you used to rely on this behavior, now you should create the resources for background tasks inside the background task itself, and use internally only data that doesn't depend on the resources of dependencies with `yield`. + +For example, instead of using the same database session, you would create a new database session inside of the background task, and you would obtain the objects from the database using this new session. And then instead of passing the object from the database as a parameter to the background task function, you would pass the ID of that object and then obtain the object again inside the background task function. + +The sequence of execution before FastAPI 0.106.0 was like this diagram: + +Time flows from top to bottom. And each column is one of the parts interacting or executing code. + +```mermaid +sequenceDiagram + +participant client as Client +participant handler as Exception handler +participant dep as Dep with yield +participant operation as Path Operation +participant tasks as Background tasks + + Note over client,tasks: Can raise exception for dependency, handled after response is sent + Note over client,operation: Can raise HTTPException and can change the response + client ->> dep: Start request + Note over dep: Run code up to yield + opt raise + dep -->> handler: Raise HTTPException + handler -->> client: HTTP error response + dep -->> dep: Raise other exception + end + dep ->> operation: Run dependency, e.g. DB session + opt raise + operation -->> dep: Raise HTTPException + dep -->> handler: Auto forward exception + handler -->> client: HTTP error response + operation -->> dep: Raise other exception + dep -->> handler: Auto forward exception + end + operation ->> client: Return response to client + Note over client,operation: Response is already sent, can't change it anymore + opt Tasks + operation -->> tasks: Send background tasks + end + opt Raise other exception + tasks -->> dep: Raise other exception + end + Note over dep: After yield + opt Handle other exception + dep -->> dep: Handle exception, can't change response. E.g. close DB session. + end +``` + +The new execution flow can be found in the docs: [Execution of dependencies with `yield`](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#execution-of-dependencies-with-yield). + +### Features + +* ✨ Add support for raising exceptions (including `HTTPException`) in dependencies with `yield` in the exit code, do not support them in background tasks. PR [#10831](https://github.com/tiangolo/fastapi/pull/10831) by [@tiangolo](https://github.com/tiangolo). + +### Internal + +* 👥 Update FastAPI People. PR [#10567](https://github.com/tiangolo/fastapi/pull/10567) by [@tiangolo](https://github.com/tiangolo). + ## 0.105.0 ### Features @@ -3171,7 +3435,7 @@ Note: all the previous parameters are still there, so it's still possible to dec * Add OAuth2 redirect page for Swagger UI. This allows having delegated authentication in the Swagger UI docs. For this to work, you need to add `{your_origin}/docs/oauth2-redirect` to the allowed callbacks in your OAuth2 provider (in Auth0, Facebook, Google, etc). * For example, during development, it could be `http://localhost:8000/docs/oauth2-redirect`. - * Have in mind that this callback URL is independent of whichever one is used by your frontend. You might also have another callback at `https://yourdomain.com/login/callback`. + * Keep in mind that this callback URL is independent of whichever one is used by your frontend. You might also have another callback at `https://yourdomain.com/login/callback`. * This is only to allow delegated authentication in the API docs with Swagger UI. * PR [#198](https://github.com/tiangolo/fastapi/pull/198) by [@steinitzu](https://github.com/steinitzu). diff --git a/docs/en/docs/tutorial/bigger-applications.md b/docs/en/docs/tutorial/bigger-applications.md index 1cf7e50e02c50..b2d92840523a3 100644 --- a/docs/en/docs/tutorial/bigger-applications.md +++ b/docs/en/docs/tutorial/bigger-applications.md @@ -79,7 +79,7 @@ You can create the *path operations* for that module using `APIRouter`. You import it and create an "instance" the same way you would with the class `FastAPI`: -```Python hl_lines="1 3" +```Python hl_lines="1 3" title="app/routers/users.py" {!../../../docs_src/bigger_applications/app/routers/users.py!} ``` @@ -89,7 +89,7 @@ And then you use it to declare your *path operations*. Use it the same way you would use the `FastAPI` class: -```Python hl_lines="6 11 16" +```Python hl_lines="6 11 16" title="app/routers/users.py" {!../../../docs_src/bigger_applications/app/routers/users.py!} ``` @@ -114,13 +114,13 @@ We will now use a simple dependency to read a custom `X-Token` header: === "Python 3.9+" - ```Python hl_lines="3 6-8" + ```Python hl_lines="3 6-8" title="app/dependencies.py" {!> ../../../docs_src/bigger_applications/app_an_py39/dependencies.py!} ``` === "Python 3.8+" - ```Python hl_lines="1 5-7" + ```Python hl_lines="1 5-7" title="app/dependencies.py" {!> ../../../docs_src/bigger_applications/app_an/dependencies.py!} ``` @@ -129,7 +129,7 @@ We will now use a simple dependency to read a custom `X-Token` header: !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="1 4-6" + ```Python hl_lines="1 4-6" title="app/dependencies.py" {!> ../../../docs_src/bigger_applications/app/dependencies.py!} ``` @@ -160,7 +160,7 @@ We know all the *path operations* in this module have the same: So, instead of adding all that to each *path operation*, we can add it to the `APIRouter`. -```Python hl_lines="5-10 16 21" +```Python hl_lines="5-10 16 21" title="app/routers/items.py" {!../../../docs_src/bigger_applications/app/routers/items.py!} ``` @@ -212,7 +212,7 @@ And we need to get the dependency function from the module `app.dependencies`, t So we use a relative import with `..` for the dependencies: -```Python hl_lines="3" +```Python hl_lines="3" title="app/routers/items.py" {!../../../docs_src/bigger_applications/app/routers/items.py!} ``` @@ -282,7 +282,7 @@ We are not adding the prefix `/items` nor the `tags=["items"]` to each *path ope But we can still add _more_ `tags` that will be applied to a specific *path operation*, and also some extra `responses` specific to that *path operation*: -```Python hl_lines="30-31" +```Python hl_lines="30-31" title="app/routers/items.py" {!../../../docs_src/bigger_applications/app/routers/items.py!} ``` @@ -307,7 +307,7 @@ You import and create a `FastAPI` class as normally. And we can even declare [global dependencies](dependencies/global-dependencies.md){.internal-link target=_blank} that will be combined with the dependencies for each `APIRouter`: -```Python hl_lines="1 3 7" +```Python hl_lines="1 3 7" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -315,7 +315,7 @@ And we can even declare [global dependencies](dependencies/global-dependencies.m Now we import the other submodules that have `APIRouter`s: -```Python hl_lines="5" +```Python hl_lines="4-5" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -377,7 +377,7 @@ The `router` from `users` would overwrite the one from `items` and we wouldn't b So, to be able to use both of them in the same file, we import the submodules directly: -```Python hl_lines="5" +```Python hl_lines="5" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -385,7 +385,7 @@ So, to be able to use both of them in the same file, we import the submodules di Now, let's include the `router`s from the submodules `users` and `items`: -```Python hl_lines="10-11" +```Python hl_lines="10-11" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -418,7 +418,7 @@ It contains an `APIRouter` with some admin *path operations* that your organizat For this example it will be super simple. But let's say that because it is shared with other projects in the organization, we cannot modify it and add a `prefix`, `dependencies`, `tags`, etc. directly to the `APIRouter`: -```Python hl_lines="3" +```Python hl_lines="3" title="app/internal/admin.py" {!../../../docs_src/bigger_applications/app/internal/admin.py!} ``` @@ -426,7 +426,7 @@ But we still want to set a custom `prefix` when including the `APIRouter` so tha We can declare all that without having to modify the original `APIRouter` by passing those parameters to `app.include_router()`: -```Python hl_lines="14-17" +```Python hl_lines="14-17" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -449,7 +449,7 @@ We can also add *path operations* directly to the `FastAPI` app. Here we do it... just to show that we can 🤷: -```Python hl_lines="21-23" +```Python hl_lines="21-23" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` diff --git a/docs/en/docs/tutorial/body-nested-models.md b/docs/en/docs/tutorial/body-nested-models.md index 387f0de9aaed7..7058d4ad040c5 100644 --- a/docs/en/docs/tutorial/body-nested-models.md +++ b/docs/en/docs/tutorial/body-nested-models.md @@ -361,7 +361,7 @@ In this case, you would accept any `dict` as long as it has `int` keys with `flo ``` !!! tip - Have in mind that JSON only supports `str` as keys. + Keep in mind that JSON only supports `str` as keys. But Pydantic has automatic data conversion. diff --git a/docs/en/docs/tutorial/body-updates.md b/docs/en/docs/tutorial/body-updates.md index 3341f2d5d88b4..39d133c55f3dd 100644 --- a/docs/en/docs/tutorial/body-updates.md +++ b/docs/en/docs/tutorial/body-updates.md @@ -59,9 +59,14 @@ This means that you can send only the data that you want to update, leaving the ### Using Pydantic's `exclude_unset` parameter -If you want to receive partial updates, it's very useful to use the parameter `exclude_unset` in Pydantic's model's `.dict()`. +If you want to receive partial updates, it's very useful to use the parameter `exclude_unset` in Pydantic's model's `.model_dump()`. -Like `item.dict(exclude_unset=True)`. +Like `item.model_dump(exclude_unset=True)`. + +!!! info + In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`. + + The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. That would generate a `dict` with only the data that was set when creating the `item` model, excluding default values. @@ -87,9 +92,14 @@ Then you can use this to generate a `dict` with only the data that was set (sent ### Using Pydantic's `update` parameter -Now, you can create a copy of the existing model using `.copy()`, and pass the `update` parameter with a `dict` containing the data to update. +Now, you can create a copy of the existing model using `.model_copy()`, and pass the `update` parameter with a `dict` containing the data to update. + +!!! info + In Pydantic v1 the method was called `.copy()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_copy()`. + + The examples here use `.copy()` for compatibility with Pydantic v1, but you should use `.model_copy()` instead if you can use Pydantic v2. -Like `stored_item_model.copy(update=update_data)`: +Like `stored_item_model.model_copy(update=update_data)`: === "Python 3.10+" @@ -120,7 +130,7 @@ In summary, to apply partial updates you would: * This way you can update only the values actually set by the user, instead of overriding values already stored with default values in your model. * Create a copy of the stored model, updating it's attributes with the received partial updates (using the `update` parameter). * Convert the copied model to something that can be stored in your DB (for example, using the `jsonable_encoder`). - * This is comparable to using the model's `.dict()` method again, but it makes sure (and converts) the values to data types that can be converted to JSON, for example, `datetime` to `str`. + * This is comparable to using the model's `.model_dump()` method again, but it makes sure (and converts) the values to data types that can be converted to JSON, for example, `datetime` to `str`. * Save the data to your DB. * Return the updated model. diff --git a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md index fe18f1f1d9afe..de87ba3156e54 100644 --- a/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/en/docs/tutorial/dependencies/dependencies-with-yield.md @@ -1,8 +1,8 @@ # Dependencies with yield -FastAPI supports dependencies that do some extra steps after finishing. +FastAPI supports dependencies that do some extra steps after finishing. -To do this, use `yield` instead of `return`, and write the extra steps after. +To do this, use `yield` instead of `return`, and write the extra steps (code) after. !!! tip Make sure to use `yield` one single time. @@ -21,7 +21,7 @@ To do this, use `yield` instead of `return`, and write the extra steps after. For example, you could use this to create a database session and close it after finishing. -Only the code prior to and including the `yield` statement is executed before sending a response: +Only the code prior to and including the `yield` statement is executed before creating a response: ```Python hl_lines="2-4" {!../../../docs_src/dependencies/tutorial007.py!} @@ -40,7 +40,7 @@ The code following the `yield` statement is executed after the response has been ``` !!! tip - You can use `async` or normal functions. + You can use `async` or regular functions. **FastAPI** will do the right thing with each, the same as with normal dependencies. @@ -114,7 +114,7 @@ And, in turn, `dependency_b` needs the value from `dependency_a` (here named `de {!> ../../../docs_src/dependencies/tutorial008.py!} ``` -The same way, you could have dependencies with `yield` and `return` mixed. +The same way, you could have some dependencies with `yield` and some other dependencies with `return`, and have some of those depend on some of the others. And you could have a single dependency that requires several other dependencies with `yield`, etc. @@ -131,24 +131,38 @@ You can have any combinations of dependencies that you want. You saw that you can use dependencies with `yield` and have `try` blocks that catch exceptions. -It might be tempting to raise an `HTTPException` or similar in the exit code, after the `yield`. But **it won't work**. +The same way, you could raise an `HTTPException` or similar in the exit code, after the `yield`. -The exit code in dependencies with `yield` is executed *after* the response is sent, so [Exception Handlers](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank} will have already run. There's nothing catching exceptions thrown by your dependencies in the exit code (after the `yield`). +!!! tip -So, if you raise an `HTTPException` after the `yield`, the default (or any custom) exception handler that catches `HTTPException`s and returns an HTTP 400 response won't be there to catch that exception anymore. + This is a somewhat advanced technique, and in most of the cases you won't really need it, as you can raise exceptions (including `HTTPException`) from inside of the rest of your application code, for example, in the *path operation function*. -This is what allows anything set in the dependency (e.g. a DB session) to, for example, be used by background tasks. + But it's there for you if you need it. 🤓 -Background tasks are run *after* the response has been sent. So there's no way to raise an `HTTPException` because there's not even a way to change the response that is *already sent*. +=== "Python 3.9+" -But if a background task creates a DB error, at least you can rollback or cleanly close the session in the dependency with `yield`, and maybe log the error or report it to a remote tracking system. + ```Python hl_lines="18-22 31" + {!> ../../../docs_src/dependencies/tutorial008b_an_py39.py!} + ``` -If you have some code that you know could raise an exception, do the most normal/"Pythonic" thing and add a `try` block in that section of the code. +=== "Python 3.8+" -If you have custom exceptions that you would like to handle *before* returning the response and possibly modifying the response, maybe even raising an `HTTPException`, create a [Custom Exception Handler](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. + ```Python hl_lines="17-21 30" + {!> ../../../docs_src/dependencies/tutorial008b_an.py!} + ``` -!!! tip - You can still raise exceptions including `HTTPException` *before* the `yield`. But not after. +=== "Python 3.8+ non-Annotated" + + !!! tip + Prefer to use the `Annotated` version if possible. + + ```Python hl_lines="16-20 29" + {!> ../../../docs_src/dependencies/tutorial008b.py!} + ``` + +An alternative you could use to catch exceptions (and possibly also raise another `HTTPException`) is to create a [Custom Exception Handler](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. + +## Execution of dependencies with `yield` The sequence of execution is more or less like this diagram. Time flows from top to bottom. And each column is one of the parts interacting or executing code. @@ -161,34 +175,30 @@ participant dep as Dep with yield participant operation as Path Operation participant tasks as Background tasks - Note over client,tasks: Can raise exception for dependency, handled after response is sent - Note over client,operation: Can raise HTTPException and can change the response + Note over client,operation: Can raise exceptions, including HTTPException client ->> dep: Start request Note over dep: Run code up to yield - opt raise - dep -->> handler: Raise HTTPException + opt raise Exception + dep -->> handler: Raise Exception handler -->> client: HTTP error response - dep -->> dep: Raise other exception end dep ->> operation: Run dependency, e.g. DB session opt raise - operation -->> dep: Raise HTTPException - dep -->> handler: Auto forward exception + operation -->> dep: Raise Exception (e.g. HTTPException) + opt handle + dep -->> dep: Can catch exception, raise a new HTTPException, raise other exception + dep -->> handler: Auto forward exception + end handler -->> client: HTTP error response - operation -->> dep: Raise other exception - dep -->> handler: Auto forward exception end + operation ->> client: Return response to client Note over client,operation: Response is already sent, can't change it anymore opt Tasks operation -->> tasks: Send background tasks end opt Raise other exception - tasks -->> dep: Raise other exception - end - Note over dep: After yield - opt Handle other exception - dep -->> dep: Handle exception, can't change response. E.g. close DB session. + tasks -->> tasks: Handle exceptions in the background task code end ``` @@ -198,10 +208,33 @@ participant tasks as Background tasks After one of those responses is sent, no other response can be sent. !!! tip - This diagram shows `HTTPException`, but you could also raise any other exception for which you create a [Custom Exception Handler](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. + This diagram shows `HTTPException`, but you could also raise any other exception that you catch in a dependency with `yield` or with a [Custom Exception Handler](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}. If you raise any exception, it will be passed to the dependencies with yield, including `HTTPException`, and then **again** to the exception handlers. If there's no exception handler for that exception, it will then be handled by the default internal `ServerErrorMiddleware`, returning a 500 HTTP status code, to let the client know that there was an error in the server. +## Dependencies with `yield`, `HTTPException` and Background Tasks + +!!! warning + You most probably don't need these technical details, you can skip this section and continue below. + + These details are useful mainly if you were using a version of FastAPI prior to 0.106.0 and used resources from dependencies with `yield` in background tasks. + +Before FastAPI 0.106.0, raising exceptions after `yield` was not possible, the exit code in dependencies with `yield` was executed *after* the response was sent, so [Exception Handlers](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank} would have already run. + +This was designed this way mainly to allow using the same objects "yielded" by dependencies inside of background tasks, because the exit code would be executed after the background tasks were finished. + +Nevertheless, as this would mean waiting for the response to travel through the network while unnecessarily holding a resource in a dependency with yield (for example a database connection), this was changed in FastAPI 0.106.0. + +!!! tip + + Additionally, a background task is normally an independent set of logic that should be handled separately, with its own resources (e.g. its own database connection). + + So, this way you will probably have cleaner code. + +If you used to rely on this behavior, now you should create the resources for background tasks inside the background task itself, and use internally only data that doesn't depend on the resources of dependencies with `yield`. + +For example, instead of using the same database session, you would create a new database session inside of the background task, and you would obtain the objects from the database using this new session. And then instead of passing the object from the database as a parameter to the background task function, you would pass the ID of that object and then obtain the object again inside the background task function. + ## Context Managers ### What are "Context Managers" @@ -216,11 +249,11 @@ with open("./somefile.txt") as f: print(contents) ``` -Underneath, the `open("./somefile.txt")` creates an object that is a called a "Context Manager". +Underneath, the `open("./somefile.txt")` creates an object that is called a "Context Manager". When the `with` block finishes, it makes sure to close the file, even if there were exceptions. -When you create a dependency with `yield`, **FastAPI** will internally convert it to a context manager, and combine it with some other related tools. +When you create a dependency with `yield`, **FastAPI** will internally create a context manager for it, and combine it with some other related tools. ### Using context managers in dependencies with `yield` diff --git a/docs/en/docs/tutorial/dependencies/index.md b/docs/en/docs/tutorial/dependencies/index.md index bc98cb26edc54..608ced407ea49 100644 --- a/docs/en/docs/tutorial/dependencies/index.md +++ b/docs/en/docs/tutorial/dependencies/index.md @@ -287,9 +287,9 @@ Other common terms for this same idea of "dependency injection" are: ## **FastAPI** plug-ins -Integrations and "plug-in"s can be built using the **Dependency Injection** system. But in fact, there is actually **no need to create "plug-ins"**, as by using dependencies it's possible to declare an infinite number of integrations and interactions that become available to your *path operation functions*. +Integrations and "plug-ins" can be built using the **Dependency Injection** system. But in fact, there is actually **no need to create "plug-ins"**, as by using dependencies it's possible to declare an infinite number of integrations and interactions that become available to your *path operation functions*. -And dependencies can be created in a very simple and intuitive way that allow you to just import the Python packages you need, and integrate them with your API functions in a couple of lines of code, *literally*. +And dependencies can be created in a very simple and intuitive way that allows you to just import the Python packages you need, and integrate them with your API functions in a couple of lines of code, *literally*. You will see examples of this in the next chapters, about relational and NoSQL databases, security, etc. diff --git a/docs/en/docs/tutorial/extra-models.md b/docs/en/docs/tutorial/extra-models.md index 590d095bd2457..d83b6bc8594bb 100644 --- a/docs/en/docs/tutorial/extra-models.md +++ b/docs/en/docs/tutorial/extra-models.md @@ -29,6 +29,11 @@ Here's a general idea of how the models could look like with their password fiel {!> ../../../docs_src/extra_models/tutorial001.py!} ``` +!!! info + In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`. + + The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. + ### About `**user_in.dict()` #### Pydantic's `.dict()` diff --git a/docs/en/docs/tutorial/handling-errors.md b/docs/en/docs/tutorial/handling-errors.md index a03029e811356..7d521696d88ef 100644 --- a/docs/en/docs/tutorial/handling-errors.md +++ b/docs/en/docs/tutorial/handling-errors.md @@ -234,9 +234,7 @@ You will receive a response telling you that the data is invalid containing the And **FastAPI**'s `HTTPException` error class inherits from Starlette's `HTTPException` error class. -The only difference, is that **FastAPI**'s `HTTPException` allows you to add headers to be included in the response. - -This is needed/used internally for OAuth 2.0 and some security utilities. +The only difference is that **FastAPI**'s `HTTPException` accepts any JSON-able data for the `detail` field, while Starlette's `HTTPException` only accepts strings for it. So, you can keep raising **FastAPI**'s `HTTPException` as normally in your code. diff --git a/docs/en/docs/tutorial/middleware.md b/docs/en/docs/tutorial/middleware.md index 3c6868fe4de73..492a1b065e515 100644 --- a/docs/en/docs/tutorial/middleware.md +++ b/docs/en/docs/tutorial/middleware.md @@ -33,7 +33,7 @@ The middleware function receives: ``` !!! tip - Have in mind that custom proprietary headers can be added using the 'X-' prefix. + Keep in mind that custom proprietary headers can be added using the 'X-' prefix. But if you have custom headers that you want a client in a browser to be able to see, you need to add them to your CORS configurations ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}) using the parameter `expose_headers` documented in Starlette's CORS docs. diff --git a/docs/en/docs/tutorial/path-params-numeric-validations.md b/docs/en/docs/tutorial/path-params-numeric-validations.md index 57ad20b137ea0..b5b13cfbe6f81 100644 --- a/docs/en/docs/tutorial/path-params-numeric-validations.md +++ b/docs/en/docs/tutorial/path-params-numeric-validations.md @@ -126,7 +126,7 @@ So, you can declare your function as: {!> ../../../docs_src/path_params_numeric_validations/tutorial002.py!} ``` -But have in mind that if you use `Annotated`, you won't have this problem, it won't matter as you're not using the function parameter default values for `Query()` or `Path()`. +But keep in mind that if you use `Annotated`, you won't have this problem, it won't matter as you're not using the function parameter default values for `Query()` or `Path()`. === "Python 3.9+" @@ -166,7 +166,7 @@ Python won't do anything with that `*`, but it will know that all the following ### Better with `Annotated` -Have in mind that if you use `Annotated`, as you are not using function parameter default values, you won't have this problem, and you probably won't need to use `*`. +Keep in mind that if you use `Annotated`, as you are not using function parameter default values, you won't have this problem, and you probably won't need to use `*`. === "Python 3.9+" diff --git a/docs/en/docs/tutorial/query-params-str-validations.md b/docs/en/docs/tutorial/query-params-str-validations.md index 91ae615fffb68..7a9bc487541f9 100644 --- a/docs/en/docs/tutorial/query-params-str-validations.md +++ b/docs/en/docs/tutorial/query-params-str-validations.md @@ -173,7 +173,7 @@ q: str | None = None But it declares it explicitly as being a query parameter. !!! info - Have in mind that the most important part to make a parameter optional is the part: + Keep in mind that the most important part to make a parameter optional is the part: ```Python = None @@ -199,7 +199,7 @@ This will validate the data, show a clear error when the data is not valid, and ### `Query` as the default value or in `Annotated` -Have in mind that when using `Query` inside of `Annotated` you cannot use the `default` parameter for `Query`. +Keep in mind that when using `Query` inside of `Annotated` you cannot use the `default` parameter for `Query`. Instead use the actual default value of the function parameter. Otherwise, it would be inconsistent. @@ -659,7 +659,7 @@ You can also use `list` directly instead of `List[str]` (or `list[str]` in Pytho ``` !!! note - Have in mind that in this case, FastAPI won't check the contents of the list. + Keep in mind that in this case, FastAPI won't check the contents of the list. For example, `List[int]` would check (and document) that the contents of the list are integers. But `list` alone wouldn't. @@ -670,7 +670,7 @@ You can add more information about the parameter. That information will be included in the generated OpenAPI and used by the documentation user interfaces and external tools. !!! note - Have in mind that different tools might have different levels of OpenAPI support. + Keep in mind that different tools might have different levels of OpenAPI support. Some of them might not show all the extra information declared yet, although in most of the cases, the missing feature is already planned for development. diff --git a/docs/en/docs/tutorial/request-files.md b/docs/en/docs/tutorial/request-files.md index c85a68ed60631..8eb8ace64850c 100644 --- a/docs/en/docs/tutorial/request-files.md +++ b/docs/en/docs/tutorial/request-files.md @@ -71,7 +71,7 @@ The files will be uploaded as "form data". If you declare the type of your *path operation function* parameter as `bytes`, **FastAPI** will read the file for you and you will receive the contents as `bytes`. -Have in mind that this means that the whole contents will be stored in memory. This will work well for small files. +Keep in mind that this means that the whole contents will be stored in memory. This will work well for small files. But there are several cases in which you might benefit from using `UploadFile`. diff --git a/docs/en/docs/tutorial/response-model.md b/docs/en/docs/tutorial/response-model.md index d6d3d61cb4b24..d5683ac7f2e8a 100644 --- a/docs/en/docs/tutorial/response-model.md +++ b/docs/en/docs/tutorial/response-model.md @@ -377,6 +377,11 @@ So, if you send a request to that *path operation* for the item with ID `foo`, t } ``` +!!! info + In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`. + + The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. + !!! info FastAPI uses Pydantic model's `.dict()` with its `exclude_unset` parameter to achieve this. diff --git a/docs/en/docs/tutorial/security/get-current-user.md b/docs/en/docs/tutorial/security/get-current-user.md index e99a800c6d50c..dc6d87c9caaf8 100644 --- a/docs/en/docs/tutorial/security/get-current-user.md +++ b/docs/en/docs/tutorial/security/get-current-user.md @@ -227,7 +227,7 @@ Just use any kind of model, any kind of class, any kind of database that you nee ## Code size -This example might seem verbose. Have in mind that we are mixing security, data models, utility functions and *path operations* in the same file. +This example might seem verbose. Keep in mind that we are mixing security, data models, utility functions and *path operations* in the same file. But here's the key point. diff --git a/docs/en/docs/tutorial/security/oauth2-jwt.md b/docs/en/docs/tutorial/security/oauth2-jwt.md index 0a347fed3eb83..1c792e3d9e599 100644 --- a/docs/en/docs/tutorial/security/oauth2-jwt.md +++ b/docs/en/docs/tutorial/security/oauth2-jwt.md @@ -285,7 +285,7 @@ Create a real JWT access token and return it !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="114-127" + ```Python hl_lines="114-129" {!> ../../../docs_src/security/tutorial004_py310.py!} ``` @@ -294,7 +294,7 @@ Create a real JWT access token and return it !!! tip Prefer to use the `Annotated` version if possible. - ```Python hl_lines="115-128" + ```Python hl_lines="115-130" {!> ../../../docs_src/security/tutorial004.py!} ``` @@ -318,7 +318,7 @@ In those cases, several of those entities could have the same ID, let's say `foo So, to avoid ID collisions, when creating the JWT token for the user, you could prefix the value of the `sub` key, e.g. with `username:`. So, in this example, the value of `sub` could have been: `username:johndoe`. -The important thing to have in mind is that the `sub` key should have a unique identifier across the entire application, and it should be a string. +The important thing to keep in mind is that the `sub` key should have a unique identifier across the entire application, and it should be a string. ## Check it diff --git a/docs/en/docs/tutorial/sql-databases.md b/docs/en/docs/tutorial/sql-databases.md index 010244bbf6f14..70d9482df2257 100644 --- a/docs/en/docs/tutorial/sql-databases.md +++ b/docs/en/docs/tutorial/sql-databases.md @@ -301,7 +301,7 @@ while Pydantic *models* declare the types using `:`, the new type annotation syn name: str ``` -Have it in mind, so you don't get confused when using `=` and `:` with them. +Keep these in mind, so you don't get confused when using `=` and `:` with them. ### Create Pydantic *models* / schemas for reading / returning @@ -451,6 +451,11 @@ The steps are: {!../../../docs_src/sql_databases/sql_app/crud.py!} ``` +!!! info + In Pydantic v1 the method was called `.dict()`, it was deprecated (but still supported) in Pydantic v2, and renamed to `.model_dump()`. + + The examples here use `.dict()` for compatibility with Pydantic v1, but you should use `.model_dump()` instead if you can use Pydantic v2. + !!! tip The SQLAlchemy model for `User` contains a `hashed_password` that should contain a secure hashed version of the password. @@ -508,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 templates from [Project Generation - Template](../project-generation.md){.internal-link target=_blank}. Specifically in the `alembic` directory in the source code. ### Create a dependency @@ -624,7 +629,7 @@ def read_user(user_id: int, db: Session = Depends(get_db)): ``` !!! info - If you need to connect to your relational database asynchronously, see [Async SQL (Relational) Databases](../advanced/async-sql-databases.md){.internal-link target=_blank}. + If you need to connect to your relational database asynchronously, see [Async SQL (Relational) Databases](../how-to/async-sql-encode-databases.md){.internal-link target=_blank}. !!! note "Very Technical Details" If you are curious and have a deep technical knowledge, you can check the very technical details of how this `async def` vs `def` is handled in the [Async](../async.md#very-technical-details){.internal-link target=_blank} docs. diff --git a/docs/en/docs/tutorial/static-files.md b/docs/en/docs/tutorial/static-files.md index 7a0c36af3f4c5..311d2b1c8de14 100644 --- a/docs/en/docs/tutorial/static-files.md +++ b/docs/en/docs/tutorial/static-files.md @@ -22,7 +22,7 @@ You can serve static files automatically from a directory using `StaticFiles`. This is different from using an `APIRouter` as a mounted application is completely independent. The OpenAPI and docs from your main application won't include anything from the mounted application, etc. -You can read more about this in the **Advanced User Guide**. +You can read more about this in the [Advanced User Guide](../advanced/index.md){.internal-link target=_blank}. ## Details diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index a64eff26969aa..92d081aa12333 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -58,15 +58,18 @@ plugins: python: options: extensions: - - griffe_typingdoc + - griffe_typingdoc show_root_heading: true show_if_no_docstring: true - preload_modules: [httpx, starlette] + preload_modules: + - httpx + - starlette inherited_members: true members_order: source separate_signature: true unwrap_annotated: true - filters: ["!^_"] + filters: + - '!^_' merge_init_into_class: true docstring_section_style: spacy signature_crossrefs: true @@ -264,25 +267,25 @@ extra: - link: / name: en - English - link: /de/ - name: de - - link: /em/ - name: 😉 + name: de - Deutsch - link: /es/ name: es - español - link: /fa/ - name: fa + name: fa - فارسی - link: /fr/ name: fr - français - link: /he/ - name: he + name: he - עברית + - link: /hu/ + name: hu - magyar - link: /id/ - name: id + name: id - Bahasa Indonesia - link: /ja/ name: ja - 日本語 - link: /ko/ name: ko - 한국어 - link: /pl/ - name: pl + name: pl - Polski - link: /pt/ name: pt - português - link: /ru/ @@ -290,15 +293,17 @@ extra: - link: /tr/ name: tr - Türkçe - link: /uk/ - name: uk + name: uk - українська мова - link: /ur/ - name: ur + name: ur - اردو - link: /vi/ name: vi - Tiếng Việt - link: /yo/ name: yo - Yorùbá - link: /zh/ name: zh - 汉语 + - link: /em/ + name: 😉 extra_css: - css/termynal.css - css/custom.css diff --git a/docs/es/docs/about/index.md b/docs/es/docs/about/index.md new file mode 100644 index 0000000000000..e83400a8dc100 --- /dev/null +++ b/docs/es/docs/about/index.md @@ -0,0 +1,3 @@ +# Acerca de + +Acerca de FastAPI, su diseño, inspiración y más. 🤓 diff --git a/docs/es/docs/advanced/additional-status-codes.md b/docs/es/docs/advanced/additional-status-codes.md index 1f28ea85b738a..eaa3369ebe0b7 100644 --- a/docs/es/docs/advanced/additional-status-codes.md +++ b/docs/es/docs/advanced/additional-status-codes.md @@ -23,7 +23,7 @@ Para conseguir esto importa `JSONResponse` y devuelve ahí directamente tu conte No será serializado con el modelo, etc. - Asegurate de que la respuesta tenga los datos que quieras, y que los valores sean JSON válidos (si estás usando `JSONResponse`). + Asegúrate de que la respuesta tenga los datos que quieras, y que los valores sean JSON válidos (si estás usando `JSONResponse`). !!! note "Detalles Técnicos" También podrías utilizar `from starlette.responses import JSONResponse`. diff --git a/docs/es/docs/advanced/response-directly.md b/docs/es/docs/advanced/response-directly.md index 54dadf5763a9b..dee44ac08a239 100644 --- a/docs/es/docs/advanced/response-directly.md +++ b/docs/es/docs/advanced/response-directly.md @@ -21,7 +21,7 @@ Y cuando devuelves una `Response`, **FastAPI** la pasará directamente. No hará ninguna conversión de datos con modelos Pydantic, no convertirá el contenido a ningún tipo, etc. -Esto te da mucha flexibilidad. Puedes devolver cualquier tipo de dato, sobrescribir cualquer declaración de datos o validación, etc. +Esto te da mucha flexibilidad. Puedes devolver cualquier tipo de dato, sobrescribir cualquier declaración de datos o validación, etc. ## Usando el `jsonable_encoder` en una `Response` diff --git a/docs/es/docs/features.md b/docs/es/docs/features.md index d05c4f73e4058..d68791d635f95 100644 --- a/docs/es/docs/features.md +++ b/docs/es/docs/features.md @@ -13,7 +13,7 @@ ### Documentación automática -Documentación interactiva de la API e interfaces web de exploración. Hay múltiples opciones, dos incluídas por defecto, porque el framework está basado en OpenAPI. +Documentación interactiva de la API e interfaces web de exploración. Hay múltiples opciones, dos incluidas por defecto, porque el framework está basado en OpenAPI. * Swagger UI, con exploración interactiva, llama y prueba tu API directamente desde tu navegador. @@ -25,7 +25,7 @@ Documentación interactiva de la API e interfaces web de exploración. Hay múlt ### Simplemente Python moderno -Todo está basado en las declaraciones de tipo de **Python 3.8** estándar (gracias a Pydantic). No necesitas aprender una sintáxis nueva, solo Python moderno. +Todo está basado en las declaraciones de tipo de **Python 3.8** estándar (gracias a Pydantic). No necesitas aprender una sintaxis nueva, solo Python moderno. Si necesitas un repaso de 2 minutos de cómo usar los tipos de Python (así no uses FastAPI) prueba el tutorial corto: [Python Types](python-types.md){.internal-link target=_blank}. @@ -72,9 +72,9 @@ my_second_user: User = User(**second_user_data) El framework fue diseñado en su totalidad para ser fácil e intuitivo de usar. Todas las decisiones fueron probadas en múltiples editores antes de comenzar el desarrollo para asegurar la mejor experiencia de desarrollo. -En la última encuesta a desarrolladores de Python fue claro que la característica más usada es el "autocompletado". +En la última encuesta a desarrolladores de Python fue claro que la característica más usada es el "auto-completado". -El framework **FastAPI** está creado para satisfacer eso. El autocompletado funciona en todas partes. +El framework **FastAPI** está creado para satisfacer eso. El auto-completado funciona en todas partes. No vas a tener que volver a la documentación seguido. @@ -140,13 +140,13 @@ FastAPI incluye un sistema de Dependency Injection بسیار آسان اما بسیار قدرتمند است. + +* حتی وابستگی ها نیز میتوانند وابستگی هایی داشته باشند و یک سلسله مراتب یا **"گرافی" از وابستگی ها** ایجاد کنند. + +* همه چیز توسط فریم ورک **به طور خودکار اداره میشود** + +* همه وابستگی ها میتوانند به داده های request ها نیاز داشته باشند و مستندات خودکار و محدودیت های path operation را **افزایش** دهند. + +* با قابلیت **اعتبارسنجی خودکار** حتی برای path operation parameter های تعریف شده در وابستگی ها. + +* پشتیبانی از سیستم های پیچیده احرازهویت کاربر، **اتصالات پایگاه داده** و غیره. + +* بدون هیچ ارتباطی با دیتابیس ها، فرانت اند و غیره. اما ادغام آسان و راحت با همه آنها. + +### پلاگین های نامحدود + +یا به عبارت دیگر، هیچ نیازی به آنها نیست، کد موردنیاز خود را وارد و استفاده کنید. + +هر یکپارچه سازی به گونه ای طراحی شده است که استفاده از آن بسیار ساده باشد (با وابستگی ها) که میتوانید با استفاده از همان ساختار و روشی که برای _path operation_ های خود استفاده کرده اید تنها در ۲ خط کد "پلاگین" برنامه خودتان را ایجاد کنید. + +### تست شده + +* 100% پوشش تست. + +* 100% کد بر اساس type annotate ها. + +* استفاده شده در اپلیکیشن های تولید + +## ویژگی های Starlette + +**FastAPI** کاملا (و براساس) با Starlette سازگار است. بنابراین، هرکد اضافی Starlette که دارید، نیز کار خواهد کرد. + +‍‍`FastAPI` در واقع یک زیرکلاس از `Starlette` است. بنابراین اگر از قبل Starlette را میشناسید یا با آن کار کرده اید، بیشتر قابلیت ها به همین روش کار خواهد کرد. + +با **FastAPI** شما تمام ویژگی های **Starlette** را خواهید داشت (زیرا FastAPI یک نسخه و نمونه به تمام معنا از Starlette است): + +* عملکرد به طورجدی چشمگیر. این یکی از سریعترین فریم ورک های موجود در پایتون است که همتراز با **نود جی اس** و **گو** است. +* پشتیبانی از **WebSocket**. +* تسک های درجریان در پس زمینه. +* رویداد های راه اندازی و متوفق شدن. +* تست کلاینت ساخته شده به روی HTTPX. +* **CORS**, GZip, فایل های استاتیک, پاسخ های جریانی. +* پشتیبانی از **نشست ها و کوکی ها**. +* 100% پوشش با تست. +* 100% کد براساس type annotate ها. + +## ویژگی های Pydantic + +**FastAPI** کاملا (و براساس) با Pydantic سازگار است. بنابراین هرکد Pydantic اضافی که داشته باشید، نیز کار خواهد کرد. + +از جمله کتابخانه های خارجی نیز مبتنی بر Pydantic میتوان به ORM و ODM ها برای دیتابیس ها اشاره کرد. + +این همچنین به این معناست که در خیلی از موارد میتوانید همان ابجکتی که از request میگیرید را **مستقیما به دیتابیس** بفرستید زیرا همه چیز به طور خودکار تأیید میشود. + +همین امر برعکس نیز صدق می‌کند، در بسیاری از موارد شما می‌توانید ابجکتی را که از پایگاه داده دریافت می‌کنید را **مستقیماً به کاربر** ارسال کنید. + +با FastAPI شما تمام ویژگی های Pydantic را دراختیار دارید (زیرا FastAPI برای تمام بخش مدیریت دیتا بر اساس Pydantic عمل میکند): + +* **خبری از گیج شدن نیست**: + * هیچ زبان خردی برای یادگیری تعریف طرحواره های جدید وجود ندارد. + * اگر تایپ های پایتون را میشناسید، نحوه استفاده از Pydantic را نیز میدانید. +* به خوبی با **IDE/linter/مغز** شما عمل میکند: + * به این دلیل که ساختار داده Pydantic فقط نمونه هایی از کلاس هایی هستند که شما تعریف میکنید، تکمیل خودکار، mypy، linting و مشاهده شما باید به درستی با داده های معتبر شما کار کنند. +* اعتبار سنجی **ساختارهای پیچیده**: + * استفاده از مدل های سلسله مراتبی Pydantic, `List` و `Dict` کتابخانه `typing` پایتون و غیره. + * و اعتبارسنج ها اجازه میدهند که طرحواره های داده پیچیده به طور واضح و آسان تعریف، بررسی و بر پایه JSON مستند شوند. + * شما میتوانید ابجکت های عمیقا تودرتو JSON را که همگی تایید شده و annotated شده اند را داشته باشید. +* **قابل توسعه**: + * Pydantic اجازه میدهد تا data type های سفارشی تعریف شوند یا میتوانید اعتبارسنجی را با روش هایی به روی مدل ها با validator decorator گسترش دهید. +* 100% پوشش با تست. diff --git a/docs/hu/docs/index.md b/docs/hu/docs/index.md new file mode 100644 index 0000000000000..29c3c05ac6271 --- /dev/null +++ b/docs/hu/docs/index.md @@ -0,0 +1,469 @@ +

+ FastAPI +

+

+ FastAPI keretrendszer, nagy teljesítmény, könnyen tanulható, gyorsan kódolható, productionre kész +

+

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

+ +--- + +**Dokumentáció**: https://fastapi.tiangolo.com + +**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. + + +Kulcs funkciók: + +* **Gyors**: Nagyon nagy teljesítmény, a **NodeJS**-el és a **Go**-val egyenrangú (a Starlettenek és a Pydantic-nek köszönhetően). [Az egyik leggyorsabb Python keretrendszer](#performance). +* **Gyorsan kódolható**: A funkciók fejlesztési sebességét 200-300 százalékkal megnöveli. * +* **Kevesebb hiba**: Körülbelül 40%-al csökkenti az emberi (fejlesztői) hibák számát. * +* **Intuitív**: Kiváló szerkesztő támogatás. Kiegészítés mindenhol. Kevesebb hibakereséssel töltött idő. +* **Egyszerű**: Egyszerű tanulásra és használatra tervezve. Kevesebb dokumentáció olvasással töltött idő. +* **Rövid**: Kód duplikáció minimalizálása. Több funkció minden paraméter deklarálásával. Kevesebb hiba. +* **Robosztus**: Production ready kód. Automatikus interaktív dokumentáció val. +* **Szabvány alapú**: Az API-ok nyílt szabványaira alapuló (és azokkal teljesen kompatibilis): OpenAPI (korábban Swagger néven ismert) és a JSON Schema. + +* Egy production alkalmazásokat építő belső fejlesztői csapat tesztjein alapuló becslés. + +## Szponzorok + + + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} + +{% endfor -%} +{%- for sponsor in sponsors.silver -%} + +{% endfor %} +{% endif %} + + + +További szponzorok + +## Vélemények + +"_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._" + +
Kabir Khan - Microsoft (ref)
+ +--- + +"_We adopted the **FastAPI** library to spawn a **REST** server that can be queried to obtain **predictions**. [for Ludwig]_" + +
Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - Uber (ref)
+ +--- + +"_**Netflix** is pleased to announce the open-source release of our **crisis management** orchestration framework: **Dispatch**! [built with **FastAPI**]_" + +
Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix (ref)
+ +--- + +"_I’m over the moon excited about **FastAPI**. It’s so fun!_" + +
Brian Okken - Python Bytes podcast host (ref)
+ +--- + +"_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._" + +
Timothy Crosley - Hug creator (ref)
+ +--- + +"_If you're looking to learn one **modern framework** for building REST APIs, check out **FastAPI** [...] It's fast, easy to use and easy to learn [...]_" + +"_We've switched over to **FastAPI** for our **APIs** [...] I think you'll like it [...]_" + +
Ines Montani - Matthew Honnibal - Explosion AI founders - spaCy creators (ref) - (ref)
+ +--- + +"_If anyone is looking to build a production Python API, I would highly recommend **FastAPI**. It is **beautifully designed**, **simple to use** and **highly scalable**, it has become a **key component** in our API first development strategy and is driving many automations and services such as our Virtual TAC Engineer._" + +
Deon Pillsbury - Cisco (ref)
+ +--- + +## **Typer**, a CLI-ok FastAPI-ja + + + +Ha egy olyan CLI alkalmazást fejlesztesz amit a parancssorban kell használni webes API helyett, tekintsd meg: **Typer**. + +**Typer** a FastAPI kistestvére. A **CLI-k FastAPI-ja**. ⌨️ 🚀 + +## Követelmények + +Python 3.8+ + +A FastAPI óriások vállán áll: + +* Starlette a webes részekhez. +* Pydantic az adat részekhez. + +## Telepítés + +
+ +```console +$ pip install fastapi + +---> 100% +``` + +
+ +A production-höz egy ASGI szerverre is szükség lesz, mint például az Uvicorn vagy a Hypercorn. + +
+ +```console +$ pip install "uvicorn[standard]" + +---> 100% +``` + +
+ +## Példa + +### Hozd létre + +* Hozz létre a `main.py` fájlt a következő tartalommal: + +```Python +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +
+Vagy használd az async def-et... + +Ha a kódod `async` / `await`-et, használ `async def`: + +```Python hl_lines="9 14" +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +async def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +async def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +**Megjegyzés**: + +Ha nem tudod, tekintsd meg a _"Sietsz?"_ szekciót `async` és `await`-ről dokumentációba. + +
+ +### Futtasd le + +Indítsd el a szervert a következő paranccsal: + +
+ +```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. +``` + +
+ +
+A parancsról uvicorn main:app --reload... + +A `uvicorn main:app` parancs a következőre utal: + +* `main`: fájl `main.py` (a Python "modul"). +* `app`: a `main.py`-ban a `app = FastAPI()` sorral létrehozott objektum. +* `--reload`: kód változtatás esetén újra indítja a szervert. Csak fejlesztés közben használandó. + +
+ +### Ellenőrizd + +Nyisd meg a böngésződ a következő címen: http://127.0.0.1:8000/items/5?q=somequery. + +A következő JSON választ fogod látni: + +```JSON +{"item_id": 5, "q": "somequery"} +``` + +Máris létrehoztál egy API-t ami: + +* HTTP kéréseket fogad a `/` és `/items/{item_id}` _útvonalakon_. +* Mindkét _útvonal_ a `GET` műveletet használja (másik elnevezés: HTTP _metódus_). +* A `/items/{item_id}` _útvonalnak_ van egy _path paramétere_, az `item_id`, aminek `int` típusúnak kell lennie. +* A `/items/{item_id}` _útvonalnak_ még van egy opcionális, `str` típusú _query paramétere_ is, a `q`. + +### Interaktív API dokumentáció + +Most nyisd meg a http://127.0.0.1:8000/docs címet. + +Az automatikus interaktív API dokumentációt fogod látni (amit a Swagger UI-al hozunk létre): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### Alternatív API dokumentáció + +És most menj el a http://127.0.0.1:8000/redoc címre. + +Az alternatív automatikus dokumentációt fogod látni. (lásd ReDoc): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +## Példa frissítése + +Módosítsuk a `main.py` fájlt, hogy `PUT` kérések esetén tudjon body-t fogadni. + +Deklaráld a body-t standard Python típusokkal, a Pydantic-nak köszönhetően. + +```Python hl_lines="4 9-12 25-27" +from typing import Union + +from fastapi import FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Item(BaseModel): + name: str + price: float + is_offer: Union[bool, None] = None + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} + + +@app.put("/items/{item_id}") +def update_item(item_id: int, item: Item): + return {"item_name": item.name, "item_id": item_id} +``` + +A szerver automatikusan újraindul (mert hozzáadtuk a --reload paramétert a fenti `uvicorn` parancshoz). + +### Interaktív API dokumentáció frissítése + +Most menj el a http://127.0.0.1:8000/docs címre. + +* Az interaktív API dokumentáció automatikusan frissült így már benne van az új body. + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* Kattints rá a "Try it out" gombra, ennek segítségével kitöltheted a paramétereket és közvetlen használhatod az API-t: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) + +* Ezután kattints az "Execute" gompra, a felhasználói felület kommunikálni fog az API-oddal. Elküldi a paramétereket és a visszakapott választ megmutatja a képernyődön. + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) + +### Alternatív API dokumentáció frissítés + +Most menj el a http://127.0.0.1:8000/redoc címre. + +* Az alternatív dokumentáció szintúgy tükrözni fogja az új kérési paraméter és body-t. + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### Összefoglalás + +Összegzésül, deklarálod **egyszer** a paraméterek, body, stb típusát funkciós paraméterekként. + +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+**. + +Például egy `int`-nek: + +```Python +item_id: int +``` + +Egy komplexebb `Item` modellnek: + +```Python +item: Item +``` + +... És csupán egy deklarációval megkapod a: + +* Szerkesztő támogatást, beleértve: + * Szövegkiegészítés. + * Típus ellenőrzés. +* Adatok validációja: + * Automatikus és érthető hibák amikor az adatok hibásak. + * Validáció mélyen ágyazott objektumok esetén is. +* Bemeneti adatok átváltása : a hálózatról érkező Python adatokká és típusokká. Adatok olvasása következő forrásokból: + * JSON. + * Cím paraméterek. + * Query paraméterek. + * Cookie-k. + * Header-ök. + * Formok. + * Fájlok. +* Kimeneti adatok átváltása: Python adatok is típusokról hálózati adatokká: + * válts át Python típusokat (`str`, `int`, `float`, `bool`, `list`, etc). + * `datetime` csak objektumokat. + * `UUID` objektumokat. + * Adatbázis modelleket. + * ...És sok mást. +* Automatikus interaktív dokumentáció, beleértve két alternatív dokumentációt is: + * Swagger UI. + * ReDoc. + +--- + +Visszatérve az előző kód példához. A **FastAPI**: + +* Validálja hogy van egy `item_id` mező a `GET` és `PUT` kérésekben. +* Validálja hogy az `item_id` `int` típusú a `GET` és `PUT` kérésekben. + * Ha nem akkor látni fogunk egy tiszta hibát ezzel kapcsolatban. +* ellenőrzi hogyha van egy opcionális query paraméter `q` névvel (azaz `http://127.0.0.1:8000/items/foo?q=somequery`) `GET` kérések esetén. + * Mivel a `q` paraméter `= None`-al van deklarálva, ezért opcionális. + * `None` nélkül ez a mező kötelező lenne (mint például a body `PUT` kérések esetén). +* a `/items/{item_id}` címre érkező `PUT` kérések esetén, a JSON-t a következőképpen olvassa be: + * Ellenőrzi hogy létezik a kötelező `name` nevű attribútum és `string`. + * Ellenőrzi hogy létezik a kötelező `price` nevű attribútum és `float`. + * Ellenőrzi hogy létezik a `is_offer` nevű opcionális paraméter, ami ha létezik akkor `bool` + * Ez ágyazott JSON objektumokkal is működik +* JSONről való automatikus konvertálás. +* dokumentáljuk mindent OpenAPI-al amit használható: + * Interaktív dokumentációs rendszerekkel. + * Automatikus kliens kód generáló a rendszerekkel, több nyelven. +* Hozzá tartozik kettő interaktív dokumentációs web felület. + +--- + +Eddig csak a felszínt kapargattuk, de a lényeg hogy most már könnyebben érthető hogyan működik. + +Próbáld kicserélni a következő sorban: + +```Python + return {"item_name": item.name, "item_id": item_id} +``` + +...ezt: + +```Python + ... "item_name": item.name ... +``` + +...erre: + +```Python + ... "item_price": item.price ... +``` + +... És figyeld meg hogy a szerkesztő automatikusan tudni fogja a típusokat és kiegészíti azokat: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +Teljesebb példákért és funkciókért tekintsd meg a Tutorial - User Guide -t. + +**Spoiler veszély**: a Tutorial - User Guidehoz tartozik: + +* **Paraméterek** deklarációja különböző helyekről: **header-ök**, **cookie-k**, **form mezők** és **fájlok**. +* Hogyan állíts be **validációs feltételeket** mint a `maximum_length` vagy a `regex`. +* Nagyon hatékony és erős **Függőség Injekció** rendszerek. +* Biztonság és autentikáció beleértve, **OAuth2**, **JWT tokens** és **HTTP Basic** támogatást. +* Több haladó (de ugyanannyira könnyű) technika **mélyen ágyazott JSON modellek deklarációjára** (Pydantic-nek köszönhetően). +* **GraphQL** integráció Strawberry-vel és más könyvtárakkal. +* több extra funkció (Starlette-nek köszönhetően) pl.: + * **WebSockets** + * rendkívül könnyű tesztek HTTPX és `pytest` alapokra építve + * **CORS** + * **Cookie Sessions** + * ...és több. + +## Teljesítmény + +A független TechEmpower benchmarkok szerint az Uvicorn alatt futó **FastAPI** alkalmazások az egyik leggyorsabb Python keretrendszerek közé tartoznak, éppen lemaradva a Starlette és az Uvicorn (melyeket a FastAPI belsőleg használ) mögött.(*) + +Ezeknek a további megértéséhez: Benchmarks. + +## Opcionális követelmények + +Pydantic által használt: + +* email_validator - e-mail validációkra. +* pydantic-settings - Beállítások követésére. +* pydantic-extra-types - Extra típusok Pydantic-hoz. + +Starlette által használt: + +* httpx - Követelmény ha a `TestClient`-et akarod használni. +* jinja2 - Követelmény ha az alap template konfigurációt akarod használni. +* python-multipart - Követelmény ha "parsing"-ot akarsz támogatni, `request.form()`-al. +* itsdangerous - Követelmény `SessionMiddleware` támogatáshoz. +* pyyaml - Követelmény a Starlette `SchemaGenerator`-ának támogatásához (valószínűleg erre nincs szükség FastAPI használása esetén). +* ujson - Követelmény ha `UJSONResponse`-t akarsz használni. + +FastAPI / Starlette által használt + +* uvicorn - Szerverekhez amíg betöltik és szolgáltatják az applikációdat. +* orjson - Követelmény ha `ORJSONResponse`-t akarsz használni. + +Ezeket mind telepítheted a `pip install "fastapi[all]"` paranccsal. + +## Licensz +Ez a projekt az MIT license, licensz alatt fut diff --git a/docs/hu/mkdocs.yml b/docs/hu/mkdocs.yml new file mode 100644 index 0000000000000..de18856f445aa --- /dev/null +++ b/docs/hu/mkdocs.yml @@ -0,0 +1 @@ +INHERIT: ../en/mkdocs.yml diff --git a/docs/ja/docs/index.md b/docs/ja/docs/index.md index f340fdb87ebc5..22c31e7ca926e 100644 --- a/docs/ja/docs/index.md +++ b/docs/ja/docs/index.md @@ -24,7 +24,7 @@ --- -FastAPI は、Pythonの標準である型ヒントに基づいてPython 3.6 以降でAPI を構築するための、モダンで、高速(高パフォーマンス)な、Web フレームワークです。 +FastAPI は、Pythonの標準である型ヒントに基づいてPython 3.8 以降でAPI を構築するための、モダンで、高速(高パフォーマンス)な、Web フレームワークです。 主な特徴: @@ -317,7 +317,7 @@ def update_item(item_id: int, item: Item): 新しい構文や特定のライブラリのメソッドやクラスなどを覚える必要はありません。 -単なる標準的な**3.6 以降の Python**です。 +単なる標準的な**3.8 以降の Python**です。 例えば、`int`の場合: diff --git a/docs/ja/docs/python-types.md b/docs/ja/docs/python-types.md new file mode 100644 index 0000000000000..bbfef2adf1853 --- /dev/null +++ b/docs/ja/docs/python-types.md @@ -0,0 +1,315 @@ +# Pythonの型の紹介 + +**Python 3.6以降** では「型ヒント」オプションがサポートされています。 + +これらの **"型ヒント"** は変数のを宣言することができる新しい構文です。(Python 3.6以降) + +変数に型を宣言することでエディターやツールがより良いサポートを提供することができます。 + +ここではPythonの型ヒントについての **クイックチュートリアル/リフレッシュ** で、**FastAPI**でそれらを使用するために必要な最低限のことだけをカバーしています。...実際には本当に少ないです。 + +**FastAPI** はすべてこれらの型ヒントに基づいており、多くの強みと利点を与えてくれます。 + +しかしたとえまったく **FastAPI** を使用しない場合でも、それらについて少し学ぶことで利点を得ることができるでしょう。 + +!!! note "備考" + もしあなたがPythonの専門家で、すでに型ヒントについてすべて知っているのであれば、次の章まで読み飛ばしてください。 + +## 動機 + +簡単な例から始めてみましょう: + +```Python +{!../../../docs_src/python_types/tutorial001.py!} +``` + +このプログラムを実行すると以下が出力されます: + +``` +John Doe +``` + +この関数は以下のようなことを行います: + +* `first_name`と`last_name`を取得します。 +* `title()`を用いて、それぞれの最初の文字を大文字に変換します。 +* 真ん中にスペースを入れて連結します。 + +```Python hl_lines="2" +{!../../../docs_src/python_types/tutorial001.py!} +``` + +### 編集 + +これはとても簡単なプログラムです。 + +しかし、今、あなたがそれを一から書いていたと想像してみてください。 + +パラメータの準備ができていたら、そのとき、関数の定義を始めていたことでしょう... + +しかし、そうすると「最初の文字を大文字に変換するあのメソッド」を呼び出す必要があります。 + +それは`upper`でしたか?`uppercase`でしたか?それとも`first_uppercase`?または`capitalize`? + +そして、古くからプログラマーの友人であるエディタで自動補完を試してみます。 + +関数の最初のパラメータ`first_name`を入力し、ドット(`.`)を入力してから、`Ctrl+Space`を押すと補完が実行されます。 + +しかし、悲しいことに、これはなんの役にも立ちません: + + + +### 型の追加 + +先ほどのコードから一行変更してみましょう。 + +以下の関数のパラメータ部分を: + +```Python + first_name, last_name +``` + +以下へ変更します: + +```Python + first_name: str, last_name: str +``` + +これだけです。 + +それが「型ヒント」です: + +```Python hl_lines="1" +{!../../../docs_src/python_types/tutorial002.py!} +``` + +これは、以下のようにデフォルト値を宣言するのと同じではありません: + +```Python + first_name="john", last_name="doe" +``` + +それとは別物です。 + +イコール(`=`)ではなく、コロン(`:`)を使用します。 + +そして、通常、型ヒントを追加しても、それらがない状態と起こることは何も変わりません。 + +しかし今、あなたが再びその関数を作成している最中に、型ヒントを使っていると想像してみて下さい。 + +同じタイミングで`Ctrl+Space`で自動補完を実行すると、以下のようになります: + + + +これであれば、あなたは「ベルを鳴らす」一つを見つけるまで、オプションを見て、スクロールすることができます: + + + +## より強い動機 + +この関数を見てください。すでに型ヒントを持っています: + +```Python hl_lines="1" +{!../../../docs_src/python_types/tutorial003.py!} +``` + +エディタは変数の型を知っているので、補完だけでなく、エラーチェックをすることもできます。 + + + +これで`age`を`str(age)`で文字列に変換して修正する必要があることがわかります: + +```Python hl_lines="2" +{!../../../docs_src/python_types/tutorial004.py!} +``` + +## 型の宣言 + +関数のパラメータとして、型ヒントを宣言している主な場所を確認しました。 + +これは **FastAPI** で使用する主な場所でもあります。 + +### 単純な型 + +`str`だけでなく、Pythonの標準的な型すべてを宣言することができます。 + +例えば、以下を使用可能です: + +* `int` +* `float` +* `bool` +* `bytes` + +```Python hl_lines="1" +{!../../../docs_src/python_types/tutorial005.py!} +``` + +### 型パラメータを持つジェネリック型 + +データ構造の中には、`dict`、`list`、`set`、そして`tuple`のように他の値を含むことができるものがあります。また内部の値も独自の型を持つことができます。 + +これらの型や内部の型を宣言するには、Pythonの標準モジュール`typing`を使用します。 + +これらの型ヒントをサポートするために特別に存在しています。 + +#### `List` + +例えば、`str`の`list`の変数を定義してみましょう。 + +`typing`から`List`をインポートします(大文字の`L`を含む): + +```Python hl_lines="1" +{!../../../docs_src/python_types/tutorial006.py!} +``` + +同じようにコロン(`:`)の構文で変数を宣言します。 + +型として、`List`を入力します。 + +リストはいくつかの内部の型を含む型なので、それらを角括弧で囲んでいます。 + +```Python hl_lines="4" +{!../../../docs_src/python_types/tutorial006.py!} +``` + +!!! tip "豆知識" + 角括弧内の内部の型は「型パラメータ」と呼ばれています。 + + この場合、`str`は`List`に渡される型パラメータです。 + +つまり: 変数`items`は`list`であり、このリストの各項目は`str`です。 + +そうすることで、エディタはリストの項目を処理している間にもサポートを提供できます。 + + + +タイプがなければ、それはほぼ不可能です。 + +変数`item`はリスト`items`の要素の一つであることに注意してください。 + +それでも、エディタはそれが`str`であることを知っていて、そのためのサポートを提供しています。 + +#### `Tuple` と `Set` + +`tuple`と`set`の宣言も同様です: + +```Python hl_lines="1 4" +{!../../../docs_src/python_types/tutorial007.py!} +``` + +つまり: + +* 変数`items_t`は`int`、`int`、`str`の3つの項目を持つ`tuple`です + +* 変数`items_s`はそれぞれの項目が`bytes`型である`set`です。 + +#### `Dict` + +`dict`を宣言するためには、カンマ区切りで2つの型パラメータを渡します。 + +最初の型パラメータは`dict`のキーです。 + +2番目の型パラメータは`dict`の値です。 + +```Python hl_lines="1 4" +{!../../../docs_src/python_types/tutorial008.py!} +``` + +つまり: + +* 変数`prices`は`dict`であり: + * この`dict`のキーは`str`型です。(つまり、各項目の名前) + * この`dict`の値は`float`型です。(つまり、各項目の価格) + +#### `Optional` + +また、`Optional`を使用して、変数が`str`のような型を持つことを宣言することもできますが、それは「オプション」であり、`None`にすることもできます。 + +```Python hl_lines="1 4" +{!../../../docs_src/python_types/tutorial009.py!} +``` + +ただの`str`の代わりに`Optional[str]`を使用することで、エディタは値が常に`str`であると仮定している場合に実際には`None`である可能性があるエラーを検出するのに役立ちます。 + +#### ジェネリック型 + +以下のように角括弧で型パラメータを取る型を: + +* `List` +* `Tuple` +* `Set` +* `Dict` +* `Optional` +* ...など + +**ジェネリック型** または **ジェネリクス** と呼びます。 + +### 型としてのクラス + +変数の型としてクラスを宣言することもできます。 + +例えば、`Person`クラスという名前のクラスがあるとしましょう: + +```Python hl_lines="1 2 3" +{!../../../docs_src/python_types/tutorial010.py!} +``` + +変数の型を`Person`として宣言することができます: + +```Python hl_lines="6" +{!../../../docs_src/python_types/tutorial010.py!} +``` + +そして、再び、すべてのエディタのサポートを得ることができます: + + + +## Pydanticのモデル + +Pydantic はデータ検証を行うためのPythonライブラリです。 + +データの「形」を属性付きのクラスとして宣言します。 + +そして、それぞれの属性は型を持ちます。 + +さらに、いくつかの値を持つクラスのインスタンスを作成すると、その値を検証し、適切な型に変換して(もしそうであれば)全てのデータを持つオブジェクトを提供してくれます。 + +また、その結果のオブジェクトですべてのエディタのサポートを受けることができます。 + +Pydanticの公式ドキュメントから引用: + +```Python +{!../../../docs_src/python_types/tutorial011.py!} +``` + +!!! info "情報" + Pydanticについてより学びたい方はドキュメントを参照してください. + +**FastAPI** はすべてPydanticをベースにしています。 + +すべてのことは[チュートリアル - ユーザーガイド](tutorial/index.md){.internal-link target=_blank}で実際に見ることができます。 + +## **FastAPI**での型ヒント + +**FastAPI** はこれらの型ヒントを利用していくつかのことを行います。 + +**FastAPI** では型ヒントを使って型パラメータを宣言すると以下のものが得られます: + +* **エディタサポート**. +* **型チェック**. + +...そして **FastAPI** は同じように宣言をすると、以下のことを行います: + +* **要件の定義**: リクエストパスパラメータ、クエリパラメータ、ヘッダー、ボディ、依存関係などから要件を定義します。 +* **データの変換**: リクエストのデータを必要な型に変換します。 +* **データの検証**: リクエストごとに: + * データが無効な場合にクライアントに返される **自動エラー** を生成します。 +* **ドキュメント** OpenAPIを使用したAPI: + * 自動的に対話型ドキュメントのユーザーインターフェイスで使用されます。 + +すべてが抽象的に聞こえるかもしれません。心配しないでください。 この全ての動作は [チュートリアル - ユーザーガイド](tutorial/index.md){.internal-link target=_blank}で見ることができます。 + +重要なのは、Pythonの標準的な型を使うことで、(クラスやデコレータなどを追加するのではなく)1つの場所で **FastAPI** が多くの作業を代わりにやってくれているということです。 + +!!! info "情報" + すでにすべてのチュートリアルを終えて、型についての詳細を見るためにこのページに戻ってきた場合は、`mypy`のチートシートを参照してください diff --git a/docs/ja/docs/tutorial/background-tasks.md b/docs/ja/docs/tutorial/background-tasks.md new file mode 100644 index 0000000000000..6094c370fde65 --- /dev/null +++ b/docs/ja/docs/tutorial/background-tasks.md @@ -0,0 +1,94 @@ +# バックグラウンドタスク + +レスポンスを返した *後に* 実行されるバックグラウンドタスクを定義できます。 + +これは、リクエスト後に処理を開始する必要があるが、クライアントがレスポンスを受け取る前に処理を終える必要のない操作に役立ちます。 + +これには、たとえば次のものが含まれます。 + +* 作業実行後のメール通知: + * メールサーバーへの接続とメールの送信は「遅い」(数秒) 傾向があるため、すぐにレスポンスを返し、バックグラウンドでメール通知ができます。 +* データ処理: + * たとえば、時間のかかる処理を必要とするファイル受信時には、「受信済み」(HTTP 202) のレスポンスを返し、バックグラウンドで処理できます。 + +## `BackgroundTasks` の使用 + +まず初めに、`BackgroundTasks` をインポートし、` BackgroundTasks` の型宣言と共に、*path operation 関数* のパラメーターを定義します: + +```Python hl_lines="1 13" +{!../../../docs_src/background_tasks/tutorial001.py!} +``` + +**FastAPI** は、`BackgroundTasks` 型のオブジェクトを作成し、そのパラメーターに渡します。 + +## タスク関数の作成 + +バックグラウンドタスクとして実行される関数を作成します。 + +これは、パラメーターを受け取ることができる単なる標準的な関数です。 + +これは `async def` または通常の `def` 関数であり、**FastAPI** はこれを正しく処理します。 + +ここで、タスク関数はファイル書き込みを実行します (メール送信のシミュレーション)。 + +また、書き込み操作では `async` と `await` を使用しないため、通常の `def` で関数を定義します。 + +```Python hl_lines="6-9" +{!../../../docs_src/background_tasks/tutorial001.py!} +``` + +## バックグラウンドタスクの追加 + +*path operations 関数* 内で、`.add_task()` メソッドを使用してタスク関数を *background tasks* オブジェクトに渡します。 + +```Python hl_lines="14" +{!../../../docs_src/background_tasks/tutorial001.py!} +``` + +`.add_task()` は以下の引数を受け取ります: + +* バックグラウンドで実行されるタスク関数 (`write_notification`)。 +* タスク関数に順番に渡す必要のある引数の列 (`email`)。 +* タスク関数に渡す必要のあるキーワード引数 (`message="some notification"`)。 + +## 依存性注入 + +`BackgroundTasks` の使用は依存性注入システムでも機能し、様々な階層 (*path operations 関数*、依存性 (依存可能性)、サブ依存性など) で `BackgroundTasks` 型のパラメーターを宣言できます。 + +**FastAPI** は、それぞれの場合の処理​​方法と同じオブジェクトの再利用方法を知っているため、すべてのバックグラウンドタスクがマージされ、バックグラウンドで後で実行されます。 + +```Python hl_lines="13 15 22 25" +{!../../../docs_src/background_tasks/tutorial002.py!} +``` + +この例では、レスポンスが送信された *後* にメッセージが `log.txt` ファイルに書き込まれます。 + +リクエストにクエリがあった場合、バックグラウンドタスクでログに書き込まれます。 + +そして、*path operations 関数* で生成された別のバックグラウンドタスクは、`email` パスパラメータを使用してメッセージを書き込みます。 + +## 技術的な詳細 + +`BackgroundTasks` クラスは、`starlette.background`から直接取得されます。 + +これは、FastAPI に直接インポート/インクルードされるため、`fastapi` からインポートできる上に、`starlette.background`から別の `BackgroundTask` (末尾に `s` がない) を誤ってインポートすることを回避できます。 + +`BackgroundTasks`のみを使用することで (`BackgroundTask` ではなく)、`Request` オブジェクトを直接使用する場合と同様に、それを *path operations 関数* パラメーターとして使用し、**FastAPI** に残りの処理を任せることができます。 + +それでも、FastAPI で `BackgroundTask` を単独で使用することは可能ですが、コード内でオブジェクトを作成し、それを含むStarlette `Response` を返す必要があります。 + +詳細については、バックグラウンドタスクに関する Starlette の公式ドキュメントを参照して下さい。 + +## 警告 + +大量のバックグラウンド計算が必要であり、必ずしも同じプロセスで実行する必要がない場合 (たとえば、メモリや変数などを共有する必要がない場合)、Celery のようなより大きな他のツールを使用するとメリットがあるかもしれません。 + +これらは、より複雑な構成、RabbitMQ や Redis などのメッセージ/ジョブキューマネージャーを必要とする傾向がありますが、複数のプロセス、特に複数のサーバーでバックグラウンドタスクを実行できます。 + +例を確認するには、[Project Generators](../project-generation.md){.internal-link target=_blank} を参照してください。これらにはすべて、Celery が構築済みです。 + +ただし、同じ **FastAPI** アプリから変数とオブジェクトにアクセスする必要がある場合、または小さなバックグラウンドタスク (電子メール通知の送信など) を実行する必要がある場合は、単に `BackgroundTasks` を使用できます。 + +## まとめ + +`BackgroundTasks` をインポートして、*path operations 関数* や依存関係のパラメータに `BackgroundTasks`を使用し、バックグラウンドタスクを追加して下さい。 diff --git a/docs/ja/docs/tutorial/body-fields.md b/docs/ja/docs/tutorial/body-fields.md new file mode 100644 index 0000000000000..8f01e821624d0 --- /dev/null +++ b/docs/ja/docs/tutorial/body-fields.md @@ -0,0 +1,48 @@ +# ボディ - フィールド + +`Query`や`Path`、`Body`を使って *path operation関数* のパラメータに追加のバリデーションやメタデータを宣言するのと同じように、Pydanticの`Field`を使ってPydanticモデルの内部でバリデーションやメタデータを宣言することができます。 + +## `Field`のインポート + +まず、以下のようにインポートします: + +```Python hl_lines="4" +{!../../../docs_src/body_fields/tutorial001.py!} +``` + +!!! warning "注意" + `Field`は他の全てのもの(`Query`、`Path`、`Body`など)とは違い、`fastapi`からではなく、`pydantic`から直接インポートされていることに注意してください。 + +## モデルの属性の宣言 + +以下のように`Field`をモデルの属性として使用することができます: + +```Python hl_lines="11 12 13 14" +{!../../../docs_src/body_fields/tutorial001.py!} +``` + +`Field`は`Query`や`Path`、`Body`と同じように動作し、全く同様のパラメータなどを持ちます。 + +!!! note "技術詳細" + 実際には次に見る`Query`や`Path`などは、共通の`Param`クラスのサブクラスのオブジェクトを作成しますが、それ自体はPydanticの`FieldInfo`クラスのサブクラスです。 + + また、Pydanticの`Field`は`FieldInfo`のインスタンスも返します。 + + `Body`は`FieldInfo`のサブクラスのオブジェクトを直接返すこともできます。そして、他にも`Body`クラスのサブクラスであるものがあります。 + + `fastapi`から`Query`や`Path`などをインポートする場合、これらは実際には特殊なクラスを返す関数であることに注意してください。 + +!!! tip "豆知識" + 型、デフォルト値、`Field`を持つ各モデルの属性が、`Path`や`Query`、`Body`の代わりに`Field`を持つ、*path operation 関数の*パラメータと同じ構造になっていることに注目してください。 + +## 追加情報の追加 + +追加情報は`Field`や`Query`、`Body`などで宣言することができます。そしてそれは生成されたJSONスキーマに含まれます。 + +後に例を用いて宣言を学ぶ際に、追加情報を句悪方法を学べます。 + +## まとめ + +Pydanticの`Field`を使用して、モデルの属性に追加のバリデーションやメタデータを宣言することができます。 + +追加のキーワード引数を使用して、追加のJSONスキーマのメタデータを渡すこともできます。 diff --git a/docs/ja/docs/tutorial/body-multiple-params.md b/docs/ja/docs/tutorial/body-multiple-params.md new file mode 100644 index 0000000000000..2ba10c583e1b7 --- /dev/null +++ b/docs/ja/docs/tutorial/body-multiple-params.md @@ -0,0 +1,169 @@ +# ボディ - 複数のパラメータ + +これまで`Path`と`Query`をどう使うかを見てきましたが、リクエストボディの宣言のより高度な使い方を見てみましょう。 + +## `Path`、`Query`とボディパラメータを混ぜる + +まず、もちろん、`Path`と`Query`とリクエストボディのパラメータの宣言は自由に混ぜることができ、 **FastAPI** は何をするべきかを知っています。 + +また、デフォルトの`None`を設定することで、ボディパラメータをオプションとして宣言することもできます: + +```Python hl_lines="19 20 21" +{!../../../docs_src/body_multiple_params/tutorial001.py!} +``` + +!!! note "備考" + この場合、ボディから取得する`item`はオプションであることに注意してください。デフォルト値は`None`です。 + +## 複数のボディパラメータ + +上述の例では、*path operations*は`item`の属性を持つ以下のようなJSONボディを期待していました: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 +} +``` + +しかし、`item`と`user`のように複数のボディパラメータを宣言することもできます: + +```Python hl_lines="22" +{!../../../docs_src/body_multiple_params/tutorial002.py!} +``` + +この場合、**FastAPI**は関数内に複数のボディパラメータ(Pydanticモデルである2つのパラメータ)があることに気付きます。 + +そのため、パラメータ名をボディのキー(フィールド名)として使用し、以下のようなボディを期待しています: + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + }, + "user": { + "username": "dave", + "full_name": "Dave Grohl" + } +} +``` + +!!! note "備考" + 以前と同じように`item`が宣言されていたにもかかわらず、`item`はキー`item`を持つボディの内部にあることが期待されていることに注意してください。 + +**FastAPI** はリクエストから自動で変換を行い、パラメータ`item`が特定の内容を受け取り、`user`も同じように特定の内容を受け取ります。 + +複合データの検証を行い、OpenAPIスキーマや自動ドキュメントのように文書化してくれます。 + +## ボディ内の単数値 + +クエリとパスパラメータの追加データを定義するための `Query` と `Path` があるのと同じように、 **FastAPI** は同等の `Body` を提供します。 + +例えば、前のモデルを拡張して、同じボディに `item` と `user` の他にもう一つのキー `importance` を入れたいと決めることができます。 + +単数値なのでそのまま宣言すると、**FastAPI** はそれがクエリパラメータであるとみなします。 + +しかし、`Body`を使用して、**FastAPI** に別のボディキーとして扱うように指示することができます: + + +```Python hl_lines="23" +{!../../../docs_src/body_multiple_params/tutorial003.py!} +``` + +この場合、**FastAPI** は以下のようなボディを期待します: + + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + }, + "user": { + "username": "dave", + "full_name": "Dave Grohl" + }, + "importance": 5 +} +``` + +繰り返しになりますが、データ型の変換、検証、文書化などを行います。 + +## 複数のボディパラメータとクエリ + +もちろん、ボディパラメータに加えて、必要に応じて追加のクエリパラメータを宣言することもできます。 + +デフォルトでは、単数値はクエリパラメータとして解釈されるので、明示的に `Query` を追加する必要はありません。 + +```Python +q: str = None +``` + +以下において: + +```Python hl_lines="27" +{!../../../docs_src/body_multiple_params/tutorial004.py!} +``` + +!!! info "情報" + `Body`もまた、後述する `Query` や `Path` などと同様に、すべての検証パラメータとメタデータパラメータを持っています。 + + +## 単一のボディパラメータの埋め込み + +Pydanticモデル`Item`のボディパラメータ`item`を1つだけ持っているとしましょう。 + +デフォルトでは、**FastAPI**はそのボディを直接期待します。 + +しかし、追加のボディパラメータを宣言したときのように、キー `item` を持つ JSON とその中のモデルの内容を期待したい場合は、特別な `Body` パラメータ `embed` を使うことができます: + +```Python +item: Item = Body(..., embed=True) +``` + +以下において: + +```Python hl_lines="17" +{!../../../docs_src/body_multiple_params/tutorial005.py!} +``` + +この場合、**FastAPI** は以下のようなボディを期待します: + +```JSON hl_lines="2" +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + } +} +``` + +以下の代わりに: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 +} +``` + +## まとめ + +リクエストが単一のボディしか持てない場合でも、*path operation関数*に複数のボディパラメータを追加することができます。 + +しかし、**FastAPI** はそれを処理し、関数内の正しいデータを与え、*path operation*内の正しいスキーマを検証し、文書化します。 + +また、ボディの一部として受け取る単数値を宣言することもできます。 + +また、単一のパラメータしか宣言されていない場合でも、ボディをキーに埋め込むように **FastAPI** に指示することができます。 diff --git a/docs/ja/docs/tutorial/body-nested-models.md b/docs/ja/docs/tutorial/body-nested-models.md new file mode 100644 index 0000000000000..7f916c47a1079 --- /dev/null +++ b/docs/ja/docs/tutorial/body-nested-models.md @@ -0,0 +1,244 @@ +# ボディ - ネストされたモデル + +**FastAPI** を使用すると、深くネストされた任意のモデルを定義、検証、文書化、使用することができます(Pydanticのおかげです)。 + +## リストのフィールド + +属性をサブタイプとして定義することができます。例えば、Pythonの`list`は以下のように定義できます: + +```Python hl_lines="12" +{!../../../docs_src/body_nested_models/tutorial001.py!} +``` + +これにより、各項目の型は宣言されていませんが、`tags`はある項目のリストになります。 + +## タイプパラメータを持つリストのフィールド + +しかし、Pythonには型や「タイプパラメータ」を使ってリストを宣言する方法があります: + +### typingの`List`をインポート + +まず、Pythonの標準の`typing`モジュールから`List`をインポートします: + +```Python hl_lines="1" +{!../../../docs_src/body_nested_models/tutorial002.py!} +``` + +### タイプパラメータを持つ`List`の宣言 + +`list`や`dict`、`tuple`のようなタイプパラメータ(内部の型)を持つ型を宣言するには: + +* `typing`モジュールからそれらをインストールします。 +* 角括弧(`[`と`]`)を使って「タイプパラメータ」として内部の型を渡します: + +```Python +from typing import List + +my_list: List[str] +``` + +型宣言の標準的なPythonの構文はこれだけです。 + +内部の型を持つモデルの属性にも同じ標準の構文を使用してください。 + +そのため、以下の例では`tags`を具体的な「文字列のリスト」にすることができます: + +```Python hl_lines="14" +{!../../../docs_src/body_nested_models/tutorial002.py!} +``` + +## セット型 + +しかし、よく考えてみると、タグは繰り返すべきではなく、おそらくユニークな文字列になるのではないかと気付いたとします。 + +そして、Pythonにはユニークな項目のセットのための特別なデータ型`set`があります。 + +そのため、以下のように、`Set`をインポートして`str`の`set`として`tags`を宣言することができます: + +```Python hl_lines="1 14" +{!../../../docs_src/body_nested_models/tutorial003.py!} +``` + +これを使えば、データが重複しているリクエストを受けた場合でも、ユニークな項目のセットに変換されます。 + +そして、そのデータを出力すると、たとえソースに重複があったとしても、固有の項目のセットとして出力されます。 + +また、それに応じて注釈をつけたり、文書化したりします。 + +## ネストされたモデル + +Pydanticモデルの各属性には型があります。 + +しかし、その型はそれ自体が別のPydanticモデルである可能性があります。 + +そのため、特定の属性名、型、バリデーションを指定して、深くネストしたJSON`object`を宣言することができます。 + +すべては、任意のネストにされています。 + +### サブモデルの定義 + +例えば、`Image`モデルを定義することができます: + +```Python hl_lines="9 10 11" +{!../../../docs_src/body_nested_models/tutorial004.py!} +``` + +### サブモデルを型として使用 + +そして、それを属性の型として使用することができます: + +```Python hl_lines="20" +{!../../../docs_src/body_nested_models/tutorial004.py!} +``` + +これは **FastAPI** が以下のようなボディを期待することを意味します: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2, + "tags": ["rock", "metal", "bar"], + "image": { + "url": "http://example.com/baz.jpg", + "name": "The Foo live" + } +} +``` + +繰り返しになりますが、**FastAPI** を使用して、その宣言を行うだけで以下のような恩恵を受けられます: + +* ネストされたモデルでも対応可能なエディタのサポート(補完など) +* データ変換 +* データの検証 +* 自動文書化 + +## 特殊な型とバリデーション + +`str`や`int`、`float`のような通常の単数型の他にも、`str`を継承したより複雑な単数型を使うこともできます。 + +すべてのオプションをみるには、Pydanticのエキゾチック な型のドキュメントを確認してください。次の章でいくつかの例をみることができます。 + +例えば、`Image`モデルのように`url`フィールドがある場合、`str`の代わりにPydanticの`HttpUrl`を指定することができます: + +```Python hl_lines="4 10" +{!../../../docs_src/body_nested_models/tutorial005.py!} +``` + +文字列は有効なURLであることが確認され、そのようにJSONスキーマ・OpenAPIで文書化されます。 + +## サブモデルのリストを持つ属性 + +Pydanticモデルを`list`や`set`などのサブタイプとして使用することもできます: + +```Python hl_lines="20" +{!../../../docs_src/body_nested_models/tutorial006.py!} +``` + +これは、次のようなJSONボディを期待します(変換、検証、ドキュメントなど): + +```JSON hl_lines="11" +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2, + "tags": [ + "rock", + "metal", + "bar" + ], + "images": [ + { + "url": "http://example.com/baz.jpg", + "name": "The Foo live" + }, + { + "url": "http://example.com/dave.jpg", + "name": "The Baz" + } + ] +} +``` + +!!! info "情報" + `images`キーが画像オブジェクトのリストを持つようになったことに注目してください。 + +## 深くネストされたモデル + +深くネストされた任意のモデルを定義することができます: + +```Python hl_lines="9 14 20 23 27" +{!../../../docs_src/body_nested_models/tutorial007.py!} +``` + +!!! info "情報" + `Offer`は`Item`のリストであり、オプションの`Image`のリストを持っていることに注目してください。 + +## 純粋なリストのボディ + +期待するJSONボディのトップレベルの値がJSON`array`(Pythonの`list`)であれば、Pydanticモデルと同じように、関数のパラメータで型を宣言することができます: + +```Python +images: List[Image] +``` + +以下のように: + +```Python hl_lines="15" +{!../../../docs_src/body_nested_models/tutorial008.py!} +``` + +## あらゆる場所でのエディタサポート + +エディタのサポートもどこでも受けることができます。 + +以下のようにリストの中の項目でも: + + + +Pydanticモデルではなく、`dict`を直接使用している場合はこのようなエディタのサポートは得られません。 + +しかし、それらについて心配する必要はありません。入力された辞書は自動的に変換され、出力も自動的にJSONに変換されます。 + +## 任意の`dict`のボディ + +また、ある型のキーと別の型の値を持つ`dict`としてボディを宣言することもできます。 + +有効なフィールド・属性名を事前に知る必要がありません(Pydanticモデルの場合のように)。 + +これは、まだ知らないキーを受け取りたいときに便利だと思います。 + +--- + +他にも、`int`のように他の型のキーを持ちたい場合などに便利です。 + +それをここで見ていきましょう。 + +この場合、`int`のキーと`float`の値を持つものであれば、どんな`dict`でも受け入れることができます: + +```Python hl_lines="15" +{!../../../docs_src/body_nested_models/tutorial009.py!} +``` + +!!! tip "豆知識" + JSONはキーとして`str`しかサポートしていないことに注意してください。 + + しかしPydanticには自動データ変換機能があります。 + + これは、APIクライアントがキーとして文字列しか送信できなくても、それらの文字列に純粋な整数が含まれている限り、Pydanticが変換して検証することを意味します。 + + そして、`weights`として受け取る`dict`は、実際には`int`のキーと`float`の値を持つことになります。 + +## まとめ + +**FastAPI** を使用すると、Pydanticモデルが提供する最大限の柔軟性を持ちながら、コードをシンプルに短く、エレガントに保つことができます。 + +以下のような利点があります: + +* エディタのサポート(どこでも補完!) +* データ変換(別名:構文解析・シリアライズ) +* データの検証 +* スキーマ文書 +* 自動文書化 diff --git a/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md new file mode 100644 index 0000000000000..5c150d00c50b7 --- /dev/null +++ b/docs/ja/docs/tutorial/dependencies/classes-as-dependencies.md @@ -0,0 +1,191 @@ +# 依存関係としてのクラス + +**依存性注入** システムを深く掘り下げる前に、先ほどの例をアップグレードしてみましょう。 + +## 前の例の`dict` + +前の例では、依存関係("dependable")から`dict`を返していました: + +```Python hl_lines="9" +{!../../../docs_src/dependencies/tutorial001.py!} +``` + +しかし、*path operation関数*のパラメータ`commons`に`dict`が含まれています。 + +また、エディタは`dict`のキーと値の型を知ることができないため、多くのサポート(補完のような)を提供することができません。 + +もっとうまくやれるはずです...。 + +## 依存関係を作るもの + +これまでは、依存関係が関数として宣言されているのを見てきました。 + +しかし、依存関係を定義する方法はそれだけではありません(その方が一般的かもしれませんが)。 + +重要なのは、依存関係が「呼び出し可能」なものであることです。 + +Pythonにおける「**呼び出し可能**」とは、Pythonが関数のように「呼び出す」ことができるものを指します。 + +そのため、`something`オブジェクト(関数ではないかもしれませんが)を持っていて、それを次のように「呼び出す」(実行する)ことができるとします: + +```Python +something() +``` + +または + +```Python +something(some_argument, some_keyword_argument="foo") +``` + +これを「呼び出し可能」なものと呼びます。 + +## 依存関係としてのクラス + +Pythonのクラスのインスタンスを作成する際に、同じ構文を使用していることに気づくかもしれません。 + +例えば: + +```Python +class Cat: + def __init__(self, name: str): + self.name = name + + +fluffy = Cat(name="Mr Fluffy") +``` + +この場合、`fluffy`は`Cat`クラスのインスタンスです。 + +そして`fluffy`を作成するために、`Cat`を「呼び出している」ことになります。 + +そのため、Pythonのクラスもまた「呼び出し可能」です。 + +そして、**FastAPI** では、Pythonのクラスを依存関係として使用することができます。 + +FastAPIが実際にチェックしているのは、それが「呼び出し可能」(関数、クラス、その他なんでも)であり、パラメータが定義されているかどうかということです。 + +**FastAPI** の依存関係として「呼び出し可能なもの」を渡すと、その「呼び出し可能なもの」のパラメータを解析し、サブ依存関係も含めて、*path operation関数*のパラメータと同じように処理します。 + +それは、パラメータが全くない呼び出し可能なものにも適用されます。パラメータのない*path operation関数*と同じように。 + +そこで、上で紹介した依存関係の`common_parameters`を`CommonQueryParams`クラスに変更します: + +```Python hl_lines="11 12 13 14 15" +{!../../../docs_src/dependencies/tutorial002.py!} +``` + +クラスのインスタンスを作成するために使用される`__init__`メソッドに注目してください: + +```Python hl_lines="12" +{!../../../docs_src/dependencies/tutorial002.py!} +``` + +...以前の`common_parameters`と同じパラメータを持っています: + +```Python hl_lines="8" +{!../../../docs_src/dependencies/tutorial001.py!} +``` + +これらのパラメータは **FastAPI** が依存関係を「解決」するために使用するものです。 + +どちらの場合も以下を持っています: + +* オプショナルの`q`クエリパラメータ。 +* `skip`クエリパラメータ、デフォルトは`0`。 +* `limit`クエリパラメータ、デフォルトは`100`。 + +どちらの場合も、データは変換され、検証され、OpenAPIスキーマなどで文書化されます。 + +## 使用 + +これで、このクラスを使用して依存関係を宣言することができます。 + +```Python hl_lines="19" +{!../../../docs_src/dependencies/tutorial002.py!} +``` + +**FastAPI** は`CommonQueryParams`クラスを呼び出します。これにより、そのクラスの「インスタンス」が作成され、インスタンスはパラメータ`commons`として関数に渡されます。 + +## 型注釈と`Depends` + +上のコードでは`CommonQueryParams`を2回書いていることに注目してください: + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +以下にある最後の`CommonQueryParams`: + +```Python +... = Depends(CommonQueryParams) +``` + +...は、**FastAPI** が依存関係を知るために実際に使用するものです。 + +そこからFastAPIが宣言されたパラメータを抽出し、それが実際にFastAPIが呼び出すものです。 + +--- + +この場合、以下にある最初の`CommonQueryParams`: + +```Python +commons: CommonQueryParams ... +``` + +...は **FastAPI** に対して特別な意味をもちません。FastAPIはデータ変換や検証などには使用しません(それらのためには`= Depends(CommonQueryParams)`を使用しています)。 + +実際には以下のように書けばいいだけです: + +```Python +commons = Depends(CommonQueryParams) +``` + +以下にあるように: + +```Python hl_lines="19" +{!../../../docs_src/dependencies/tutorial003.py!} +``` + +しかし、型を宣言することは推奨されています。そうすれば、エディタは`commons`のパラメータとして何が渡されるかを知ることができ、コードの補完や型チェックなどを行うのに役立ちます: + + + +## ショートカット + +しかし、ここでは`CommonQueryParams`を2回書くというコードの繰り返しが発生していることがわかります: + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +依存関係が、クラス自体のインスタンスを作成するために**FastAPI**が「呼び出す」*特定の*クラスである場合、**FastAPI** はこれらのケースのショートカットを提供しています。 + +それらの具体的なケースについては以下のようにします: + +以下のように書く代わりに: + +```Python +commons: CommonQueryParams = Depends(CommonQueryParams) +``` + +...以下のように書きます: + +```Python +commons: CommonQueryParams = Depends() +``` + +パラメータの型として依存関係を宣言し、`Depends()`の中でパラメータを指定せず、`Depends()`をその関数のパラメータの「デフォルト」値(`=`のあとの値)として使用することで、`Depends(CommonQueryParams)`の中でクラス全体を*もう一度*書かなくてもよくなります。 + +同じ例では以下のようになります: + +```Python hl_lines="19" +{!../../../docs_src/dependencies/tutorial004.py!} +``` + +...そして **FastAPI** は何をすべきか知っています。 + +!!! tip "豆知識" + 役に立つというよりも、混乱するようであれば無視してください。それをする*必要*はありません。 + + それは単なるショートカットです。なぜなら **FastAPI** はコードの繰り返しを最小限に抑えることに気を使っているからです。 diff --git a/docs/ja/docs/tutorial/dependencies/index.md b/docs/ja/docs/tutorial/dependencies/index.md new file mode 100644 index 0000000000000..ec563a16d7219 --- /dev/null +++ b/docs/ja/docs/tutorial/dependencies/index.md @@ -0,0 +1,209 @@ +# 依存関係 - 最初のステップ + +** FastAPI** は非常に強力でありながら直感的な **依存性注入** システムを持っています。 + +それは非常にシンプルに使用できるように設計されており、開発者が他のコンポーネント **FastAPI** と統合するのが非常に簡単になるように設計されています。 + +## 「依存性注入」とは + +**「依存性注入」** とは、プログラミングにおいて、コード(この場合は、*path operation関数*)が動作したり使用したりするために必要なもの(「依存関係」)を宣言する方法があることを意味します: + +そして、そのシステム(この場合は、**FastAPI**)は、必要な依存関係をコードに提供するために必要なことは何でも行います(依存関係を「注入」します)。 + +これは以下のようなことが必要な時にとても便利です: + +* ロジックを共有している。(同じコードロジックを何度も繰り返している)。 +* データベース接続を共有する。 +* セキュリティ、認証、ロール要件などを強制する。 +* そのほかにも多くのこと... + +これらすべてを、コードの繰り返しを最小限に抑えながら行います。 + +## 最初のステップ + +非常にシンプルな例を見てみましょう。あまりにもシンプルなので、今のところはあまり参考にならないでしょう。 + +しかし、この方法では **依存性注入** システムがどのように機能するかに焦点を当てることができます。 + +### 依存関係の作成 + +まずは依存関係に注目してみましょう。 + +以下のように、*path operation関数*と同じパラメータを全て取ることができる関数にすぎません: + +```Python hl_lines="8 9" +{!../../../docs_src/dependencies/tutorial001.py!} +``` + +これだけです。 + +**2行**。 + +そして、それはすべての*path operation関数*が持っているのと同じ形と構造を持っています。 + +「デコレータ」を含まない(`@app.get("/some-path")`を含まない)*path operation関数*と考えることもできます。 + +そして何でも返すことができます。 + +この場合、この依存関係は以下を期待しています: + +* オプショナルのクエリパラメータ`q`は`str`です。 +* オプショナルのクエリパラメータ`skip`は`int`で、デフォルトは`0`です。 +* オプショナルのクエリパラメータ`limit`は`int`で、デフォルトは`100`です。 + +そして、これらの値を含む`dict`を返します。 + +### `Depends`のインポート + +```Python hl_lines="3" +{!../../../docs_src/dependencies/tutorial001.py!} +``` + +### "dependant"での依存関係の宣言 + +*path operation関数*のパラメータに`Body`や`Query`などを使用するのと同じように、新しいパラメータに`Depends`を使用することができます: + +```Python hl_lines="13 18" +{!../../../docs_src/dependencies/tutorial001.py!} +``` + +関数のパラメータに`Depends`を使用するのは`Body`や`Query`などと同じですが、`Depends`の動作は少し異なります。 + +`Depends`は1つのパラメータしか与えられません。 + +このパラメータは関数のようなものである必要があります。 + +そして、その関数は、*path operation関数*が行うのと同じ方法でパラメータを取ります。 + +!!! tip "豆知識" + 次の章では、関数以外の「もの」が依存関係として使用できるものを見ていきます。 + +新しいリクエストが到着するたびに、**FastAPI** が以下のような処理を行います: + +* 依存関係("dependable")関数を正しいパラメータで呼び出します。 +* 関数の結果を取得します。 +* *path operation関数*のパラメータにその結果を代入してください。 + +```mermaid +graph TB + +common_parameters(["common_parameters"]) +read_items["/items/"] +read_users["/users/"] + +common_parameters --> read_items +common_parameters --> read_users +``` + +この方法では、共有されるコードを一度書き、**FastAPI** が*path operations*のための呼び出しを行います。 + +!!! check "確認" + 特別なクラスを作成してどこかで **FastAPI** に渡して「登録」する必要はないことに注意してください。 + + `Depends`を渡すだけで、**FastAPI** が残りの処理をしてくれます。 + +## `async`にするかどうか + +依存関係は **FastAPI**(*path operation関数*と同じ)からも呼び出されるため、関数を定義する際にも同じルールが適用されます。 + +`async def`や通常の`def`を使用することができます。 + +また、通常の`def`*path operation関数*の中に`async def`を入れて依存関係を宣言したり、`async def`*path operation関数*の中に`def`を入れて依存関係を宣言したりすることなどができます。 + +それは重要ではありません。**FastAPI** は何をすべきかを知っています。 + +!!! note "備考" + わからない場合は、ドキュメントの[Async: *"In a hurry?"*](../../async.md){.internal-link target=_blank}の中の`async`と`await`についてのセクションを確認してください。 + +## OpenAPIとの統合 + +依存関係(およびサブ依存関係)のすべてのリクエスト宣言、検証、および要件は、同じOpenAPIスキーマに統合されます。 + +つまり、対話型ドキュメントにはこれらの依存関係から得られる全ての情報も含まれているということです: + + + +## 簡単な使い方 + +見てみると、*path*と*operation*が一致した時に*path operation関数*が宣言されていて、**FastAPI** が正しいパラメータで関数を呼び出してリクエストからデータを抽出する処理をしています。 + +実は、すべての(あるいはほとんどの)Webフレームワークは、このように動作します。 + +これらの関数を直接呼び出すことはありません。これらの関数はフレームワーク(この場合は、**FastAPI**)によって呼び出されます。 + +依存性注入システムでは、**FastAPI** に*path operation*もまた、*path operation関数*の前に実行されるべき他の何かに「依存」していることを伝えることができ、**FastAPI** がそれを実行し、結果を「注入」することを引き受けます。 + +他にも、「依存性注入」と同じような考えの一般的な用語があります: + +* リソース +* プロバイダ +* サービス +* インジェクタブル +* コンポーネント + +## **FastAPI** プラグイン + +統合や「プラグイン」は **依存性注入** システムを使って構築することができます。しかし、実際には、**「プラグイン」を作成する必要はありません**。依存関係を使用することで、無限の数の統合やインタラクションを宣言することができ、それが**path operation関数*で利用可能になるからです。 + +依存関係は非常にシンプルで直感的な方法で作成することができ、必要なPythonパッケージをインポートするだけで、*文字通り*数行のコードでAPI関数と統合することができます。 + +次の章では、リレーショナルデータベースやNoSQLデータベース、セキュリティなどについて、その例を見ていきます。 + +## **FastAPI** 互換性 + +依存性注入システムがシンプルなので、**FastAPI** は以下のようなものと互換性があります: + +* すべてのリレーショナルデータベース +* NoSQLデータベース +* 外部パッケージ +* 外部API +* 認証・認可システム +* API利用状況監視システム +* レスポンスデータ注入システム +* など。 + +## シンプルでパワフル + +階層依存性注入システムは、定義や使用方法が非常にシンプルであるにもかかわらず、非常に強力なものとなっています。 + +依存関係事態を定義する依存関係を定義することができます。 + +最終的には、依存関係の階層ツリーが構築され、**依存性注入**システムが、これらの依存関係(およびそのサブ依存関係)をすべて解決し、各ステップで結果を提供(注入)します。 + +例えば、4つのAPIエンドポイント(*path operations*)があるとします: + +* `/items/public/` +* `/items/private/` +* `/users/{user_id}/activate` +* `/items/pro/` + +そして、依存関係とサブ依存関係だけで、それぞれに異なるパーミッション要件を追加することができます: + +```mermaid +graph TB + +current_user(["current_user"]) +active_user(["active_user"]) +admin_user(["admin_user"]) +paying_user(["paying_user"]) + +public["/items/public/"] +private["/items/private/"] +activate_user["/users/{user_id}/activate"] +pro_items["/items/pro/"] + +current_user --> active_user +active_user --> admin_user +active_user --> paying_user + +current_user --> public +active_user --> private +admin_user --> activate_user +paying_user --> pro_items +``` + +## **OpenAPI** との統合 + +これら全ての依存関係は、要件を宣言すると同時に、*path operations*にパラメータやバリデーションを追加します。 + +**FastAPI** はそれをすべてOpenAPIスキーマに追加して、対話型のドキュメントシステムに表示されるようにします。 diff --git a/docs/ja/docs/tutorial/extra-models.md b/docs/ja/docs/tutorial/extra-models.md new file mode 100644 index 0000000000000..aa2e5ffdcbe61 --- /dev/null +++ b/docs/ja/docs/tutorial/extra-models.md @@ -0,0 +1,195 @@ +# モデル - より詳しく + +先ほどの例に続き、複数の関連モデルを持つことが一般的です。 + +これはユーザーモデルの場合は特にそうです。なぜなら: + +* **入力モデル** にはパスワードが必要です。 +* **出力モデル**はパスワードをもつべきではありません。 +* **データベースモデル**はおそらくハッシュ化されたパスワードが必要になるでしょう。 + +!!! danger "危険" + ユーザーの平文のパスワードは絶対に保存しないでください。常に認証に利用可能な「安全なハッシュ」を保存してください。 + + 知らない方は、[セキュリティの章](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}で「パスワードハッシュ」とは何かを学ぶことができます。 + +## 複数のモデル + +ここでは、パスワードフィールドをもつモデルがどのように見えるのか、また、どこで使われるのか、大まかなイメージを紹介します: + +```Python hl_lines="9 11 16 22 24 29-30 33-35 40-41" +{!../../../docs_src/extra_models/tutorial001.py!} +``` + +### `**user_in.dict()`について + +#### Pydanticの`.dict()` + +`user_in`は`UserIn`クラスのPydanticモデルです。 + +Pydanticモデルには、モデルのデータを含む`dict`を返す`.dict()`メソッドがあります。 + +そこで、以下のようなPydanticオブジェクト`user_in`を作成すると: + +```Python +user_in = UserIn(username="john", password="secret", email="john.doe@example.com") +``` + +そして呼び出すと: + +```Python +user_dict = user_in.dict() +``` + +これで変数`user_dict`のデータを持つ`dict`ができました。(これはPydanticモデルのオブジェクトの代わりに`dict`です)。 + +そして呼び出すと: + +```Python +print(user_dict) +``` + +以下のようなPythonの`dict`を得ることができます: + +```Python +{ + 'username': 'john', + 'password': 'secret', + 'email': 'john.doe@example.com', + 'full_name': None, +} +``` + +#### `dict`の展開 + +`user_dict`のような`dict`を受け取り、それを`**user_dict`を持つ関数(またはクラス)に渡すと、Pythonはそれを「展開」します。これは`user_dict`のキーと値を直接キー・バリューの引数として渡します。 + +そこで上述の`user_dict`の続きを以下のように書くと: + +```Python +UserInDB(**user_dict) +``` + +以下と同等の結果になります: + +```Python +UserInDB( + username="john", + password="secret", + email="john.doe@example.com", + full_name=None, +) +``` + +もっと正確に言えば、`user_dict`を将来的にどんな内容であっても直接使用することになります: + +```Python +UserInDB( + username = user_dict["username"], + password = user_dict["password"], + email = user_dict["email"], + full_name = user_dict["full_name"], +) +``` + +#### 別のモデルからつくるPydanticモデル + +上述の例では`user_in.dict()`から`user_dict`をこのコードのように取得していますが: + +```Python +user_dict = user_in.dict() +UserInDB(**user_dict) +``` + +これは以下と同等です: + +```Python +UserInDB(**user_in.dict()) +``` + +...なぜなら`user_in.dict()`は`dict`であり、`**`を付与して`UserInDB`を渡してPythonに「展開」させているからです。 + +そこで、別のPydanticモデルのデータからPydanticモデルを取得します。 + +#### `dict`の展開と追加引数 + +そして、追加のキーワード引数`hashed_password=hashed_password`を以下のように追加すると: + +```Python +UserInDB(**user_in.dict(), hashed_password=hashed_password) +``` + +...以下のようになります: + +```Python +UserInDB( + username = user_dict["username"], + password = user_dict["password"], + email = user_dict["email"], + full_name = user_dict["full_name"], + hashed_password = hashed_password, +) +``` + +!!! warning "注意" + サポートしている追加機能は、データの可能な流れをデモするだけであり、もちろん本当のセキュリティを提供しているわけではありません。 + +## 重複の削減 + +コードの重複を減らすことは、**FastAPI**の中核的なアイデアの1つです。 + +コードの重複が増えると、バグやセキュリティの問題、コードの非同期化問題(ある場所では更新しても他の場所では更新されない場合)などが発生する可能性が高くなります。 + +そして、これらのモデルは全てのデータを共有し、属性名や型を重複させています。 + +もっと良い方法があります。 + +他のモデルのベースとなる`UserBase`モデルを宣言することができます。そして、そのモデルの属性(型宣言、検証など)を継承するサブクラスを作ることができます。 + +データの変換、検証、文書化などはすべて通常通りに動作します。 + +このようにして、モデル間の違いだけを宣言することができます: + +```Python hl_lines="9 15 16 19 20 23 24" +{!../../../docs_src/extra_models/tutorial002.py!} +``` + +## `Union`または`anyOf` + +レスポンスを2つの型の`Union`として宣言することができます。 + +OpenAPIでは`anyOf`で定義されます。 + +そのためには、標準的なPythonの型ヒント`typing.Union`を使用します: + +```Python hl_lines="1 14 15 18 19 20 33" +{!../../../docs_src/extra_models/tutorial003.py!} +``` + +## モデルのリスト + +同じように、オブジェクトのリストのレスポンスを宣言することができます。 + +そのためには、標準のPythonの`typing.List`を使用する: + +```Python hl_lines="1 20" +{!../../../docs_src/extra_models/tutorial004.py!} +``` + +## 任意の`dict`を持つレスポンス + +また、Pydanticモデルを使用せずに、キーと値の型だけを定義した任意の`dict`を使ってレスポンスを宣言することもできます。 + +これは、有効なフィールド・属性名(Pydanticモデルに必要なもの)を事前に知らない場合に便利です。 + +この場合、`typing.Dict`を使用することができます: + +```Python hl_lines="1 8" +{!../../../docs_src/extra_models/tutorial005.py!} +``` + +## まとめ + +複数のPydanticモデルを使用し、ケースごとに自由に継承します。 + +エンティティが異なる「状態」を持たなければならない場合は、エンティティごとに単一のデータモデルを持つ必要はありません。`password` や `password_hash` やパスワードなしなどのいくつかの「状態」をもつユーザー「エンティティ」の場合の様にすれば良いです。 diff --git a/docs/ja/docs/tutorial/handling-errors.md b/docs/ja/docs/tutorial/handling-errors.md new file mode 100644 index 0000000000000..ec36e9880d859 --- /dev/null +++ b/docs/ja/docs/tutorial/handling-errors.md @@ -0,0 +1,265 @@ +# エラーハンドリング + +APIを使用しているクライアントにエラーを通知する必要がある状況はたくさんあります。 + +このクライアントは、フロントエンドを持つブラウザ、誰かのコード、IoTデバイスなどが考えられます。 + +クライアントに以下のようなことを伝える必要があるかもしれません: + +* クライアントにはその操作のための十分な権限がありません。 +* クライアントはそのリソースにアクセスできません。 +* クライアントがアクセスしようとしていた項目が存在しません。 +* など + +これらの場合、通常は **400**(400から499)の範囲内の **HTTPステータスコード** を返すことになります。 + +これは200のHTTPステータスコード(200から299)に似ています。これらの「200」ステータスコードは、何らかの形でリクエスト「成功」であったことを意味します。 + +400の範囲にあるステータスコードは、クライアントからのエラーがあったことを意味します。 + +**"404 Not Found"** のエラー(およびジョーク)を覚えていますか? + +## `HTTPException`の使用 + +HTTPレスポンスをエラーでクライアントに返すには、`HTTPException`を使用します。 + +### `HTTPException`のインポート + +```Python hl_lines="1" +{!../../../docs_src/handling_errors/tutorial001.py!} +``` + +### コード内での`HTTPException`の発生 + +`HTTPException`は通常のPythonの例外であり、APIに関連するデータを追加したものです。 + +Pythonの例外なので、`return`ではなく、`raise`です。 + +これはまた、*path operation関数*の内部で呼び出しているユーティリティ関数の内部から`HTTPException`を発生させた場合、*path operation関数*の残りのコードは実行されず、そのリクエストを直ちに終了させ、`HTTPException`からのHTTPエラーをクライアントに送信することを意味します。 + +値を返す`return`よりも例外を発生させることの利点は、「依存関係とセキュリティ」のセクションでより明確になります。 + +この例では、クライアントが存在しないIDでアイテムを要求した場合、`404`のステータスコードを持つ例外を発生させます: + +```Python hl_lines="11" +{!../../../docs_src/handling_errors/tutorial001.py!} +``` + +### レスポンス結果 + +クライアントが`http://example.com/items/foo`(`item_id` `"foo"`)をリクエストすると、HTTPステータスコードが200で、以下のJSONレスポンスが返されます: + +```JSON +{ + "item": "The Foo Wrestlers" +} +``` + +しかし、クライアントが`http://example.com/items/bar`(存在しない`item_id` `"bar"`)をリクエストした場合、HTTPステータスコード404("not found"エラー)と以下のJSONレスポンスが返されます: + +```JSON +{ + "detail": "Item not found" +} +``` + +!!! tip "豆知識" + `HTTPException`を発生させる際には、`str`だけでなく、JSONに変換できる任意の値を`detail`パラメータとして渡すことができます。 + + `dist`や`list`などを渡すことができます。 + + これらは **FastAPI** によって自動的に処理され、JSONに変換されます。 + +## カスタムヘッダーの追加 + +例えば、いくつかのタイプのセキュリティのために、HTTPエラーにカスタムヘッダを追加できると便利な状況がいくつかあります。 + +おそらくコードの中で直接使用する必要はないでしょう。 + +しかし、高度なシナリオのために必要な場合には、カスタムヘッダーを追加することができます: + +```Python hl_lines="14" +{!../../../docs_src/handling_errors/tutorial002.py!} +``` + +## カスタム例外ハンドラのインストール + +カスタム例外ハンドラはStarletteと同じ例外ユーティリティを使用して追加することができます。 + +あなた(または使用しているライブラリ)が`raise`するかもしれないカスタム例外`UnicornException`があるとしましょう。 + +そして、この例外をFastAPIでグローバルに処理したいと思います。 + +カスタム例外ハンドラを`@app.exception_handler()`で追加することができます: + +```Python hl_lines="5 6 7 13 14 15 16 17 18 24" +{!../../../docs_src/handling_errors/tutorial003.py!} +``` + +ここで、`/unicorns/yolo`をリクエストすると、*path operation*は`UnicornException`を`raise`します。 + +しかし、これは`unicorn_exception_handler`で処理されます。 + +そのため、HTTPステータスコードが`418`で、JSONの内容が以下のような明確なエラーを受け取ることになります: + +```JSON +{"message": "Oops! yolo did something. There goes a rainbow..."} +``` + +!!! note "技術詳細" + また、`from starlette.requests import Request`と`from starlette.responses import JSONResponse`を使用することもできます。 + + **FastAPI** は開発者の利便性を考慮して、`fastapi.responses`と同じ`starlette.responses`を提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。これは`Request`と同じです。 + +## デフォルトの例外ハンドラのオーバーライド + +**FastAPI** にはいくつかのデフォルトの例外ハンドラがあります。 + +これらのハンドラは、`HTTPException`を`raise`させた場合や、リクエストに無効なデータが含まれている場合にデフォルトのJSONレスポンスを返す役割を担っています。 + +これらの例外ハンドラを独自のものでオーバーライドすることができます。 + +### リクエスト検証の例外のオーバーライド + +リクエストに無効なデータが含まれている場合、**FastAPI** は内部的に`RequestValidationError`を発生させます。 + +また、そのためのデフォルトの例外ハンドラも含まれています。 + +これをオーバーライドするには`RequestValidationError`をインポートして`@app.exception_handler(RequestValidationError)`と一緒に使用して例外ハンドラをデコレートします。 + +この例外ハンドラは`Requset`と例外を受け取ります。 + +```Python hl_lines="2 14 15 16" +{!../../../docs_src/handling_errors/tutorial004.py!} +``` + +これで、`/items/foo`にアクセスすると、デフォルトのJSONエラーの代わりに以下が返されます: + +```JSON +{ + "detail": [ + { + "loc": [ + "path", + "item_id" + ], + "msg": "value is not a valid integer", + "type": "type_error.integer" + } + ] +} +``` + +以下のようなテキスト版を取得します: + +``` +1 validation error +path -> item_id + value is not a valid integer (type=type_error.integer) +``` + +#### `RequestValidationError`と`ValidationError` + +!!! warning "注意" + これらは今のあなたにとって重要でない場合は省略しても良い技術的な詳細です。 + +`RequestValidationError`はPydanticの`ValidationError`のサブクラスです。 + +**FastAPI** は`response_model`でPydanticモデルを使用していて、データにエラーがあった場合、ログにエラーが表示されるようにこれを使用しています。 + +しかし、クライアントやユーザーはそれを見ることはありません。その代わりに、クライアントはHTTPステータスコード`500`の「Internal Server Error」を受け取ります。 + +*レスポンス*やコードのどこか(クライアントの*リクエスト*ではなく)にPydanticの`ValidationError`がある場合、それは実際にはコードのバグなのでこのようにすべきです。 + +また、あなたがそれを修正している間は、セキュリティの脆弱性が露呈する場合があるため、クライアントやユーザーがエラーに関する内部情報にアクセスできないようにしてください。 + +### エラーハンドラ`HTTPException`のオーバーライド + +同様に、`HTTPException`ハンドラをオーバーライドすることもできます。 + +例えば、これらのエラーに対しては、JSONではなくプレーンテキストを返すようにすることができます: + +```Python hl_lines="3 4 9 10 11 22" +{!../../../docs_src/handling_errors/tutorial004.py!} +``` + +!!! note "技術詳細" + また、`from starlette.responses import PlainTextResponse`を使用することもできます。 + + **FastAPI** は開発者の利便性を考慮して、`fastapi.responses`と同じ`starlette.responses`を提供しています。しかし、利用可能なレスポンスのほとんどはStarletteから直接提供されます。 + +### `RequestValidationError`のボディの使用 + +`RequestValidationError`には無効なデータを含む`body`が含まれています。 + +アプリ開発中に本体のログを取ってデバッグしたり、ユーザーに返したりなどに使用することができます。 + +```Python hl_lines="14" +{!../../../docs_src/handling_errors/tutorial005.py!} +``` + +ここで、以下のような無効な項目を送信してみてください: + +```JSON +{ + "title": "towel", + "size": "XL" +} +``` + +受信したボディを含むデータが無効であることを示すレスポンスが表示されます: + +```JSON hl_lines="12 13 14 15" +{ + "detail": [ + { + "loc": [ + "body", + "size" + ], + "msg": "value is not a valid integer", + "type": "type_error.integer" + } + ], + "body": { + "title": "towel", + "size": "XL" + } +} +``` + +#### FastAPIの`HTTPException`とStarletteの`HTTPException` + +**FastAPI**は独自の`HTTPException`を持っています。 + +また、 **FastAPI**のエラークラス`HTTPException`はStarletteのエラークラス`HTTPException`を継承しています。 + +唯一の違いは、**FastAPI** の`HTTPException`はレスポンスに含まれるヘッダを追加できることです。 + +これはOAuth 2.0といくつかのセキュリティユーティリティのために内部的に必要とされ、使用されています。 + +そのため、コード内では通常通り **FastAPI** の`HTTPException`を発生させ続けることができます。 + +しかし、例外ハンドラを登録する際には、Starletteの`HTTPException`を登録しておく必要があります。 + +これにより、Starletteの内部コードやStarletteの拡張機能やプラグインの一部が`HTTPException`を発生させた場合、ハンドラがそれをキャッチして処理することができるようになります。 + +以下の例では、同じコード内で両方の`HTTPException`を使用できるようにするために、Starletteの例外の名前を`StarletteHTTPException`に変更しています: + +```Python +from starlette.exceptions import HTTPException as StarletteHTTPException +``` + +### **FastAPI** の例外ハンドラの再利用 + +また、何らかの方法で例外を使用することもできますが、**FastAPI** から同じデフォルトの例外ハンドラを使用することもできます。 + +デフォルトの例外ハンドラを`fastapi.exception_handlers`からインポートして再利用することができます: + +```Python hl_lines="2 3 4 5 15 21" +{!../../../docs_src/handling_errors/tutorial006.py!} +``` + +この例では、非常に表現力のあるメッセージでエラーを`print`しています。 + +しかし、例外を使用して、デフォルトの例外ハンドラを再利用することができるということが理解できます。 diff --git a/docs/ja/docs/tutorial/path-params-numeric-validations.md b/docs/ja/docs/tutorial/path-params-numeric-validations.md new file mode 100644 index 0000000000000..551aeabb3afa9 --- /dev/null +++ b/docs/ja/docs/tutorial/path-params-numeric-validations.md @@ -0,0 +1,122 @@ +# パスパラメータと数値の検証 + +クエリパラメータに対して`Query`でより多くのバリデーションとメタデータを宣言できるのと同じように、パスパラメータに対しても`Path`で同じ種類のバリデーションとメタデータを宣言することができます。 + +## Pathのインポート + +まず初めに、`fastapi`から`Path`をインポートします: + +```Python hl_lines="1" +{!../../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` + +## メタデータの宣言 + +パラメータは`Query`と同じものを宣言することができます。 + +例えば、パスパラメータ`item_id`に対して`title`のメタデータを宣言するには以下のようにします: + +```Python hl_lines="8" +{!../../../docs_src/path_params_numeric_validations/tutorial001.py!} +``` + +!!! note "備考" + パスの一部でなければならないので、パスパラメータは常に必須です。 + + そのため、`...`を使用して必須と示す必要があります。 + + それでも、`None`で宣言しても、デフォルト値を設定しても、何の影響もなく、常に必要とされていることに変わりはありません。 + +## 必要に応じてパラメータを並び替える + +クエリパラメータ`q`を必須の`str`として宣言したいとしましょう。 + +また、このパラメータには何も宣言する必要がないので、`Query`を使う必要はありません。 + +しかし、パスパラメータ`item_id`のために`Path`を使用する必要があります。 + +Pythonは「デフォルト」を持たない値の前に「デフォルト」を持つ値を置くことができません。 + +しかし、それらを並び替えることができ、デフォルト値を持たない値(クエリパラメータ`q`)を最初に持つことができます。 + +**FastAPI**では関係ありません。パラメータは名前、型、デフォルトの宣言(`Query`、`Path`など)で検出され、順番は気にしません。 + +そのため、以下のように関数を宣言することができます: + +```Python hl_lines="8" +{!../../../docs_src/path_params_numeric_validations/tutorial002.py!} +``` + +## 必要に応じてパラメータを並び替えるトリック + +クエリパラメータ`q`を`Query`やデフォルト値なしで宣言し、パスパラメータ`item_id`を`Path`を用いて宣言し、それらを別の順番に並びたい場合、Pythonには少し特殊な構文が用意されています。 + +関数の最初のパラメータとして`*`を渡します。 + +Pythonはその`*`で何かをすることはありませんが、それ以降のすべてのパラメータがキーワード引数(キーと値のペア)として呼ばれるべきものであると知っているでしょう。それはkwargsとしても知られています。たとえデフォルト値がなくても。 + +```Python hl_lines="8" +{!../../../docs_src/path_params_numeric_validations/tutorial003.py!} +``` + +## 数値の検証: 以上 + +`Query`と`Path`(、そして後述する他のもの)を用いて、文字列の制約を宣言することができますが、数値の制約も同様に宣言できます。 + +ここで、`ge=1`の場合、`item_id`は`1`「より大きい`g`か、同じ`e`」整数でなれけばなりません。 + +```Python hl_lines="8" +{!../../../docs_src/path_params_numeric_validations/tutorial004.py!} +``` + +## 数値の検証: より大きいと小なりイコール + +以下も同様です: + +* `gt`: より大きい(`g`reater `t`han) +* `le`: 小なりイコール(`l`ess than or `e`qual) + +```Python hl_lines="9" +{!../../../docs_src/path_params_numeric_validations/tutorial005.py!} +``` + +## 数値の検証: 浮動小数点、 大なり小なり + +数値のバリデーションは`float`の値に対しても有効です。 + +ここで重要になってくるのはgtだけでなくgeも宣言できることです。これと同様に、例えば、値が`1`より小さくても`0`より大きくなければならないことを要求することができます。 + +したがって、`0.5`は有効な値ですが、`0.0`や`0`はそうではありません。 + +これはltも同じです。 + +```Python hl_lines="11" +{!../../../docs_src/path_params_numeric_validations/tutorial006.py!} +``` + +## まとめ + +`Query`と`Path`(そしてまだ見たことない他のもの)では、[クエリパラメータと文字列の検証](query-params-str-validations.md){.internal-link target=_blank}と同じようにメタデータと文字列の検証を宣言することができます。 + +また、数値のバリデーションを宣言することもできます: + +* `gt`: より大きい(`g`reater `t`han) +* `ge`: 以上(`g`reater than or `e`qual) +* `lt`: より小さい(`l`ess `t`han) +* `le`: 以下(`l`ess than or `e`qual) + +!!! info "情報" + `Query`、`Path`などは後に共通の`Param`クラスのサブクラスを見ることになります。(使う必要はありません) + + そして、それらすべては、これまで見てきた追加のバリデーションとメタデータと同じパラメータを共有しています。 + +!!! note "技術詳細" + `fastapi`から`Query`、`Path`などをインポートすると、これらは実際には関数です。 + + 呼び出されると、同じ名前のクラスのインスタンスを返します。 + + そのため、関数である`Query`をインポートし、それを呼び出すと、`Query`という名前のクラスのインスタンスが返されます。 + + これらの関数は(クラスを直接使うのではなく)エディタが型についてエラーとしないようにするために存在します。 + + この方法によって、これらのエラーを無視するための設定を追加することなく、通常のエディタやコーディングツールを使用することができます。 diff --git a/docs/ja/docs/tutorial/response-model.md b/docs/ja/docs/tutorial/response-model.md new file mode 100644 index 0000000000000..749b330610d71 --- /dev/null +++ b/docs/ja/docs/tutorial/response-model.md @@ -0,0 +1,208 @@ +# レスポンスモデル + +*path operations* のいずれにおいても、`response_model`パラメータを使用して、レスポンスのモデルを宣言することができます: + +* `@app.get()` +* `@app.post()` +* `@app.put()` +* `@app.delete()` +* など。 + +```Python hl_lines="17" +{!../../../docs_src/response_model/tutorial001.py!} +``` + +!!! note "備考" + `response_model`は「デコレータ」メソッド(`get`、`post`など)のパラメータであることに注意してください。すべてのパラメータやボディのように、*path operation関数* のパラメータではありません。 + +Pydanticモデルの属性に対して宣言するのと同じ型を受け取るので、Pydanticモデルになることもできますが、例えば、`List[Item]`のようなPydanticモデルの`list`になることもできます。 + +FastAPIは`response_model`を使って以下のことをします: + +* 出力データを型宣言に変換します。 +* データを検証します。 +* OpenAPIの *path operation* で、レスポンス用のJSON Schemaを追加します。 +* 自動ドキュメントシステムで使用されます。 + +しかし、最も重要なのは: + +* 出力データをモデルのデータに限定します。これがどのように重要なのか以下で見ていきましょう。 + +!!! note "技術詳細" + レスポンスモデルは、関数の戻り値のアノテーションではなく、このパラメータで宣言されています。なぜなら、パス関数は実際にはそのレスポンスモデルを返すのではなく、`dict`やデータベースオブジェクト、あるいは他のモデルを返し、`response_model`を使用してフィールドの制限やシリアライズを行うからです。 + +## 同じ入力データの返却 + +ここでは`UserIn`モデルを宣言しています。それには平文のパスワードが含まれています: + +```Python hl_lines="9 11" +{!../../../docs_src/response_model/tutorial002.py!} +``` + +そして、このモデルを使用して入力を宣言し、同じモデルを使って出力を宣言しています: + +```Python hl_lines="17 18" +{!../../../docs_src/response_model/tutorial002.py!} +``` + +これで、ブラウザがパスワードを使ってユーザーを作成する際に、APIがレスポンスで同じパスワードを返すようになりました。 + +この場合、ユーザー自身がパスワードを送信しているので問題ないかもしれません。 + +しかし、同じモデルを別の*path operation*に使用すると、すべてのクライアントにユーザーのパスワードを送信してしまうことになります。 + +!!! danger "危険" + ユーザーの平文のパスワードを保存したり、レスポンスで送信したりすることは絶対にしないでください。 + +## 出力モデルの追加 + +代わりに、平文のパスワードを持つ入力モデルと、パスワードを持たない出力モデルを作成することができます: + +```Python hl_lines="9 11 16" +{!../../../docs_src/response_model/tutorial003.py!} +``` + +ここでは、*path operation関数*がパスワードを含む同じ入力ユーザーを返しているにもかかわらず: + +```Python hl_lines="24" +{!../../../docs_src/response_model/tutorial003.py!} +``` + +...`response_model`を`UserOut`と宣言したことで、パスワードが含まれていません: + +```Python hl_lines="22" +{!../../../docs_src/response_model/tutorial003.py!} +``` + +そのため、**FastAPI** は出力モデルで宣言されていない全てのデータをフィルタリングしてくれます(Pydanticを使用)。 + +## ドキュメントを見る + +自動ドキュメントを見ると、入力モデルと出力モデルがそれぞれ独自のJSON Schemaを持っていることが確認できます。 + + + +そして、両方のモデルは、対話型のAPIドキュメントに使用されます: + + + +## レスポンスモデルのエンコーディングパラメータ + +レスポンスモデルにはデフォルト値を設定することができます: + +```Python hl_lines="11 13 14" +{!../../../docs_src/response_model/tutorial004.py!} +``` + +* `description: str = None`は`None`がデフォルト値です。 +* `tax: float = 10.5`は`10.5`がデフォルト値です。 +* `tags: List[str] = []` は空のリスト(`[]`)がデフォルト値です。 + +しかし、実際に保存されていない場合には結果からそれらを省略した方が良いかもしれません。 + +例えば、NoSQLデータベースに多くのオプション属性を持つモデルがあるが、デフォルト値でいっぱいの非常に長いJSONレスポンスを送信したくない場合です。 + +### `response_model_exclude_unset`パラメータの使用 + +*path operation デコレータ*に`response_model_exclude_unset=True`パラメータを設定することができます: + +```Python hl_lines="24" +{!../../../docs_src/response_model/tutorial004.py!} +``` + +そして、これらのデフォルト値はレスポンスに含まれず、実際に設定された値のみが含まれます。 + +そのため、*path operation*にID`foo`が設定されたitemのリクエストを送ると、レスポンスは以下のようになります(デフォルト値を含まない): + +```JSON +{ + "name": "Foo", + "price": 50.2 +} +``` + +!!! info "情報" + FastAPIはこれをするために、Pydanticモデルの`.dict()`をその`exclude_unset`パラメータで使用しています。 + +!!! info "情報" + 以下も使用することができます: + + * `response_model_exclude_defaults=True` + * `response_model_exclude_none=True` + + `exclude_defaults`と`exclude_none`については、Pydanticのドキュメントで説明されている通りです。 + +#### デフォルト値を持つフィールドの値を持つデータ + +しかし、ID`bar`のitemのように、デフォルト値が設定されているモデルのフィールドに値が設定されている場合: + +```Python hl_lines="3 5" +{ + "name": "Bar", + "description": "The bartenders", + "price": 62, + "tax": 20.2 +} +``` + +それらはレスポンスに含まれます。 + +#### デフォルト値と同じ値を持つデータ + +ID`baz`のitemのようにデフォルト値と同じ値を持つデータの場合: + +```Python hl_lines="3 5 6" +{ + "name": "Baz", + "description": None, + "price": 50.2, + "tax": 10.5, + "tags": [] +} +``` + +FastAPIは十分に賢いので(実際には、Pydanticが十分に賢い)`description`や`tax`、`tags`はデフォルト値と同じ値を持っているにもかかわらず、明示的に設定されていることを理解しています。(デフォルトから取得するのではなく) + +そのため、それらはJSONレスポンスに含まれることになります。 + +!!! tip "豆知識" + デフォルト値は`None`だけでなく、なんでも良いことに注意してください。 + 例えば、リスト(`[]`)や`10.5`の`float`などです。 + +### `response_model_include`と`response_model_exclude` + +*path operationデコレータ*として`response_model_include`と`response_model_exclude`も使用することができます。 + +属性名を持つ`str`の`set`を受け取り、含める(残りを省略する)か、除外(残りを含む)します。 + +これは、Pydanticモデルが1つしかなく、出力からいくつかのデータを削除したい場合のクイックショートカットとして使用することができます。 + +!!! tip "豆知識" + それでも、これらのパラメータではなく、複数のクラスを使用して、上記のようなアイデアを使うことをおすすめします。 + + これは`response_model_include`や`response_mode_exclude`を使用していくつかの属性を省略しても、アプリケーションのOpenAPI(とドキュメント)で生成されたJSON Schemaが完全なモデルになるからです。 + + 同様に動作する`response_model_by_alias`にも当てはまります。 + +```Python hl_lines="31 37" +{!../../../docs_src/response_model/tutorial005.py!} +``` + +!!! tip "豆知識" + `{"name", "description"}`の構文はこれら2つの値をもつ`set`を作成します。 + + これは`set(["name", "description"])`と同等です。 + +#### `set`の代わりに`list`を使用する + +もし`set`を使用することを忘れて、代わりに`list`や`tuple`を使用しても、FastAPIはそれを`set`に変換して正しく動作します: + +```Python hl_lines="31 37" +{!../../../docs_src/response_model/tutorial006.py!} +``` + +## まとめ + +*path operationデコレータの*`response_model`パラメータを使用して、レスポンスモデルを定義し、特にプライベートデータがフィルタリングされていることを保証します。 + +明示的に設定された値のみを返すには、`response_model_exclude_unset`を使用します。 diff --git a/docs/ja/docs/tutorial/response-status-code.md b/docs/ja/docs/tutorial/response-status-code.md new file mode 100644 index 0000000000000..ead2adddaa60b --- /dev/null +++ b/docs/ja/docs/tutorial/response-status-code.md @@ -0,0 +1,89 @@ +# レスポンスステータスコード + +レスポンスモデルを指定するのと同じ方法で、レスポンスに使用されるHTTPステータスコードを以下の*path operations*のいずれかの`status_code`パラメータで宣言することもできます。 + +* `@app.get()` +* `@app.post()` +* `@app.put()` +* `@app.delete()` +* など。 + +```Python hl_lines="6" +{!../../../docs_src/response_status_code/tutorial001.py!} +``` + +!!! note "備考" + `status_code`は「デコレータ」メソッド(`get`、`post`など)のパラメータであることに注意してください。すべてのパラメータやボディのように、*path operation関数*のものではありません。 + +`status_code`パラメータはHTTPステータスコードを含む数値を受け取ります。 + +!!! info "情報" + `status_code`は代わりに、Pythonの`http.HTTPStatus`のように、`IntEnum`を受け取ることもできます。 + +これは: + +* レスポンスでステータスコードを返します。 +* OpenAPIスキーマ(およびユーザーインターフェース)に以下のように文書化します: + + + +!!! note "備考" + いくつかのレスポンスコード(次のセクションを参照)は、レスポンスにボディがないことを示しています。 + + FastAPIはこれを知っていて、レスポンスボディがないというOpenAPIドキュメントを生成します。 + +## HTTPステータスコードについて + +!!! note "備考" + すでにHTTPステータスコードが何であるかを知っている場合は、次のセクションにスキップしてください。 + +HTTPでは、レスポンスの一部として3桁の数字のステータスコードを送信します。 + +これらのステータスコードは、それらを認識するために関連付けられた名前を持っていますが、重要な部分は番号です。 + +つまり: + +* `100`以上は「情報」のためのものです。。直接使うことはほとんどありません。これらのステータスコードを持つレスポンスはボディを持つことができません。 +* **`200`** 以上は「成功」のレスポンスのためのものです。これらは最も利用するであろうものです。 + * `200`はデフォルトのステータスコードで、すべてが「OK」であったことを意味します。 + * 別の例としては、`201`(Created)があります。これはデータベースに新しいレコードを作成した後によく使用されます。 + * 特殊なケースとして、`204`(No Content)があります。このレスポンスはクライアントに返すコンテンツがない場合に使用されます。そしてこのレスポンスはボディを持つことはできません。 +* **`300`** 以上は「リダイレクト」のためのものです。これらのステータスコードを持つレスポンスは`304`(Not Modified)を除き、ボディを持つことも持たないこともできます。 +* **`400`** 以上は「クライアントエラー」のレスポンスのためのものです。これらは、おそらく最も多用するであろう2番目のタイプです。 + * 例えば、`404`は「Not Found」レスポンスです。 + * クライアントからの一般的なエラーについては、`400`を使用することができます。 +* `500`以上はサーバーエラーのためのものです。これらを直接使うことはほとんどありません。アプリケーションコードやサーバーのどこかで何か問題が発生した場合、これらのステータスコードのいずれかが自動的に返されます。 + +!!! tip "豆知識" + それぞれのステータスコードとどのコードが何のためのコードなのかについて詳細はMDN HTTP レスポンスステータスコードについてのドキュメントを参照してください。 + +## 名前を覚えるための近道 + +先ほどの例をもう一度見てみましょう: + +```Python hl_lines="6" +{!../../../docs_src/response_status_code/tutorial001.py!} +``` + +`201`は「作成完了」のためのステータスコードです。 + +しかし、それぞれのコードの意味を暗記する必要はありません。 + +`fastapi.status`の便利な変数を利用することができます。 + +```Python hl_lines="1 6" +{!../../../docs_src/response_status_code/tutorial002.py!} +``` + +それらは便利です。それらは同じ番号を保持しており、その方法ではエディタの自動補完を使用してそれらを見つけることができます。 + + + +!!! note "技術詳細" + また、`from starlette import status`を使うこともできます。 + + **FastAPI** は、`開発者の利便性を考慮して、fastapi.status`と同じ`starlette.status`を提供しています。しかし、これはStarletteから直接提供されています。 + +## デフォルトの変更 + +後に、[高度なユーザーガイド](../advanced/response-change-status-code.md){.internal-link target=_blank}で、ここで宣言しているデフォルトとは異なるステータスコードを返す方法を見ていきます。 diff --git a/docs/ja/docs/tutorial/schema-extra-example.md b/docs/ja/docs/tutorial/schema-extra-example.md new file mode 100644 index 0000000000000..3102a4936248e --- /dev/null +++ b/docs/ja/docs/tutorial/schema-extra-example.md @@ -0,0 +1,58 @@ +# スキーマの追加 - 例 + +JSON Schemaに追加する情報を定義することができます。 + +一般的なユースケースはこのドキュメントで示されているように`example`を追加することです。 + +JSON Schemaの追加情報を宣言する方法はいくつかあります。 + +## Pydanticの`schema_extra` + +Pydanticのドキュメント: スキーマのカスタマイズで説明されているように、`Config`と`schema_extra`を使ってPydanticモデルの例を宣言することができます: + +```Python hl_lines="15 16 17 18 19 20 21 22 23" +{!../../../docs_src/schema_extra_example/tutorial001.py!} +``` + +その追加情報はそのまま出力され、JSON Schemaに追加されます。 + +## `Field`の追加引数 + +後述する`Field`、`Path`、`Query`、`Body`などでは、任意の引数を関数に渡すことでJSON Schemaの追加情報を宣言することもできます: + +```Python hl_lines="4 10 11 12 13" +{!../../../docs_src/schema_extra_example/tutorial002.py!} +``` + +!!! warning "注意" + これらの追加引数が渡されても、文書化のためのバリデーションは追加されず、注釈だけが追加されることを覚えておいてください。 + +## `Body`の追加引数 + +追加情報を`Field`に渡すのと同じように、`Path`、`Query`、`Body`などでも同じことができます。 + +例えば、`Body`にボディリクエストの`example`を渡すことができます: + +```Python hl_lines="21 22 23 24 25 26" +{!../../../docs_src/schema_extra_example/tutorial003.py!} +``` + +## ドキュメントのUIの例 + +上記のいずれの方法でも、`/docs`の中では以下のようになります: + + + +## 技術詳細 + +`example` と `examples`について... + +JSON Schemaの最新バージョンでは`examples`というフィールドを定義していますが、OpenAPIは`examples`を持たない古いバージョンのJSON Schemaをベースにしています。 + +そのため、OpenAPIでは同じ目的のために`example`を独自に定義しており(`examples`ではなく`example`として)、それがdocs UI(Swagger UIを使用)で使用されています。 + +つまり、`example`はJSON Schemaの一部ではありませんが、OpenAPIの一部であり、それがdocs UIで使用されることになります。 + +## その他の情報 + +同じように、フロントエンドのユーザーインターフェースなどをカスタマイズするために、各モデルのJSON Schemaに追加される独自の追加情報を追加することができます。 diff --git a/docs/ja/docs/tutorial/security/oauth2-jwt.md b/docs/ja/docs/tutorial/security/oauth2-jwt.md index 348ffda0163e9..d5b179aa05abf 100644 --- a/docs/ja/docs/tutorial/security/oauth2-jwt.md +++ b/docs/ja/docs/tutorial/security/oauth2-jwt.md @@ -167,7 +167,7 @@ JWTトークンの署名に使用するアルゴリズム`"HS256"`を指定し JWTアクセストークンを作成し、それを返します。 -```Python hl_lines="115-128" +```Python hl_lines="115-130" {!../../../docs_src/security/tutorial004.py!} ``` diff --git a/docs/ko/docs/index.md b/docs/ko/docs/index.md index 7ce938106d8bb..594b092f7316f 100644 --- a/docs/ko/docs/index.md +++ b/docs/ko/docs/index.md @@ -24,7 +24,7 @@ --- -FastAPI는 현대적이고, 빠르며(고성능), 파이썬 표준 타입 힌트에 기초한 Python3.6+의 API를 빌드하기 위한 웹 프레임워크입니다. +FastAPI는 현대적이고, 빠르며(고성능), 파이썬 표준 타입 힌트에 기초한 Python3.8+의 API를 빌드하기 위한 웹 프레임워크입니다. 주요 특징으로: @@ -323,7 +323,7 @@ def update_item(item_id: int, item: Item): 새로운 문법, 특정 라이브러리의 메소드나 클래스 등을 배울 필요가 없습니다. -그저 표준 **Python 3.6+**입니다. +그저 표준 **Python 3.8+** 입니다. 예를 들어, `int`에 대해선: diff --git a/docs/language_names.yml b/docs/language_names.yml new file mode 100644 index 0000000000000..7c37ff2b13271 --- /dev/null +++ b/docs/language_names.yml @@ -0,0 +1,183 @@ +aa: Afaraf +ab: аҧсуа бызшәа +ae: avesta +af: Afrikaans +ak: Akan +am: አማርኛ +an: aragonés +ar: اللغة العربية +as: অসমীয়া +av: авар мацӀ +ay: aymar aru +az: azərbaycan dili +ba: башҡорт теле +be: беларуская мова +bg: български език +bh: भोजपुरी +bi: Bislama +bm: bamanankan +bn: বাংলা +bo: བོད་ཡིག +br: brezhoneg +bs: bosanski jezik +ca: Català +ce: нохчийн мотт +ch: Chamoru +co: corsu +cr: ᓀᐦᐃᔭᐍᐏᐣ +cs: čeština +cu: ѩзыкъ словѣньскъ +cv: чӑваш чӗлхи +cy: Cymraeg +da: dansk +de: Deutsch +dv: Dhivehi +dz: རྫོང་ཁ +ee: Eʋegbe +el: Ελληνικά +en: English +eo: Esperanto +es: español +et: eesti +eu: euskara +fa: فارسی +ff: Fulfulde +fi: suomi +fj: Vakaviti +fo: føroyskt +fr: français +fy: Frysk +ga: Gaeilge +gd: Gàidhlig +gl: galego +gu: ગુજરાતી +gv: Gaelg +ha: هَوُسَ +he: עברית +hi: हिन्दी +ho: Hiri Motu +hr: Hrvatski +ht: Kreyòl ayisyen +hu: magyar +hy: Հայերեն +hz: Otjiherero +ia: Interlingua +id: Bahasa Indonesia +ie: Interlingue +ig: Asụsụ Igbo +ii: ꆈꌠ꒿ Nuosuhxop +ik: Iñupiaq +io: Ido +is: Íslenska +it: italiano +iu: ᐃᓄᒃᑎᑐᑦ +ja: 日本語 +jv: basa Jawa +ka: ქართული +kg: Kikongo +ki: Gĩkũyũ +kj: Kuanyama +kk: қазақ тілі +kl: kalaallisut +km: ខេមរភាសា +kn: ಕನ್ನಡ +ko: 한국어 +kr: Kanuri +ks: कश्मीरी +ku: Kurdî +kv: коми кыв +kw: Kernewek +ky: Кыргызча +la: latine +lb: Lëtzebuergesch +lg: Luganda +li: Limburgs +ln: Lingála +lo: ພາສາ +lt: lietuvių kalba +lu: Tshiluba +lv: latviešu valoda +mg: fiteny malagasy +mh: Kajin M̧ajeļ +mi: te reo Māori +mk: македонски јазик +ml: മലയാളം +mn: Монгол хэл +mr: मराठी +ms: Bahasa Malaysia +mt: Malti +my: ဗမာစာ +na: Ekakairũ Naoero +nb: Norsk bokmål +nd: isiNdebele +ne: नेपाली +ng: Owambo +nl: Nederlands +nn: Norsk nynorsk +'no': Norsk +nr: isiNdebele +nv: Diné bizaad +ny: chiCheŵa +oc: occitan +oj: ᐊᓂᔑᓈᐯᒧᐎᓐ +om: Afaan Oromoo +or: ଓଡ଼ିଆ +os: ирон æвзаг +pa: ਪੰਜਾਬੀ +pi: पाऴि +pl: Polski +ps: پښتو +pt: português +qu: Runa Simi +rm: rumantsch grischun +rn: Ikirundi +ro: Română +ru: русский язык +rw: Ikinyarwanda +sa: संस्कृतम् +sc: sardu +sd: सिन्धी +se: Davvisámegiella +sg: yângâ tî sängö +si: සිංහල +sk: slovenčina +sl: slovenščina +sn: chiShona +so: Soomaaliga +sq: shqip +sr: српски језик +ss: SiSwati +st: Sesotho +su: Basa Sunda +sv: svenska +sw: Kiswahili +ta: தமிழ் +te: తెలుగు +tg: тоҷикӣ +th: ไทย +ti: ትግርኛ +tk: Türkmen +tl: Wikang Tagalog +tn: Setswana +to: faka Tonga +tr: Türkçe +ts: Xitsonga +tt: татар теле +tw: Twi +ty: Reo Tahiti +ug: ئۇيغۇرچە‎ +uk: українська мова +ur: اردو +uz: Ўзбек +ve: Tshivenḓa +vi: Tiếng Việt +vo: Volapük +wa: walon +wo: Wollof +xh: isiXhosa +yi: ייִדיש +yo: Yorùbá +za: Saɯ cueŋƅ +zh: 汉语 +zh-hant: 繁體中文 +zu: isiZulu diff --git a/docs/pl/docs/index.md b/docs/pl/docs/index.md index 43a20383ca1fd..49f5c2b011734 100644 --- a/docs/pl/docs/index.md +++ b/docs/pl/docs/index.md @@ -24,7 +24,7 @@ --- -FastAPI to nowoczesny, wydajny framework webowy do budowania API z użyciem Pythona 3.6+ bazujący na standardowym typowaniu Pythona. +FastAPI to nowoczesny, wydajny framework webowy do budowania API z użyciem Pythona 3.8+ bazujący na standardowym typowaniu Pythona. Kluczowe cechy: diff --git a/docs/ru/docs/index.md b/docs/ru/docs/index.md index 97a3947bd3f25..6c99f623ddc9d 100644 --- a/docs/ru/docs/index.md +++ b/docs/ru/docs/index.md @@ -321,7 +321,7 @@ def update_item(item_id: int, item: Item): Таким образом, вы объявляете **один раз** типы параметров, тело и т. д. в качестве параметров функции. -Вы делаете это испльзуя стандартную современную типизацию Python. +Вы делаете это используя стандартную современную типизацию Python. Вам не нужно изучать новый синтаксис, методы или классы конкретной библиотеки и т. д. diff --git a/docs/ru/docs/learn/index.md b/docs/ru/docs/learn/index.md new file mode 100644 index 0000000000000..b2e4cabc751a6 --- /dev/null +++ b/docs/ru/docs/learn/index.md @@ -0,0 +1,5 @@ +# Обучение + +Здесь представлены вводные разделы и учебные пособия для изучения **FastAPI**. + +Вы можете считать это **книгой**, **курсом**, **официальным** и рекомендуемым способом изучения FastAPI. 😎 diff --git a/docs/ru/docs/tutorial/background-tasks.md b/docs/ru/docs/tutorial/background-tasks.md index 7a3cf6d839f91..73ba860bc3dd9 100644 --- a/docs/ru/docs/tutorial/background-tasks.md +++ b/docs/ru/docs/tutorial/background-tasks.md @@ -71,7 +71,7 @@ В этом примере сообщения будут записаны в `log.txt` *после* того, как ответ сервера был отправлен. -Если бы в запросе была очередь `q`, она бы первой записалась в `log.txt` фоновой задачей (потому что вызывается в зависимости `get_query`). +Если бы в запрос был передан query-параметр `q`, он бы первыми записался в `log.txt` фоновой задачей (потому что вызывается в зависимости `get_query`). После другая фоновая задача, которая была сгенерирована в функции, запишет сообщение из параметра `email`. diff --git a/docs/ru/docs/tutorial/body-nested-models.md b/docs/ru/docs/tutorial/body-nested-models.md index a6d123d30dc16..bbf9b768597c1 100644 --- a/docs/ru/docs/tutorial/body-nested-models.md +++ b/docs/ru/docs/tutorial/body-nested-models.md @@ -85,7 +85,7 @@ my_list: List[str] И в Python есть специальный тип данных для множеств уникальных элементов - `set`. -Тогда мы может обьявить поле `tags` как множество строк: +Тогда мы можем обьявить поле `tags` как множество строк: === "Python 3.10+" diff --git a/docs/ru/docs/tutorial/debugging.md b/docs/ru/docs/tutorial/debugging.md index 755d98cf20d28..38709e56df7c3 100644 --- a/docs/ru/docs/tutorial/debugging.md +++ b/docs/ru/docs/tutorial/debugging.md @@ -22,7 +22,7 @@ $ python myapp.py -но не вызывался, когда другой файл импортирует это, например:: +но не вызывался, когда другой файл импортирует это, например: ```Python from myapp import app diff --git a/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md new file mode 100644 index 0000000000000..b6ad25dafcc95 --- /dev/null +++ b/docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md @@ -0,0 +1,478 @@ +# Классы как зависимости + +Прежде чем углубиться в систему **Внедрения Зависимостей**, давайте обновим предыдущий пример. + +## `Словарь` из предыдущего примера + +В предыдущем примере мы возвращали `словарь` из нашей зависимости: + +=== "Python 3.10+" + + ```Python hl_lines="9" + {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="11" + {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="12" + {!> ../../../docs_src/dependencies/tutorial001_an.py!} + ``` + +=== "Python 3.10+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python hl_lines="7" + {!> ../../../docs_src/dependencies/tutorial001_py310.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python hl_lines="11" + {!> ../../../docs_src/dependencies/tutorial001.py!} + ``` + +Но затем мы получаем `словарь` в параметре `commons` *функции операции пути*. И мы знаем, что редакторы не могут обеспечить достаточную поддержку для `словаря`, поскольку они не могут знать их ключи и типы значений. + +Мы можем сделать лучше... + +## Что делает зависимость + +До сих пор вы видели зависимости, объявленные как функции. + +Но это не единственный способ объявления зависимостей (хотя, вероятно, более распространенный). + +Ключевым фактором является то, что зависимость должна быть "вызываемой". + +В Python "**вызываемый**" - это все, что Python может "вызвать", как функцию. + +Так, если у вас есть объект `something` (который может _не_ быть функцией) и вы можете "вызвать" его (выполнить) как: + +```Python +something() +``` + +или + +```Python +something(some_argument, some_keyword_argument="foo") +``` + +в таком случае он является "вызываемым". + +## Классы как зависимости + +Вы можете заметить, что для создания экземпляра класса в Python используется тот же синтаксис. + +Например: + +```Python +class Cat: + def __init__(self, name: str): + self.name = name + + +fluffy = Cat(name="Mr Fluffy") +``` + +В данном случае `fluffy` является экземпляром класса `Cat`. + +А чтобы создать `fluffy`, вы "вызываете" `Cat`. + +Таким образом, класс в Python также является **вызываемым**. + +Тогда в **FastAPI** в качестве зависимости можно использовать класс Python. + +На самом деле FastAPI проверяет, что переданный объект является "вызываемым" (функция, класс или что-либо еще) и указаны необходимые для его вызова параметры. + +Если вы передаёте что-то, что можно "вызывать" в качестве зависимости в **FastAPI**, то он будет анализировать параметры, необходимые для "вызова" этого объекта и обрабатывать их так же, как параметры *функции операции пути*. Включая подзависимости. + +Это относится и к вызываемым объектам без параметров. Работа с ними происходит точно так же, как и для *функций операции пути* без параметров. + +Теперь мы можем изменить зависимость `common_parameters`, указанную выше, на класс `CommonQueryParams`: + +=== "Python 3.10+" + + ```Python hl_lines="11-15" + {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="11-15" + {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="12-16" + {!> ../../../docs_src/dependencies/tutorial002_an.py!} + ``` + +=== "Python 3.10+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python hl_lines="9-13" + {!> ../../../docs_src/dependencies/tutorial002_py310.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python hl_lines="11-15" + {!> ../../../docs_src/dependencies/tutorial002.py!} + ``` + +Обратите внимание на метод `__init__`, используемый для создания экземпляра класса: + +=== "Python 3.10+" + + ```Python hl_lines="12" + {!> ../../../docs_src/dependencies/tutorial002_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="12" + {!> ../../../docs_src/dependencies/tutorial002_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="13" + {!> ../../../docs_src/dependencies/tutorial002_an.py!} + ``` + +=== "Python 3.10+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python hl_lines="10" + {!> ../../../docs_src/dependencies/tutorial002_py310.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python hl_lines="12" + {!> ../../../docs_src/dependencies/tutorial002.py!} + ``` + +...имеет те же параметры, что и ранее используемая функция `common_parameters`: + +=== "Python 3.10+" + + ```Python hl_lines="8" + {!> ../../../docs_src/dependencies/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/dependencies/tutorial001_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="10" + {!> ../../../docs_src/dependencies/tutorial001_an.py!} + ``` + +=== "Python 3.10+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python hl_lines="6" + {!> ../../../docs_src/dependencies/tutorial001_py310.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python hl_lines="9" + {!> ../../../docs_src/dependencies/tutorial001.py!} + ``` + +Эти параметры и будут использоваться **FastAPI** для "решения" зависимости. + +В обоих случаях она будет иметь: + +* Необязательный параметр запроса `q`, представляющий собой `str`. +* Параметр запроса `skip`, представляющий собой `int`, по умолчанию `0`. +* Параметр запроса `limit`, представляющий собой `int`, по умолчанию равный `100`. + +В обоих случаях данные будут конвертированы, валидированы, документированы по схеме OpenAPI и т.д. + +## Как это использовать + +Теперь вы можете объявить свою зависимость, используя этот класс. + +=== "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.6+" + + ```Python hl_lines="20" + {!> ../../../docs_src/dependencies/tutorial002_an.py!} + ``` + +=== "Python 3.10+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python hl_lines="17" + {!> ../../../docs_src/dependencies/tutorial002_py310.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial002.py!} + ``` + +**FastAPI** вызывает класс `CommonQueryParams`. При этом создается "экземпляр" этого класса, который будет передан в качестве параметра `commons` в вашу функцию. + +## Аннотация типа или `Depends` + +Обратите внимание, что в приведенном выше коде мы два раза пишем `CommonQueryParams`: + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python + commons: CommonQueryParams = Depends(CommonQueryParams) + ``` + +=== "Python 3.6+" + + ```Python + commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] + ``` + +Последний параметр `CommonQueryParams`, в: + +```Python +... Depends(CommonQueryParams) +``` + +...это то, что **FastAPI** будет использовать, чтобы узнать, что является зависимостью. + +Из него FastAPI извлечёт объявленные параметры и именно их будет вызывать. + +--- + +В этом случае первый `CommonQueryParams`, в: + +=== "Python 3.6+" + + ```Python + commons: Annotated[CommonQueryParams, ... + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python + commons: CommonQueryParams ... + ``` + +...не имеет никакого специального значения для **FastAPI**. FastAPI не будет использовать его для преобразования данных, валидации и т.д. (поскольку для этого используется `Depends(CommonQueryParams)`). + +На самом деле можно написать просто: + +=== "Python 3.6+" + + ```Python + commons: Annotated[Any, Depends(CommonQueryParams)] + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python + commons = Depends(CommonQueryParams) + ``` + +...как тут: + +=== "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.6+" + + ```Python hl_lines="20" + {!> ../../../docs_src/dependencies/tutorial003_an.py!} + ``` + +=== "Python 3.10+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python hl_lines="17" + {!> ../../../docs_src/dependencies/tutorial003_py310.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial003.py!} + ``` + +Но объявление типа приветствуется, так как в этом случае ваш редактор будет знать, что будет передано в качестве параметра `commons`, и тогда он сможет помочь вам с автодополнением, проверкой типов и т.д: + + + +## Сокращение + +Но вы видите, что здесь мы имеем некоторое повторение кода, дважды написав `CommonQueryParams`: + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python + commons: CommonQueryParams = Depends(CommonQueryParams) + ``` + +=== "Python 3.6+" + + ```Python + commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] + ``` + +Для случаев, когда зависимостью является *конкретный* класс, который **FastAPI** "вызовет" для создания экземпляра этого класса, можно использовать укороченную запись. + + +Вместо того чтобы писать: + +=== "Python 3.6+" + + ```Python + commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)] + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python + commons: CommonQueryParams = Depends(CommonQueryParams) + ``` + +...следует написать: + +=== "Python 3.6+" + + ```Python + commons: Annotated[CommonQueryParams, Depends()] + ``` + +=== "Python 3.6 без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python + commons: CommonQueryParams = Depends() + ``` + +Вы объявляете зависимость как тип параметра и используете `Depends()` без какого-либо параметра, вместо того чтобы *снова* писать полный класс внутри `Depends(CommonQueryParams)`. + +Аналогичный пример будет выглядеть следующим образом: + +=== "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.6+" + + ```Python hl_lines="20" + {!> ../../../docs_src/dependencies/tutorial004_an.py!} + ``` + +=== "Python 3.10+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python hl_lines="17" + {!> ../../../docs_src/dependencies/tutorial004_py310.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Рекомендуется использовать версию с `Annotated` если возможно. + + ```Python hl_lines="19" + {!> ../../../docs_src/dependencies/tutorial004.py!} + ``` + +...и **FastAPI** будет знать, что делать. + +!!! tip "Подсказка" + Если это покажется вам более запутанным, чем полезным, не обращайте внимания, это вам не *нужно*. + + Это просто сокращение. Потому что **FastAPI** заботится о том, чтобы помочь вам свести к минимуму повторение кода. diff --git a/docs/ru/docs/tutorial/request-files.md b/docs/ru/docs/tutorial/request-files.md new file mode 100644 index 0000000000000..00f8c8377059f --- /dev/null +++ b/docs/ru/docs/tutorial/request-files.md @@ -0,0 +1,314 @@ +# Загрузка файлов + +Используя класс `File`, мы можем позволить клиентам загружать файлы. + +!!! info "Дополнительная информация" + Чтобы получать загруженные файлы, сначала установите `python-multipart`. + + Например: `pip install python-multipart`. + + Это связано с тем, что загружаемые файлы передаются как данные формы. + +## Импорт `File` + +Импортируйте `File` и `UploadFile` из модуля `fastapi`: + +=== "Python 3.9+" + + ```Python hl_lines="3" + {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="1" + {!> ../../../docs_src/request_files/tutorial001_an.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="1" + {!> ../../../docs_src/request_files/tutorial001.py!} + ``` + +## Определите параметры `File` + +Создайте параметры `File` так же, как вы это делаете для `Body` или `Form`: + +=== "Python 3.9+" + + ```Python hl_lines="9" + {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="8" + {!> ../../../docs_src/request_files/tutorial001_an.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="7" + {!> ../../../docs_src/request_files/tutorial001.py!} + ``` + +!!! info "Дополнительная информация" + `File` - это класс, который наследуется непосредственно от `Form`. + + Но помните, что когда вы импортируете `Query`, `Path`, `File` и другие из `fastapi`, на самом деле это функции, которые возвращают специальные классы. + +!!! tip "Подсказка" + Для объявления тела файла необходимо использовать `File`, поскольку в противном случае параметры будут интерпретироваться как параметры запроса или параметры тела (JSON). + +Файлы будут загружены как данные формы. + +Если вы объявите тип параметра у *функции операции пути* как `bytes`, то **FastAPI** прочитает файл за вас, и вы получите его содержимое в виде `bytes`. + +Следует иметь в виду, что все содержимое будет храниться в памяти. Это хорошо подходит для небольших файлов. + +Однако возможны случаи, когда использование `UploadFile` может оказаться полезным. + +## Загрузка файла с помощью `UploadFile` + +Определите параметр файла с типом `UploadFile`: + +=== "Python 3.9+" + + ```Python hl_lines="14" + {!> ../../../docs_src/request_files/tutorial001_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="13" + {!> ../../../docs_src/request_files/tutorial001_an.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="12" + {!> ../../../docs_src/request_files/tutorial001.py!} + ``` + +Использование `UploadFile` имеет ряд преимуществ перед `bytes`: + +* Использовать `File()` в значении параметра по умолчанию не обязательно. +* При этом используется "буферный" файл: + * Файл, хранящийся в памяти до максимального предела размера, после преодоления которого он будет храниться на диске. +* Это означает, что он будет хорошо работать с большими файлами, такими как изображения, видео, большие бинарные файлы и т.д., не потребляя при этом всю память. +* Из загруженного файла можно получить метаданные. +* Он реализует file-like `async` интерфейс. +* Он предоставляет реальный объект Python `SpooledTemporaryFile` который вы можете передать непосредственно другим библиотекам, которые ожидают файл в качестве объекта. + +### `UploadFile` + +`UploadFile` имеет следующие атрибуты: + +* `filename`: Строка `str` с исходным именем файла, который был загружен (например, `myimage.jpg`). +* `content_type`: Строка `str` с типом содержимого (MIME type / media type) (например, `image/jpeg`). +* `file`: `SpooledTemporaryFile` (a file-like объект). Это фактический файл Python, который можно передавать непосредственно другим функциям или библиотекам, ожидающим файл в качестве объекта. + +`UploadFile` имеет следующие методы `async`. Все они вызывают соответствующие файловые методы (используя внутренний SpooledTemporaryFile). + +* `write(data)`: Записать данные `data` (`str` или `bytes`) в файл. +* `read(size)`: Прочитать количество `size` (`int`) байт/символов из файла. +* `seek(offset)`: Перейти к байту на позиции `offset` (`int`) в файле. + * Наример, `await myfile.seek(0)` перейдет к началу файла. + * Это особенно удобно, если вы один раз выполнили команду `await myfile.read()`, а затем вам нужно прочитать содержимое файла еще раз. +* `close()`: Закрыть файл. + +Поскольку все эти методы являются `async` методами, вам следует использовать "await" вместе с ними. + +Например, внутри `async` *функции операции пути* можно получить содержимое с помощью: + +```Python +contents = await myfile.read() +``` + +Если вы находитесь внутри обычной `def` *функции операции пути*, можно получить прямой доступ к файлу `UploadFile.file`, например: + +```Python +contents = myfile.file.read() +``` + +!!! note "Технические детали `async`" + При использовании методов `async` **FastAPI** запускает файловые методы в пуле потоков и ожидает их. + +!!! note "Технические детали Starlette" + **FastAPI** наследует `UploadFile` непосредственно из **Starlette**, но добавляет некоторые детали для совместимости с **Pydantic** и другими частями FastAPI. + +## Про данные формы ("Form Data") + +Способ, которым HTML-формы (`
`) отправляют данные на сервер, обычно использует "специальную" кодировку для этих данных, отличную от JSON. + +**FastAPI** позаботится о том, чтобы считать эти данные из нужного места, а не из JSON. + +!!! note "Технические детали" + Данные из форм обычно кодируются с использованием "media type" `application/x-www-form-urlencoded` когда он не включает файлы. + + Но когда форма включает файлы, она кодируется как multipart/form-data. Если вы используете `File`, **FastAPI** будет знать, что ему нужно получить файлы из нужной части тела. + + Если вы хотите узнать больше об этих кодировках и полях форм, перейдите по ссылке MDN web docs for POST. + +!!! warning "Внимание" + В операции *функции операции пути* можно объявить несколько параметров `File` и `Form`, но нельзя также объявлять поля `Body`, которые предполагается получить в виде JSON, поскольку тело запроса будет закодировано с помощью `multipart/form-data`, а не `application/json`. + + Это не является ограничением **FastAPI**, это часть протокола HTTP. + +## Необязательная загрузка файлов + +Вы можете сделать загрузку файла необязательной, используя стандартные аннотации типов и установив значение по умолчанию `None`: + +=== "Python 3.10+" + + ```Python hl_lines="9 17" + {!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="9 17" + {!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="10 18" + {!> ../../../docs_src/request_files/tutorial001_02_an.py!} + ``` + +=== "Python 3.10+ без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="7 15" + {!> ../../../docs_src/request_files/tutorial001_02_py310.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="9 17" + {!> ../../../docs_src/request_files/tutorial001_02.py!} + ``` + +## `UploadFile` с дополнительными метаданными + +Вы также можете использовать `File()` вместе с `UploadFile`, например, для установки дополнительных метаданных: + +=== "Python 3.9+" + + ```Python hl_lines="9 15" + {!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="8 14" + {!> ../../../docs_src/request_files/tutorial001_03_an.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="7 13" + {!> ../../../docs_src/request_files/tutorial001_03.py!} + ``` + +## Загрузка нескольких файлов + +Можно одновременно загружать несколько файлов. + +Они будут связаны с одним и тем же "полем формы", отправляемым с помощью данных формы. + +Для этого необходимо объявить список `bytes` или `UploadFile`: + +=== "Python 3.9+" + + ```Python hl_lines="10 15" + {!> ../../../docs_src/request_files/tutorial002_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="11 16" + {!> ../../../docs_src/request_files/tutorial002_an.py!} + ``` + +=== "Python 3.9+ без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="8 13" + {!> ../../../docs_src/request_files/tutorial002_py39.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="10 15" + {!> ../../../docs_src/request_files/tutorial002.py!} + ``` + +Вы получите, как и было объявлено, список `list` из `bytes` или `UploadFile`. + +!!! note "Technical Details" + Можно также использовать `from starlette.responses import HTMLResponse`. + + **FastAPI** предоставляет тот же `starlette.responses`, что и `fastapi.responses`, просто для удобства разработчика. Однако большинство доступных ответов поступает непосредственно из Starlette. + +### Загрузка нескольких файлов с дополнительными метаданными + +Так же, как и раньше, вы можете использовать `File()` для задания дополнительных параметров, даже для `UploadFile`: + +=== "Python 3.9+" + + ```Python hl_lines="11 18-20" + {!> ../../../docs_src/request_files/tutorial003_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="12 19-21" + {!> ../../../docs_src/request_files/tutorial003_an.py!} + ``` + +=== "Python 3.9+ без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="9 16" + {!> ../../../docs_src/request_files/tutorial003_py39.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="11 18" + {!> ../../../docs_src/request_files/tutorial003.py!} + ``` + +## Резюме + +Используйте `File`, `bytes` и `UploadFile` для работы с файлами, которые будут загружаться и передаваться в виде данных формы. diff --git a/docs/ru/docs/tutorial/request-forms-and-files.md b/docs/ru/docs/tutorial/request-forms-and-files.md new file mode 100644 index 0000000000000..3f587c38a3ae7 --- /dev/null +++ b/docs/ru/docs/tutorial/request-forms-and-files.md @@ -0,0 +1,69 @@ +# Файлы и формы в запросе + +Вы можете определять файлы и поля формы одновременно, используя `File` и `Form`. + +!!! info "Дополнительная информация" + Чтобы получать загруженные файлы и/или данные форм, сначала установите `python-multipart`. + + Например: `pip install python-multipart`. + +## Импортируйте `File` и `Form` + +=== "Python 3.9+" + + ```Python hl_lines="3" + {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="1" + {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="1" + {!> ../../../docs_src/request_forms_and_files/tutorial001.py!} + ``` + +## Определите параметры `File` и `Form` + +Создайте параметры файла и формы таким же образом, как для `Body` или `Query`: + +=== "Python 3.9+" + + ```Python hl_lines="10-12" + {!> ../../../docs_src/request_forms_and_files/tutorial001_an_py39.py!} + ``` + +=== "Python 3.6+" + + ```Python hl_lines="9-11" + {!> ../../../docs_src/request_forms_and_files/tutorial001_an.py!} + ``` + +=== "Python 3.6+ без Annotated" + + !!! tip "Подсказка" + Предпочтительнее использовать версию с аннотацией, если это возможно. + + ```Python hl_lines="8" + {!> ../../../docs_src/request_forms_and_files/tutorial001.py!} + ``` + +Файлы и поля формы будут загружены в виде данных формы, и вы получите файлы и поля формы. + +Вы можете объявить некоторые файлы как `bytes`, а некоторые - как `UploadFile`. + +!!! warning "Внимание" + Вы можете объявить несколько параметров `File` и `Form` в операции *path*, но вы не можете также объявить поля `Body`, которые вы ожидаете получить в виде JSON, так как запрос будет иметь тело, закодированное с помощью `multipart/form-data` вместо `application/json`. + + Это не ограничение **Fast API**, это часть протокола HTTP. + +## Резюме + +Используйте `File` и `Form` вместе, когда необходимо получить данные и файлы в одном запросе. diff --git a/docs/tr/docs/external-links.md b/docs/tr/docs/external-links.md new file mode 100644 index 0000000000000..78eaf1729d80b --- /dev/null +++ b/docs/tr/docs/external-links.md @@ -0,0 +1,33 @@ +# Harici Bağlantılar ve Makaleler + +**FastAPI** sürekli büyüyen harika bir topluluğa sahiptir. + +**FastAPI** ile alakalı birçok yazı, makale, araç ve proje bulunmaktadır. + +Bunlardan bazılarının tamamlanmamış bir listesi aşağıda bulunmaktadır. + +!!! tip "İpucu" + Eğer **FastAPI** ile alakalı henüz burada listelenmemiş bir makale, proje, araç veya başka bir şeyiniz varsa, bunu eklediğiniz bir Pull Request oluşturabilirsiniz. + +{% for section_name, section_content in external_links.items() %} + +## {{ section_name }} + +{% for lang_name, lang_content in section_content.items() %} + +### {{ lang_name }} + +{% for item in lang_content %} + +* {{ item.title }} by {{ item.author }}. + +{% endfor %} +{% endfor %} +{% endfor %} + +## Projeler + +`fastapi` konulu en son GitHub projeleri: + +
+
diff --git a/docs/tr/docs/index.md b/docs/tr/docs/index.md index e61f5b82cdfdf..ac8830880b35d 100644 --- a/docs/tr/docs/index.md +++ b/docs/tr/docs/index.md @@ -2,45 +2,47 @@ FastAPI

- FastAPI framework, yüksek performanslı, öğrenmesi kolay, geliştirmesi hızlı, kullanıma sunulmaya hazır. + FastAPI framework, yüksek performanslı, öğrenmesi oldukça kolay, kodlaması hızlı, kullanıma hazır

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

--- -**dokümantasyon**: https://fastapi.tiangolo.com +**Dokümantasyon**: https://fastapi.tiangolo.com -**Kaynak kodu**: https://github.com/tiangolo/fastapi +**Kaynak Kod**: https://github.com/tiangolo/fastapi --- -FastAPI, Python 3.8+'nın standart type hintlerine dayanan modern ve hızlı (yüksek performanslı) API'lar oluşturmak için kullanılabilecek web framework'ü. +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. -Ana özellikleri: +Temel özellikleri şunlardır: -* **Hızlı**: çok yüksek performanslı, **NodeJS** ve **Go** ile eşdeğer seviyede performans sağlıyor, (Starlette ve Pydantic sayesinde.) [Python'un en hızlı frameworklerinden bir tanesi.](#performans). -* **Kodlaması hızlı**: Yeni özellikler geliştirmek neredeyse %200 - %300 daha hızlı. * -* **Daha az bug**: Geliştirici (insan) kaynaklı hatalar neredeyse %40 azaltıldı. * -* **Sezgileri güçlü**: Editor (otomatik-tamamlama) desteği harika. Otomatik tamamlama her yerde. Debuglamak ile daha az zaman harcayacaksınız. -* **Kolay**: Öğrenmesi ve kullanması kolay olacak şekilde. Doküman okumak için harcayacağınız süre azaltıldı. -* **Kısa**: Kod tekrarını minimuma indirdik. Fonksiyon parametrelerinin tiplerini belirtmede farklı yollar sunarak karşılaşacağınız bug'ları azalttık. -* **Güçlü**: Otomatik dokümantasyon ile beraber, kullanıma hazır kod yaz. +* **Hızlı**: Çok yüksek performanslı, **NodeJS** ve **Go** ile eşit düzeyde (Starlette ve Pydantic sayesinde). [En hızlı Python framework'lerinden bir tanesidir](#performans). +* **Kodlaması Hızlı**: Geliştirme hızını yaklaşık %200 ile %300 aralığında arttırır. * +* **Daha az hata**: İnsan (geliştirici) kaynaklı hataları yaklaşık %40 azaltır. * +* **Sezgisel**: Muhteşem bir editör desteği. Her yerde otomatik tamamlama. Hata ayıklama ile daha az zaman harcayacaksınız. +* **Kolay**: Öğrenmesi ve kullanması kolay olacak şekilde tasarlandı. Doküman okuma ile daha az zaman harcayacaksınız. +* **Kısa**: Kod tekrarı minimize edildi. Her parametre tanımlamasında birden fazla özellik ve daha az hatayla karşılaşacaksınız. +* **Güçlü**: Otomatik ve etkileşimli dokümantasyon ile birlikte, kullanıma hazır kod elde edebilirsiniz. +* **Standard öncelikli**: API'lar için açık standartlara dayalı (ve tamamen uyumlu); OpenAPI (eski adıyla Swagger) ve JSON Schema. -* **Standartlar belirli**: Tamamiyle API'ların açık standartlara bağlı ve (tam uyumlululuk içerisinde); OpenAPI (eski adıyla Swagger) ve JSON Schema. +* ilgili kanılar, dahili geliştirme ekibinin geliştirdikleri ürünlere yaptıkları testlere dayanmaktadır. -* Bahsi geçen rakamsal ifadeler tamamiyle, geliştirme takımının kendi sundukları ürünü geliştirirken yaptıkları testlere dayanmakta. - -## Sponsors +## Sponsorlar @@ -55,63 +57,61 @@ Ana özellikleri: -Other sponsors +Diğer Sponsorlar ## Görüşler - -"_[...] Bugünlerde **FastAPI**'ı çok fazla kullanıyorum [...] Aslına bakarsanız **Microsoft'taki Machine Learning servislerimizin** hepsinde kullanmayı düşünüyorum. FastAPI ile geliştirdiğimiz servislerin bazıları çoktan **Windows**'un ana ürünlerine ve **Office** ürünlerine entegre edilmeye başlandı bile._" +"_[...] Bugünlerde **FastAPI**'ı çok fazla kullanıyorum. [...] Aslında bunu ekibimin **Microsoft'taki Machine Learning servislerinin** tamamında kullanmayı planlıyorum. Bunlardan bazıları **Windows**'un ana ürünlerine ve **Office** ürünlerine entegre ediliyor._"
Kabir Khan - Microsoft (ref)
--- - -"_**FastAPI**'ı **tahminlerimiz**'i sorgulanabilir hale getirmek için **REST** mimarisı ile beraber server üzerinde kullanmaya başladık._" - +"_**FastAPI**'ı **tahminlerimiz**'i sorgulanabilir hale getirecek bir **REST** sunucu oluşturmak için benimsedik/kullanmaya başladık._"
Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - Uber (ref)
--- - -"_**Netflix** **kriz yönetiminde** orkestrasyon yapabilmek için geliştirdiği yeni framework'ü **Dispatch**'in, açık kaynak versiyonunu paylaşmaktan gurur duyuyor. [**FastAPI** ile yapıldı.]_" +"_**Netflix**, **kriz yönetiminde** orkestrasyon yapabilmek için geliştirdiği yeni framework'ü **Dispatch**'in, açık kaynak sürümünü paylaşmaktan gurur duyuyor. [**FastAPI** ile yapıldı.]_"
Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix (ref)
--- - "_**FastAPI** için ayın üzerindeymişcesine heyecanlıyım. Çok eğlenceli!_" -
Brian Okken - Python Bytes podcast host (ref)
--- -"_Dürüst olmak gerekirse, geliştirdiğin şey bir çok açıdan çok sağlam ve parlak gözüküyor. Açıkcası benim **Hug**'ı tasarlarken yapmaya çalıştığım şey buydu - bunu birisinin başardığını görmek gerçekten çok ilham verici._" +"_Dürüst olmak gerekirse, inşa ettiğiniz şey gerçekten sağlam ve profesyonel görünüyor. Birçok açıdan **Hug**'ın olmasını istediğim şey tam da bu - böyle bir şeyi inşa eden birini görmek gerçekten ilham verici._" -
Timothy Crosley - Hug'ın Yaratıcısı (ref)
+
Timothy Crosley - Hug'ın Yaratıcısı (ref)
--- -"_Eğer REST API geliştirmek için **modern bir framework** öğrenme arayışında isen, **FastAPI**'a bir göz at [...] Hızlı, kullanımı ve öğrenmesi kolay. [...]_" +"_Eğer REST API geliştirmek için **modern bir framework** öğrenme arayışında isen, **FastAPI**'a bir göz at [...] Hızlı, kullanımı ve öğrenmesi kolay. [...]_" + +"_**API** servislerimizi **FastAPI**'a taşıdık [...] Sizin de beğeneceğinizi düşünüyoruz. [...]_" -"_Biz **API** servislerimizi **FastAPI**'a geçirdik [...] Sizin de beğeneceğinizi düşünüyoruz. [...]_" +
Ines Montani - Matthew Honnibal - Explosion AI kurucuları - spaCy yaratıcıları (ref) - (ref)
+--- +"_Python ile kullanıma hazır bir API oluşturmak isteyen herhangi biri için, **FastAPI**'ı şiddetle tavsiye ederim. **Harika tasarlanmış**, **kullanımı kolay** ve **yüksek ölçeklenebilir**, API odaklı geliştirme stratejimizin **ana bileşeni** haline geldi ve Virtual TAC Engineer gibi birçok otomasyon ve servisi yönetiyor._" -
Ines Montani - Matthew Honnibal - Explosion AI kurucuları - spaCy yaratıcıları (ref) - (ref)
+
Deon Pillsbury - Cisco (ref)
--- -## **Typer**, komut satırı uygulamalarının FastAPI'ı +## Komut Satırı Uygulamalarının FastAPI'ı: **Typer** -Eğer API yerine komut satırı uygulaması geliştiriyor isen **Typer**'a bir göz at. +Eğer API yerine, terminalde kullanılmak üzere bir komut satırı uygulaması geliştiriyorsanız **Typer**'a göz atabilirsiniz. -**Typer** kısaca FastAPI'ın küçük kız kardeşi. Komut satırı uygulamalarının **FastAPI'ı** olması hedeflendi. ⌨️ 🚀 +**Typer** kısaca FastAPI'ın küçük kardeşi. Ve hedefi komut satırı uygulamalarının **FastAPI'ı** olmak. ⌨️ 🚀 ## Gereksinimler @@ -122,7 +122,7 @@ FastAPI iki devin omuzları üstünde duruyor: * Web tarafı için Starlette. * Data tarafı için Pydantic. -## Yükleme +## Kurulum
@@ -134,7 +134,7 @@ $ pip install fastapi
-Uygulamanı kullanılabilir hale getirmek için Uvicorn ya da Hypercorn gibi bir ASGI serverına ihtiyacın olacak. +Uygulamamızı kullanılabilir hale getirmek için Uvicorn ya da Hypercorn gibi bir ASGI sunucusuna ihtiyacımız olacak.
@@ -148,9 +148,9 @@ $ pip install "uvicorn[standard]" ## Örnek -### Şimdi dene +### Kodu Oluşturalım -* `main.py` adında bir dosya oluştur : +* `main.py` adında bir dosya oluşturup içine şu kodu yapıştıralım: ```Python from typing import Union @@ -173,9 +173,9 @@ def read_item(item_id: int, q: Union[str, None] = None):
Ya da async def... -Eğer kodunda `async` / `await` var ise, `async def` kullan: +Eğer kodunuzda `async` / `await` varsa, `async def` kullanalım: -```Python hl_lines="9 14" +```Python hl_lines="9 14" from typing import Union from fastapi import FastAPI @@ -195,13 +195,13 @@ async def read_item(item_id: int, q: Union[str, None] = None): **Not**: -Eğer ne olduğunu bilmiyor isen _"Acelen mi var?"_ kısmını oku `async` ve `await`. +Eğer bu konu hakkında bilginiz yoksa `async` ve `await` dokümantasyonundaki _"Aceleniz mi var?"_ kısmını kontrol edebilirsiniz.
-### Çalıştır +### Kodu Çalıştıralım -Serverı aşağıdaki komut ile çalıştır: +Sunucuyu aşağıdaki komutla çalıştıralım:
@@ -218,56 +218,56 @@ INFO: Application startup complete.
-Çalıştırdığımız uvicorn main:app --reload hakkında... +uvicorn main:app --reload komutuyla ilgili... -`uvicorn main:app` şunları ifade ediyor: +`uvicorn main:app` komutunu şu şekilde açıklayabiliriz: * `main`: dosya olan `main.py` (yani Python "modülü"). -* `app`: ise `main.py` dosyasının içerisinde oluşturduğumuz `app = FastAPI()` 'a denk geliyor. -* `--reload`: ise kodda herhangi bir değişiklik yaptığımızda serverın yapılan değişiklerileri algılayıp, değişiklikleri siz herhangi bir şey yapmadan uygulamasını sağlıyor. +* `app`: ise `main.py` dosyasının içerisinde `app = FastAPI()` satırında oluşturduğumuz `FastAPI` nesnesi. +* `--reload`: kod değişikliklerinin ardından sunucuyu otomatik olarak yeniden başlatır. Bu parameteyi sadece geliştirme aşamasında kullanmalıyız.
-### Dokümantasyonu kontrol et +### Şimdi de Kontrol Edelim -Browserını aç ve şu linke git http://127.0.0.1:8000/items/5?q=somequery. +Tarayıcımızda şu bağlantıyı açalım http://127.0.0.1:8000/items/5?q=somequery. -Bir JSON yanıtı göreceksin: +Aşağıdaki gibi bir JSON yanıtıyla karşılaşacağız: ```JSON {"item_id": 5, "q": "somequery"} ``` -Az önce oluşturduğun API: +Az önce oluşturduğumuz API: -* `/` ve `/items/{item_id}` adreslerine HTTP talebi alabilir hale geldi. -* İki _adresde_ `GET` operasyonlarını (HTTP _metodları_ olarakta bilinen) yapabilir hale geldi. -* `/items/{item_id}` _adresi_ ayrıca bir `item_id` _adres parametresine_ sahip ve bu bir `int` olmak zorunda. -* `/items/{item_id}` _adresi_ opsiyonel bir `str` _sorgu paramtersine_ sahip bu da `q`. +* `/` ve `/items/{item_id}` _yollarına_ HTTP isteği alabilir. +* İki _yolda_ `GET` operasyonlarını (HTTP _metodları_ olarak da bilinen) kabul ediyor. +* `/items/{item_id}` _yolu_ `item_id` adında bir _yol parametresine_ sahip ve bu parametre `int` değer almak zorundadır. +* `/items/{item_id}` _yolu_ `q` adında bir _yol parametresine_ sahip ve bu parametre opsiyonel olmakla birlikte, `str` değer almak zorundadır. -### İnteraktif API dokümantasyonu +### Etkileşimli API Dokümantasyonu -Şimdi http://127.0.0.1:8000/docs adresine git. +Şimdi http://127.0.0.1:8000/docs bağlantısını açalım. -Senin için otomatik oluşturulmuş(Swagger UI tarafından sağlanan) interaktif bir API dokümanı göreceksin: +Swagger UI tarafından sağlanan otomatik etkileşimli bir API dokümantasyonu göreceğiz: ![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) -### Alternatif API dokümantasyonu +### Alternatif API Dokümantasyonu -Şimdi http://127.0.0.1:8000/redoc adresine git. +Şimdi http://127.0.0.1:8000/redoc bağlantısını açalım. -Senin için alternatif olarak (ReDoc tarafından sağlanan) bir API dokümantasyonu daha göreceksin: +ReDoc tarafından sağlanan otomatik dokümantasyonu göreceğiz: ![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) -## Örnek bir değişiklik +## Örneği Güncelleyelim -Şimdi `main.py` dosyasını değiştirelim ve body ile `PUT` talebi alabilir hale getirelim. +Şimdi `main.py` dosyasını, `PUT` isteğiyle birlikte bir gövde alacak şekilde değiştirelim. -Şimdi Pydantic sayesinde, Python'un standart tiplerini kullanarak bir body tanımlayacağız. +Gövdeyi Pydantic sayesinde standart python tiplerini kullanarak tanımlayalım. -```Python hl_lines="4 9 10 11 12 25 26 27" +```Python hl_lines="4 9-12 25-27" from typing import Union from fastapi import FastAPI @@ -297,41 +297,41 @@ def update_item(item_id: int, item: Item): return {"item_name": item.name, "item_id": item_id} ``` -Server otomatik olarak yeniden başlamalı (çünkü yukarıda `uvicorn`'u çalıştırırken `--reload` parametresini kullandık.). +Sunucu otomatik olarak yeniden başlamış olmalı (çünkü yukarıda `uvicorn` komutuyla birlikte `--reload` parametresini kullandık). -### İnteraktif API dokümantasyonu'nda değiştirme yapmak +### Etkileşimli API Dokümantasyonundaki Değişimi Görelim -Şimdi http://127.0.0.1:8000/docs bağlantısına tekrar git. +Şimdi http://127.0.0.1:8000/docs bağlantısına tekrar gidelim. -* İnteraktif API dokümantasyonu, yeni body ile beraber çoktan yenilenmiş olması lazım: +* Etkileşimli API dokümantasyonu, yeni gövdede dahil olmak üzere otomatik olarak güncellenmiş olacak: ![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) -* "Try it out"a tıkla, bu senin API parametleri üzerinde deneme yapabilmene izin veriyor: +* "Try it out" butonuna tıklayalım, bu işlem API parametleri üzerinde değişiklik yapmamıza ve doğrudan API ile etkileşime geçmemize imkan sağlayacak: ![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) -* Şimdi "Execute" butonuna tıkla, kullanıcı arayüzü otomatik olarak API'ın ile bağlantı kurarak ona bu parametreleri gönderecek ve sonucu karşına getirecek. +* Şimdi "Execute" butonuna tıklayalım, kullanıcı arayüzü API'ımız ile bağlantı kurup parametreleri gönderecek ve sonucu ekranımıza getirecek: ![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) -### Alternatif API dokümantasyonunda değiştirmek +### Alternatif API Dokümantasyonundaki Değişimi Görelim -Şimdi ise http://127.0.0.1:8000/redoc adresine git. +Şimdi ise http://127.0.0.1:8000/redoc bağlantısına tekrar gidelim. -* Alternatif dokümantasyonda koddaki değişimler ile beraber kendini yeni query ve body ile güncelledi. +* Alternatif dokümantasyonda yaptığımız değişiklikler ile birlikte yeni sorgu parametresi ve gövde bilgisi ile güncelemiş olacak: ![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) ### Özet -Özetleyecek olursak, URL, sorgu veya request body'deki parametrelerini fonksiyon parametresi olarak kullanıyorsun. Bu parametrelerin veri tiplerini bir kere belirtmen yeterli. +Özetlemek gerekirse, parametrelerin, gövdenin, vb. veri tiplerini fonksiyon parametreleri olarak **bir kere** tanımlıyoruz. -Type-hinting işlemini Python dilindeki standart veri tipleri ile yapabilirsin +Bu işlemi standart modern Python tipleriyle yapıyoruz. -Yeni bir syntax'e alışmana gerek yok, metodlar ve classlar zaten spesifik kütüphanelere ait. +Yeni bir sözdizimi yapısını, bir kütüphane özel metod veya sınıfları öğrenmeye gerek yoktur. -Sadece standart **Python 3.8+**. +Hepsi sadece **Python 3.8+** standartlarına dayalıdır. Örnek olarak, `int` tanımlamak için: @@ -339,64 +339,64 @@ Sadece standart **Python 3.8+**. item_id: int ``` -ya da daha kompleks `Item` tipi: +ya da daha kompleks herhangi bir python modelini tanımlayabiliriz, örneğin `Item` modeli için: ```Python item: Item ``` -...sadece kısa bir parametre tipi belirtmekle beraber, sahip olacakların: +...ve sadece kısa bir parametre tipi belirterek elde ettiklerimiz: -* Editör desteği dahil olmak üzere: +* Editör desteğiyle birlikte: * Otomatik tamamlama. - * Tip sorguları. -* Datanın tipe uyumunun sorgulanması: - * Eğer data geçersiz ise, otomatik olarak hataları ayıklar. - * Çok derin JSON objelerinde bile veri tipi sorgusu yapar. -* Gelen verinin dönüşümünü aşağıdaki veri tiplerini kullanarak gerçekleştirebiliyor. + * Tip kontrolü. +* Veri Doğrulama: + * Veri geçerli değilse, otomatik olarak açıklayıcı hatalar gösterir. + * Çok derin JSON nesnelerinde bile doğrulama yapar. +* Gelen verinin dönüşümünü aşağıdaki veri tiplerini kullanarak gerçekleştirir: * JSON. - * Path parametreleri. - * Query parametreleri. - * Cookies. + * Yol parametreleri. + * Sorgu parametreleri. + * Çerezler. * Headers. - * Forms. - * Files. -* Giden verinin dönüşümünü aşağıdaki veri tiplerini kullanarak gerçekleştirebiliyor (JSON olarak): - * Python tiplerinin (`str`, `int`, `float`, `bool`, `list`, vs) çevirisi. - * `datetime` objesi. - * `UUID` objesi. + * Formlar. + * Dosyalar. +* Giden verinin dönüşümünü aşağıdaki veri tiplerini kullanarak gerçekleştirir (JSON olarak): + * Python tiplerinin (`str`, `int`, `float`, `bool`, `list`, vb) dönüşümü. + * `datetime` nesnesi. + * `UUID` nesnesi. * Veritabanı modelleri. - * ve daha fazlası... -* 2 alternatif kullanıcı arayüzü dahil olmak üzere, otomatik interaktif API dokümanu: + * ve çok daha fazlası... +* 2 alternatif kullanıcı arayüzü dahil olmak üzere, otomatik etkileşimli API dokümantasyonu sağlar: * Swagger UI. * ReDoc. --- -Az önceki kod örneğine geri dönelim, **FastAPI**'ın yapacaklarına bir bakış atalım: +Az önceki örneğe geri dönelim, **FastAPI**'ın yapacaklarına bir bakış atalım: -* `item_id`'nin `GET` ve `PUT` talepleri içinde olup olmadığının doğruluğunu kontol edecek. -* `item_id`'nin tipinin `int` olduğunu `GET` ve `PUT` talepleri içinde olup olmadığının doğruluğunu kontol edecek. - * Eğer `GET` ve `PUT` içinde yok ise ve `int` değil ise, sebebini belirten bir hata mesajı gösterecek -* Opsiyonel bir `q` parametresinin `GET` talebi için (`http://127.0.0.1:8000/items/foo?q=somequery` içinde) olup olmadığını kontrol edecek +* `item_id`'nin `GET` ve `PUT` istekleri için, yolda olup olmadığının kontol edecek. +* `item_id`'nin `GET` ve `PUT` istekleri için, tipinin `int` olduğunu doğrulayacak. + * Eğer değilse, sebebini belirten bir hata mesajı gösterecek. +* Opsiyonel bir `q` parametresinin `GET` isteği içinde (`http://127.0.0.1:8000/items/foo?q=somequery` gibi) olup olmadığını kontrol edecek * `q` parametresini `= None` ile oluşturduğumuz için, opsiyonel bir parametre olacak. - * Eğer `None` olmasa zorunlu bir parametre olacak idi (bu yüzden body'de `PUT` parametresi var). -* `PUT` talebi için `/items/{item_id}`'nin body'sini, JSON olarak okuyor: - * `name` adında bir parametetre olup olmadığını ve var ise onun `str` olup olmadığını kontol ediyor. - * `price` adında bir parametetre olup olmadığını ve var ise onun `float` olup olmadığını kontol ediyor. - * `is_offer` adında bir parametetre olup olmadığını ve var ise onun `bool` olup olmadığını kontol ediyor. - * Bunların hepsini en derin JSON modellerinde bile yapacaktır. -* Bütün veri tiplerini otomatik olarak JSON'a çeviriyor veya tam tersi. -* Her şeyi dokümanlayıp, çeşitli yerlerde: - * İnteraktif dokümantasyon sistemleri. - * Otomatik alıcı kodu üretim sistemlerinde ve çeşitli dillerde. -* İki ayrı web arayüzüyle direkt olarak interaktif bir dokümantasyon sunuyor. + * Eğer `None` olmasa zorunlu bir parametre olacaktı (`PUT` metodunun gövdesinde olduğu gibi). +* `PUT` isteği için `/items/{item_id}`'nin gövdesini, JSON olarak doğrulayıp okuyacak: + * `name` adında zorunlu bir parametre olup olmadığını ve varsa tipinin `str` olup olmadığını kontol edecek. + * `price` adında zorunlu bir parametre olup olmadığını ve varsa tipinin `float` olup olmadığını kontol edecek. + * `is_offer` adında opsiyonel bir parametre olup olmadığını ve varsa tipinin `float` olup olmadığını kontol edecek. + * Bunların hepsi en derin JSON nesnelerinde bile çalışacak. +* Verilerin JSON'a ve JSON'ın python nesnesine dönüşümü otomatik olarak yapılacak. +* Her şeyi OpenAPI ile uyumlu bir şekilde otomatik olarak dokümanlayacak ve bunlarda aşağıdaki gibi kullanılabilecek: + * Etkileşimli dokümantasyon sistemleri. + * Bir çok programlama dili için otomatik istemci kodu üretim sistemleri. +* İki ayrı etkileşimli dokümantasyon arayüzünü doğrudan sağlayacak. --- -Henüz yüzeysel bir bakış attık, fakat sen çoktan çalışma mantığını anladın. +Daha yeni başladık ama çalışma mantığını çoktan anlamış oldunuz. -Şimdi aşağıdaki satırı değiştirmeyi dene: +Şimdi aşağıdaki satırı değiştirmeyi deneyin: ```Python return {"item_name": item.name, "item_id": item_id} @@ -414,22 +414,22 @@ Henüz yüzeysel bir bakış attık, fakat sen çoktan çalışma mantığını ... "item_price": item.price ... ``` -...şimdi editör desteğinin nasıl veri tiplerini bildiğini ve otomatik tamamladığını gör: +...ve editörünün veri tiplerini bildiğini ve otomatik tamamladığını göreceksiniz: ![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) -Daha fazla örnek ve özellik için Tutorial - User Guide sayfasını git. +Daha fazal özellik içeren, daha eksiksiz bir örnek için Öğretici - Kullanıcı Rehberi sayfasını ziyaret edebilirsin. -**Spoiler**: Öğretici - Kullanıcı rehberi şunları içeriyor: +**Spoiler**: Öğretici - Kullanıcı rehberi şunları içerir: -* **Parameterlerini** nasıl **headers**, **cookies**, **form fields** ve **files** olarak deklare edebileceğini. -* `maximum_length` ya da `regex` gibi şeylerle nasıl **doğrulama** yapabileceğini. -* Çok güçlü ve kullanımı kolay **Zorunluluk Entegrasyonu** oluşturmayı. -* Güvenlik ve kimlik doğrulama, **JWT tokenleri**'yle beraber **OAuth2** desteği, ve **HTTP Basic** doğrulaması. -* İleri seviye fakat ona göre oldukça basit olan **derince oluşturulmuş JSON modelleri** (Pydantic sayesinde). +* **Parameterlerin**, **headers**, **çerezler**, **form alanları** ve **dosyalar** olarak tanımlanması. +* `maximum_length` ya da `regex` gibi **doğrulama kısıtlamalarının** nasıl yapılabileceği. +* Çok güçlü ve kullanımı kolay **Bağımlılık Enjeksiyonu** sistemi oluşturmayı. +* Güvenlik ve kimlik doğrulama, **JWT tokenleri** ile **OAuth2** desteği, ve **HTTP Basic** doğrulaması. +* İleri seviye fakat bir o kadarda basit olan **çok derin JSON modelleri** (Pydantic sayesinde). +* **GraphQL** entegrasyonu: Strawberry ve diğer kütüphaneleri kullanarak. * Diğer ekstra özellikler (Starlette sayesinde): - * **WebSockets** - * **GraphQL** + * **WebSocketler** * HTTPX ve `pytest` sayesinde aşırı kolay testler. * **CORS** * **Cookie Sessions** @@ -437,33 +437,34 @@ Daha fazla örnek ve özellik için Python'un en hızlı frameworklerinden birisi , sadece Starlette ve Uvicorn'dan daha yavaş ki FastAPI bunların üzerine kurulu. +Bağımsız TechEmpower kıyaslamaları gösteriyor ki, Uvicorn ile çalıştırılan **FastAPI** uygulamaları en hızlı Python framework'lerinden birisi, sadece Starlette ve Uvicorn'dan yavaş, ki FastAPI bunların üzerine kurulu bir kütüphanedir. -Daha fazla bilgi için, bu bölüme bir göz at Benchmarks. +Daha fazla bilgi için, bu bölüme bir göz at Kıyaslamalar. -## Opsiyonel gereksinimler +## Opsiyonel Gereksinimler Pydantic tarafında kullanılan: * email_validator - email doğrulaması için. +* pydantic-settings - ayar yönetimi için. +* pydantic-extra-types - Pydantic ile birlikte kullanılabilecek ek tipler için. Starlette tarafında kullanılan: -* httpx - Eğer `TestClient` kullanmak istiyorsan gerekli. -* jinja2 - Eğer kendine ait template konfigürasyonu oluşturmak istiyorsan gerekli -* python-multipart - Form kullanmak istiyorsan gerekli ("dönüşümü"). +* httpx - Eğer `TestClient` yapısını kullanacaksanız gereklidir. +* jinja2 - Eğer varsayılan template konfigürasyonunu kullanacaksanız gereklidir. +* python-multipart - Eğer `request.form()` ile form dönüşümü desteğini kullanacaksanız gereklidir. * itsdangerous - `SessionMiddleware` desteği için gerekli. * pyyaml - `SchemaGenerator` desteği için gerekli (Muhtemelen FastAPI kullanırken ihtiyacınız olmaz). -* graphene - `GraphQLApp` desteği için gerekli. -* ujson - `UJSONResponse` kullanmak istiyorsan gerekli. +* ujson - `UJSONResponse` kullanacaksanız gerekli. Hem FastAPI hem de Starlette tarafından kullanılan: -* uvicorn - oluşturduğumuz uygulamayı bir web sunucusuna servis etmek için gerekli -* orjson - `ORJSONResponse` kullanmak istiyor isen gerekli. +* uvicorn - oluşturduğumuz uygulamayı servis edecek web sunucusu görevini üstlenir. +* orjson - `ORJSONResponse` kullanacaksanız gereklidir. Bunların hepsini `pip install fastapi[all]` ile yükleyebilirsin. ## Lisans -Bu proje, MIT lisansı şartlarına göre lisanslanmıştır. +Bu proje, MIT lisansı şartları altında lisanslanmıştır. diff --git a/docs/tr/docs/newsletter.md b/docs/tr/docs/newsletter.md new file mode 100644 index 0000000000000..22ca1b1e2949e --- /dev/null +++ b/docs/tr/docs/newsletter.md @@ -0,0 +1,5 @@ +# FastAPI ve Arkadaşları Bülteni + + + + diff --git a/docs/uk/docs/index.md b/docs/uk/docs/index.md new file mode 100644 index 0000000000000..fad693f79deb2 --- /dev/null +++ b/docs/uk/docs/index.md @@ -0,0 +1,465 @@ +

+ FastAPI +

+

+ Готовий до продакшину, високопродуктивний, простий у вивченні та швидкий для написання коду фреймворк +

+

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

+ +--- + +**Документація**: https://fastapi.tiangolo.com + +**Програмний код**: https://github.com/tiangolo/fastapi + +--- + +FastAPI - це сучасний, швидкий (високопродуктивний), вебфреймворк для створення API за допомогою Python 3.8+,в основі якого лежить стандартна анотація типів Python. + +Ключові особливості: + +* **Швидкий**: Дуже висока продуктивність, на рівні з **NodeJS** та **Go** (завдяки Starlette та Pydantic). [Один із найшвидших фреймворків](#performance). + +* **Швидке написання коду**: Пришвидшує розробку функціоналу приблизно на 200%-300%. * +* **Менше помилок**: Зменшить кількість помилок спричинених людиною (розробником) на 40%. * +* **Інтуїтивний**: Чудова підтримка редакторами коду. Доповнення всюди. Зменште час на налагодження. +* **Простий**: Спроектований, для легкого використання та навчання. Знадобиться менше часу на читання документації. +* **Короткий**: Зведе до мінімуму дублювання коду. Кожен оголошений параметр може виконувати кілька функцій. +* **Надійний**: Ви матимете стабільний код готовий до продакшину з автоматичною інтерактивною документацією. +* **Стандартизований**: Оснований та повністю сумісний з відкритими стандартами для API: OpenAPI (попередньо відомий як Swagger) та JSON Schema. + +* оцінка на основі тестів внутрішньої команди розробників, створення продуктових застосунків. + +## Спонсори + + + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} + +{% endfor -%} +{%- for sponsor in sponsors.silver -%} + +{% endfor %} +{% endif %} + + + +Other sponsors + +## Враження + +"_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._" + +
Kabir Khan - Microsoft (ref)
+ +--- + +"_We adopted the **FastAPI** library to spawn a **REST** server that can be queried to obtain **predictions**. [for Ludwig]_" + +
Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - Uber (ref)
+ +--- + +"_**Netflix** is pleased to announce the open-source release of our **crisis management** orchestration framework: **Dispatch**! [built with **FastAPI**]_" + +
Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix (ref)
+ +--- + +"_I’m over the moon excited about **FastAPI**. It’s so fun!_" + +
Brian Okken - Python Bytes podcast host (ref)
+ +--- + +"_Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted **Hug** to be - it's really inspiring to see someone build that._" + +
Timothy Crosley - Hug creator (ref)
+ +--- + +"_If you're looking to learn one **modern framework** for building REST APIs, check out **FastAPI** [...] It's fast, easy to use and easy to learn [...]_" + +"_We've switched over to **FastAPI** for our **APIs** [...] I think you'll like it [...]_" + +
Ines Montani - Matthew Honnibal - Explosion AI founders - spaCy creators (ref) - (ref)
+ +--- + +## **Typer**, FastAPI CLI + + + +Створюючи CLI застосунок для використання в терміналі, замість веб-API зверніть увагу на **Typer**. + +**Typer** є молодшим братом FastAPI. І це **FastAPI для CLI**. ⌨️ 🚀 + +## Вимоги + +Python 3.8+ + +FastAPI стоїть на плечах гігантів: + +* Starlette для web частини. +* Pydantic для частини даних. + +## Вставновлення + +
+ +```console +$ pip install fastapi + +---> 100% +``` + +
+ +Вам також знадобиться сервер ASGI для продакшину, наприклад Uvicorn або Hypercorn. + +
+ +```console +$ pip install uvicorn[standard] + +---> 100% +``` + +
+ +## Приклад + +### Створіть + +* Створіть файл `main.py` з: + +```Python +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +
+Або використайте async def... + +Якщо ваш код використовує `async` / `await`, скористайтеся `async def`: + +```Python hl_lines="9 14" +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +async def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +async def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +**Примітка**: + +Стикнувшись з проблемами, не зайвим буде ознайомитися з розділом _"In a hurry?"_ про `async` та `await` у документації. + +
+ +### Запустіть + +Запустіть 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. +``` + +
+ +
+Про команди uvicorn main:app --reload... + +Команда `uvicorn main:app` посилається на: + +* `main`: файл `main.py` ("Модуль" Python). +* `app`: об’єкт створений усередині `main.py` рядком `app = FastAPI()`. +* `--reload`: перезапускає сервер після зміни коду. Використовуйте виключно для розробки. + +
+ +### Перевірте + +Відкрийте браузер та введіть адресу http://127.0.0.1:8000/items/5?q=somequery. + +Ви побачите у відповідь подібний JSON: + +```JSON +{"item_id": 5, "q": "somequery"} +``` + +Ви вже створили API, який: + +* Отримує HTTP запити за _шляхами_ `/` та `/items/{item_id}`. +* Обидва _шляхи_ приймають `GET` операції (також відомі як HTTP _методи_). +* _Шлях_ `/items/{item_id}` містить _параметр шляху_ `item_id` який має бути типу `int`. +* _Шлях_ `/items/{item_id}` містить необовʼязковий `str` _параметр запиту_ `q`. + +### Інтерактивні документації API + +Перейдемо сюди http://127.0.0.1:8000/docs. + +Ви побачите автоматичну інтерактивну API документацію (створену завдяки Swagger UI): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### Альтернативні документації API + +Тепер перейдемо сюди http://127.0.0.1:8000/redoc. + +Ви побачите альтернативну автоматичну документацію (створену завдяки ReDoc): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +## Приклад оновлення + +Тепер модифікуйте файл `main.py`, щоб отримати вміст запиту `PUT`. + +Оголошуйте вміст запиту за допомогою стандартних типів Python завдяки Pydantic. + +```Python hl_lines="4 9-12 25-27" +from typing import Union + +from fastapi import FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Item(BaseModel): + name: str + price: float + is_offer: Union[bool, None] = None + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} + + +@app.put("/items/{item_id}") +def update_item(item_id: int, item: Item): + return {"item_name": item.name, "item_id": item_id} +``` + +Сервер повинен автоматично перезавантажуватися (тому що Ви додали `--reload` до `uvicorn` команди вище). + +### Оновлення інтерактивної API документації + +Тепер перейдемо сюди http://127.0.0.1:8000/docs. + +* Інтерактивна документація API буде автоматично оновлена, включаючи новий вміст: + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* Натисніть кнопку "Try it out", це дозволить вам заповнити параметри та безпосередньо взаємодіяти з API: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) + +* Потім натисніть кнопку "Execute", інтерфейс користувача зв'яжеться з вашим API, надішле параметри, у відповідь отримає результати та покаже їх на екрані: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) + +### Оновлення альтернативної API документації + +Зараз перейдемо http://127.0.0.1:8000/redoc. + +* Альтернативна документація також показуватиме новий параметр і вміст запиту: + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### Підсумки + +Таким чином, Ви **один раз** оголошуєте типи параметрів, тіла тощо, як параметри функції. + +Ви робите це за допомогою стандартних сучасних типів Python. + +Вам не потрібно вивчати новий синтаксис, методи чи класи конкретної бібліотеки тощо. + +Використовуючи стандартний **Python 3.8+**. + +Наприклад, для `int`: + +```Python +item_id: int +``` + +або для більш складної моделі `Item`: + +```Python +item: Item +``` + +...і з цим єдиним оголошенням Ви отримуєте: + +* Підтримку редактора, включаючи: + * Варіанти заповнення. + * Перевірку типів. +* Перевірку даних: + * Автоматичні та зрозумілі помилки, у разі некоректних даних. + * Перевірка навіть для JSON з високим рівнем вкладеності. +* Перетворення вхідних даних: з мережі до даних і типів Python. Читання з: + * JSON. + * Параметрів шляху. + * Параметрів запиту. + * Cookies. + * Headers. + * Forms. + * Файлів. +* Перетворення вихідних даних: з типів і даних Python до мережевих даних (як JSON): + * Конвертація Python типів (`str`, `int`, `float`, `bool`, `list`, тощо). + * `datetime` об'єкти. + * `UUID` об'єкти. + * Моделі бази даних. + * ...та багато іншого. +* Автоматичну інтерактивну документацію API, включаючи 2 альтернативні інтерфейси користувача: + * Swagger UI. + * ReDoc. + +--- + +Повертаючись до попереднього прикладу коду, **FastAPI**: + +* Підтвердить наявність `item_id` у шляху для запитів `GET` та `PUT`. +* Підтвердить, що `item_id` має тип `int` для запитів `GET` and `PUT`. + * Якщо це не так, клієнт побачить корисну, зрозумілу помилку. +* Перевірить, чи є необов'язковий параметр запиту з назвою `q` (а саме `http://127.0.0.1:8000/items/foo?q=somequery`) для запитів `GET`. + * Оскільки параметр `q` оголошено як `= None`, він необов'язковий. + * За відсутності `None` він був би обов'язковим (як і вміст у випадку з `PUT`). +* Для запитів `PUT` із `/items/{item_id}`, читає вміст як JSON: + * Перевірить, чи має обов'язковий атрибут `name` тип `str`. + * Перевірить, чи має обов'язковий атрибут `price` тип `float`. + * Перевірить, чи існує необов'язковий атрибут `is_offer` та чи має він тип `bool`. + * Усе це також працюватиме для глибоко вкладених об'єктів JSON. +* Автоматично конвертує із та в JSON. +* Документує все за допомогою OpenAPI, який може бути використано в: + * Інтерактивних системах документації. + * Системах автоматичної генерації клієнтського коду для багатьох мов. +* Надає безпосередньо 2 вебінтерфейси інтерактивної документації. + +--- + +Ми лише трішки доторкнулися до коду, але Ви вже маєте уявлення про те, як все працює. + +Спробуйте змінити рядок: + +```Python + return {"item_name": item.name, "item_id": item_id} +``` + +...із: + +```Python + ... "item_name": item.name ... +``` + +...на: + +```Python + ... "item_price": item.price ... +``` + +...і побачите, як ваш редактор автоматично заповнюватиме атрибути та знатиме їхні типи: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +Для більш повного ознайомлення з додатковими функціями, перегляньте Туторіал - Посібник Користувача. + +**Spoiler alert**: туторіал - посібник користувача містить: + +* Оголошення **параметрів** з інших місць як: **headers**, **cookies**, **form fields** та **files**. +* Як встановити **перевірку обмежень** як `maximum_length` або `regex`. +* Дуже потужна і проста у використанні система **Ін'єкція Залежностей**. +* Безпека та автентифікація, включаючи підтримку **OAuth2** з **JWT tokens** та **HTTP Basic** автентифікацію. +* Досконаліші (але однаково прості) техніки для оголошення **глибоко вкладених моделей JSON** (завдяки Pydantic). +* Багато додаткових функцій (завдяки Starlette) як-от: + * **WebSockets** + * надзвичайно прості тести на основі HTTPX та `pytest` + * **CORS** + * **Cookie Sessions** + * ...та більше. + +## Продуктивність + +Незалежні тести TechEmpower показують що застосунки **FastAPI**, які працюють під керуванням Uvicorn є одними з найшвидших серед доступних фреймворків в Python, поступаючись лише Starlette та Uvicorn (які внутрішньо використовуються в FastAPI). (*) + +Щоб дізнатися більше про це, перегляньте розділ Benchmarks. + +## Необов'язкові залежності + +Pydantic використовує: + +* email_validator - для валідації електронної пошти. +* pydantic-settings - для управління налаштуваннями. +* pydantic-extra-types - для додаткових типів, що можуть бути використані з Pydantic. + + +Starlette використовує: + +* httpx - Необхідно, якщо Ви хочете використовувати `TestClient`. +* jinja2 - Необхідно, якщо Ви хочете використовувати шаблони як конфігурацію за замовчуванням. +* python-multipart - Необхідно, якщо Ви хочете підтримувати "розбір" форми за допомогою `request.form()`. +* itsdangerous - Необхідно для підтримки `SessionMiddleware`. +* pyyaml - Необхідно для підтримки Starlette `SchemaGenerator` (ймовірно, вам це не потрібно з FastAPI). +* ujson - Необхідно, якщо Ви хочете використовувати `UJSONResponse`. + +FastAPI / Starlette використовують: + +* uvicorn - для сервера, який завантажує та обслуговує вашу програму. +* orjson - Необхідно, якщо Ви хочете використовувати `ORJSONResponse`. + +Ви можете встановити все це за допомогою `pip install fastapi[all]`. + +## Ліцензія + +Цей проєкт ліцензовано згідно з умовами ліцензії MIT. diff --git a/docs/uk/docs/tutorial/body-fields.md b/docs/uk/docs/tutorial/body-fields.md new file mode 100644 index 0000000000000..eee993cbe3616 --- /dev/null +++ b/docs/uk/docs/tutorial/body-fields.md @@ -0,0 +1,116 @@ +# Тіло - Поля + +Так само як ви можете визначати додаткову валідацію та метадані у параметрах *функції обробки шляху* за допомогою `Query`, `Path` та `Body`, ви можете визначати валідацію та метадані всередині моделей Pydantic за допомогою `Field` від Pydantic. + +## Імпорт `Field` + +Спочатку вам потрібно імпортувати це: + +=== "Python 3.10+" + + ```Python hl_lines="4" + {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="4" + {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="4" + {!> ../../../docs_src/body_fields/tutorial001_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip + Варто користуватись `Annotated` версією, якщо це можливо. + + ```Python hl_lines="2" + {!> ../../../docs_src/body_fields/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + Варто користуватись `Annotated` версією, якщо це можливо. + + ```Python hl_lines="4" + {!> ../../../docs_src/body_fields/tutorial001.py!} + ``` + +!!! warning + Зверніть увагу, що `Field` імпортується прямо з `pydantic`, а не з `fastapi`, як всі інші (`Query`, `Path`, `Body` тощо). + +## Оголошення атрибутів моделі + +Ви можете використовувати `Field` з атрибутами моделі: + +=== "Python 3.10+" + + ```Python hl_lines="11-14" + {!> ../../../docs_src/body_fields/tutorial001_an_py310.py!} + ``` + +=== "Python 3.9+" + + ```Python hl_lines="11-14" + {!> ../../../docs_src/body_fields/tutorial001_an_py39.py!} + ``` + +=== "Python 3.8+" + + ```Python hl_lines="12-15" + {!> ../../../docs_src/body_fields/tutorial001_an.py!} + ``` + +=== "Python 3.10+ non-Annotated" + + !!! tip + Варто користуватись `Annotated` версією, якщо це можливо.. + + ```Python hl_lines="9-12" + {!> ../../../docs_src/body_fields/tutorial001_py310.py!} + ``` + +=== "Python 3.8+ non-Annotated" + + !!! tip + Варто користуватись `Annotated` версією, якщо це можливо.. + + ```Python hl_lines="11-14" + {!> ../../../docs_src/body_fields/tutorial001.py!} + ``` + +`Field` працює так само, як `Query`, `Path` і `Body`, у нього такі самі параметри тощо. + +!!! note "Технічні деталі" + Насправді, `Query`, `Path` та інші, що ви побачите далі, створюють об'єкти підкласів загального класу `Param`, котрий сам є підкласом класу `FieldInfo` з Pydantic. + + І `Field` від Pydantic також повертає екземпляр `FieldInfo`. + + `Body` також безпосередньо повертає об'єкти підкласу `FieldInfo`. І є інші підкласи, які ви побачите пізніше, що є підкласами класу Body. + + Пам'ятайте, що коли ви імпортуєте 'Query', 'Path' та інше з 'fastapi', вони фактично є функціями, які повертають спеціальні класи. + +!!! tip + Зверніть увагу, що кожен атрибут моделі із типом, значенням за замовчуванням та `Field` має ту саму структуру, що й параметр *функції обробки шляху*, з `Field` замість `Path`, `Query` і `Body`. + +## Додавання додаткової інформації + +Ви можете визначити додаткову інформацію у `Field`, `Query`, `Body` тощо. І вона буде включена у згенеровану JSON схему. + +Ви дізнаєтеся більше про додавання додаткової інформації пізніше у документації, коли вивчатимете визначення прикладів. + +!!! warning + Додаткові ключі, передані в `Field`, також будуть присутні у згенерованій схемі OpenAPI для вашого додатка. + Оскільки ці ключі не обов'язково можуть бути частиною специфікації OpenAPI, деякі інструменти OpenAPI, наприклад, [OpenAPI валідатор](https://validator.swagger.io/), можуть не працювати з вашою згенерованою схемою. + +## Підсумок + +Ви можете використовувати `Field` з Pydantic для визначення додаткових перевірок та метаданих для атрибутів моделі. + +Ви також можете використовувати додаткові іменовані аргументи для передачі додаткових метаданих JSON схеми. diff --git a/docs/zh/docs/advanced/additional-responses.md b/docs/zh/docs/advanced/additional-responses.md new file mode 100644 index 0000000000000..2a1e1ed891a79 --- /dev/null +++ b/docs/zh/docs/advanced/additional-responses.md @@ -0,0 +1,219 @@ +# OPENAPI 中的其他响应 + +您可以声明附加响应,包括附加状态代码、媒体类型、描述等。 + +这些额外的响应将包含在OpenAPI模式中,因此它们也将出现在API文档中。 + +但是对于那些额外的响应,你必须确保你直接返回一个像 `JSONResponse` 一样的 `Response` ,并包含你的状态代码和内容。 + +## `model`附加响应 +您可以向路径操作装饰器传递参数 `responses` 。 + +它接收一个 `dict`,键是每个响应的状态代码(如`200`),值是包含每个响应信息的其他 `dict`。 + +每个响应字典都可以有一个关键模型,其中包含一个 `Pydantic` 模型,就像 `response_model` 一样。 + +**FastAPI**将采用该模型,生成其`JSON Schema`并将其包含在`OpenAPI`中的正确位置。 + +例如,要声明另一个具有状态码 `404` 和`Pydantic`模型 `Message` 的响应,可以写: +```Python hl_lines="18 22" +{!../../../docs_src/additional_responses/tutorial001.py!} +``` + + +!!! Note + 请记住,您必须直接返回 `JSONResponse` 。 + +!!! Info + `model` 密钥不是OpenAPI的一部分。 + **FastAPI**将从那里获取`Pydantic`模型,生成` JSON Schema` ,并将其放在正确的位置。 + - 正确的位置是: + - 在键 `content` 中,其具有另一个`JSON`对象( `dict` )作为值,该`JSON`对象包含: + - 媒体类型的密钥,例如 `application/json` ,它包含另一个`JSON`对象作为值,该对象包含: + - 一个键` schema` ,它的值是来自模型的`JSON Schema`,正确的位置在这里。 + - **FastAPI**在这里添加了对OpenAPI中另一个地方的全局JSON模式的引用,而不是直接包含它。这样,其他应用程序和客户端可以直接使用这些JSON模式,提供更好的代码生成工具等。 + + +**在OpenAPI中为该路径操作生成的响应将是:** + +```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" + } + } + } + } + } +} + +``` +**模式被引用到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" + } + } + } + } + } + } +} + +``` +## 主响应的其他媒体类型 + +您可以使用相同的 `responses` 参数为相同的主响应添加不同的媒体类型。 + +例如,您可以添加一个额外的媒体类型` image/png` ,声明您的路径操作可以返回JSON对象(媒体类型 `application/json` )或PNG图像: + +```Python hl_lines="19-24 28" +{!../../../docs_src/additional_responses/tutorial002.py!} +``` + +!!! Note + - 请注意,您必须直接使用 `FileResponse` 返回图像。 + +!!! Info + - 除非在 `responses` 参数中明确指定不同的媒体类型,否则**FastAPI**将假定响应与主响应类具有相同的媒体类型(默认为` application/json` )。 + - 但是如果您指定了一个自定义响应类,并将 `None `作为其媒体类型,**FastAPI**将使用 `application/json` 作为具有关联模型的任何其他响应。 + +## 组合信息 +您还可以联合接收来自多个位置的响应信息,包括 `response_model `、 `status_code` 和 `responses `参数。 + +您可以使用默认的状态码 `200` (或者您需要的自定义状态码)声明一个 `response_model `,然后直接在OpenAPI模式中在 `responses` 中声明相同响应的其他信息。 + +**FastAPI**将保留来自 `responses` 的附加信息,并将其与模型中的JSON Schema结合起来。 + +例如,您可以使用状态码 `404` 声明响应,该响应使用`Pydantic`模型并具有自定义的` description` 。 + +以及一个状态码为 `200` 的响应,它使用您的 `response_model` ,但包含自定义的 `example` : + +```Python hl_lines="20-31" +{!../../../docs_src/additional_responses/tutorial003.py!} +``` + +所有这些都将被合并并包含在您的OpenAPI中,并在API文档中显示: + +## 联合预定义响应和自定义响应 + +您可能希望有一些应用于许多路径操作的预定义响应,但是你想将不同的路径和自定义的相应组合在一块。 +对于这些情况,你可以使用Python的技术,将 `dict` 与 `**dict_to_unpack` 解包: +```Python +old_dict = { + "old key": "old value", + "second old key": "second old value", +} +new_dict = {**old_dict, "new key": "new value"} +``` + +这里, new_dict 将包含来自 old_dict 的所有键值对加上新的键值对: +```python +{ + "old key": "old value", + "second old key": "second old value", + "new key": "new value", +} +``` +您可以使用该技术在路径操作中重用一些预定义的响应,并将它们与其他自定义响应相结合。 +**例如:** +```Python hl_lines="13-17 26" +{!../../../docs_src/additional_responses/tutorial004.py!} +``` +## 有关OpenAPI响应的更多信息 + +要了解您可以在响应中包含哪些内容,您可以查看OpenAPI规范中的以下部分: + + [OpenAPI响应对象](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#responsesObject),它包括 Response Object 。 + + [OpenAPI响应对象](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.1.0.md#responseObject),您可以直接在 `responses` 参数中的每个响应中包含任何内容。包括 `description` 、 `headers` 、 `content` (其中是声明不同的媒体类型和JSON Schemas)和 `links` 。 diff --git a/docs/zh/docs/deployment/cloud.md b/docs/zh/docs/deployment/cloud.md new file mode 100644 index 0000000000000..398f613728db6 --- /dev/null +++ b/docs/zh/docs/deployment/cloud.md @@ -0,0 +1,17 @@ +# 在云上部署 FastAPI + +您几乎可以使用**任何云服务商**来部署 FastAPI 应用程序。 + +在大多数情况下,主要的云服务商都有部署 FastAPI 的指南。 + +## 云服务商 - 赞助商 + +一些云服务商 ✨ [**赞助 FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨,这确保了FastAPI 及其**生态系统**持续健康地**发展**。 + +这表明了他们对 FastAPI 及其**社区**(您)的真正承诺,因为他们不仅想为您提供**良好的服务**,而且还想确保您拥有一个**良好且健康的框架**:FastAPI。 🙇 + +您可能想尝试他们的服务并阅读他们的指南: + +* Platform.sh +* Porter +* Deta diff --git a/docs/zh/docs/deployment/https.md b/docs/zh/docs/deployment/https.md new file mode 100644 index 0000000000000..cf01a4585bec2 --- /dev/null +++ b/docs/zh/docs/deployment/https.md @@ -0,0 +1,192 @@ +# 关于 HTTPS + +人们很容易认为 HTTPS 仅仅是“启用”或“未启用”的东西。 + +但实际情况比这复杂得多。 + +!!!提示 + 如果你很赶时间或不在乎,请继续阅读下一部分,下一部分会提供一个step-by-step的教程,告诉你怎么使用不同技术来把一切都配置好。 + +要从用户的视角**了解 HTTPS 的基础知识**,请查看 https://howhttps.works/。 + +现在,从**开发人员的视角**,在了解 HTTPS 时需要记住以下几点: + +* 要使用 HTTPS,**服务器**需要拥有由**第三方**生成的**"证书(certificate)"**。 + * 这些证书实际上是从第三方**获取**的,而不是“生成”的。 +* 证书有**生命周期**。 + * 它们会**过期**。 + * 然后它们需要**更新**,**再次从第三方获取**。 +* 连接的加密发生在 **TCP 层**。 + * 这是 HTTP 协议**下面的一层**。 + * 因此,**证书和加密**处理是在 **HTTP之前**完成的。 +* **TCP 不知道域名**。 仅仅知道 IP 地址。 + * 有关所请求的 **特定域名** 的信息位于 **HTTP 数据**中。 +* **HTTPS 证书**“证明”**某个域名**,但协议和加密发生在 TCP 层,在知道正在处理哪个域名**之前**。 +* **默认情况下**,这意味着你**每个 IP 地址只能拥有一个 HTTPS 证书**。 + * 无论你的服务器有多大,或者服务器上的每个应用程序有多小。 + * 不过,对此有一个**解决方案**。 +* **TLS** 协议(在 HTTP 之下的TCP 层处理加密的协议)有一个**扩展**,称为 **SNI**。 + * SNI 扩展允许一台服务器(具有 **单个 IP 地址**)拥有 **多个 HTTPS 证书** 并提供 **多个 HTTPS 域名/应用程序**。 + * 为此,服务器上会有**单独**的一个组件(程序)侦听**公共 IP 地址**,这个组件必须拥有服务器中的**所有 HTTPS 证书**。 +* **获得安全连接后**,通信协议**仍然是HTTP**。 + * 内容是 **加密过的**,即使它们是通过 **HTTP 协议** 发送的。 + +通常的做法是在服务器上运行**一个程序/HTTP 服务器**并**管理所有 HTTPS 部分**:接收**加密的 HTTPS 请求**, 将 **解密的 HTTP 请求** 发送到在同一服务器中运行的实际 HTTP 应用程序(在本例中为 **FastAPI** 应用程序),从应用程序中获取 **HTTP 响应**, 使用适当的 **HTTPS 证书**对其进行加密并使用 **HTTPS** 将其发送回客户端。 此服务器通常被称为 **TLS 终止代理(TLS Termination Proxy)**。 + +你可以用作 TLS 终止代理的一些选项包括: + +* Traefik(也可以处理证书更新) +* Caddy(也可以处理证书更新) +* Nginx +* HAProxy + +## Let's Encrypt + +在 Let's Encrypt 之前,这些 **HTTPS 证书** 由受信任的第三方出售。 + +过去,获得这些证书的过程非常繁琐,需要大量的文书工作,而且证书非常昂贵。 + +但随后 **Let's Encrypt** 创建了。 + +它是 Linux 基金会的一个项目。 它以自动方式免费提供 **HTTPS 证书**。 这些证书可以使用所有符合标准的安全加密,并且有效期很短(大约 3 个月),因此**安全性实际上更好**,因为它们的生命周期缩短了。 + +域可以被安全地验证并自动生成证书。 这还允许自动更新这些证书。 + +我们的想法是自动获取和更新这些证书,以便你可以永远免费拥有**安全的 HTTPS**。 + +## 面向开发人员的 HTTPS + +这里有一个 HTTPS API 看起来是什么样的示例,我们会分步说明,并且主要关注对开发人员重要的部分。 + + +### 域名 + +第一步我们要先**获取**一些**域名(Domain Name)**。 然后可以在 DNS 服务器(可能是你的同一家云服务商提供的)中配置它。 + +你可能拥有一个云服务器(虚拟机)或类似的东西,并且它会有一个固定 **公共IP地址**。 + +在 DNS 服务器中,你可以配置一条记录(“A 记录”)以将 **你的域名** 指向你服务器的公共 **IP 地址**。 + +这个操作一般只需要在最开始执行一次。 + +!!! tip + 域名这部分发生在 HTTPS 之前,由于这一切都依赖于域名和 IP 地址,所以先在这里提一下。 + +### DNS + +现在让我们关注真正的 HTTPS 部分。 + +首先,浏览器将通过 **DNS 服务器** 查询**域名的IP** 是什么,在本例中为 `someapp.example.com`。 + +DNS 服务器会告诉浏览器使用某个特定的 **IP 地址**。 这将是你在 DNS 服务器中为你的服务器配置的公共 IP 地址。 + + + +### TLS 握手开始 + +然后,浏览器将在**端口 443**(HTTPS 端口)上与该 IP 地址进行通信。 + +通信的第一部分只是建立客户端和服务器之间的连接并决定它们将使用的加密密钥等。 + + + +客户端和服务器之间建立 TLS 连接的过程称为 **TLS 握手**。 + +### 带有 SNI 扩展的 TLS + +**服务器中只有一个进程**可以侦听特定 **IP 地址**的特定 **端口**。 可能有其他进程在同一 IP 地址的其他端口上侦听,但每个 IP 地址和端口组合只有一个进程。 + +TLS (HTTPS) 默认使用端口`443`。 这就是我们需要的端口。 + +由于只有一个进程可以监听此端口,因此监听端口的进程将是 **TLS 终止代理**。 + +TLS 终止代理可以访问一个或多个 **TLS 证书**(HTTPS 证书)。 + +使用上面讨论的 **SNI 扩展**,TLS 终止代理将检查应该用于此连接的可用 TLS (HTTPS) 证书,并使用与客户端期望的域名相匹配的证书。 + +在这种情况下,它将使用`someapp.example.com`的证书。 + + + +客户端已经**信任**生成该 TLS 证书的实体(在本例中为 Let's Encrypt,但我们稍后会看到),因此它可以**验证**该证书是否有效。 + +然后,通过使用证书,客户端和 TLS 终止代理 **决定如何加密** **TCP 通信** 的其余部分。 这就完成了 **TLS 握手** 部分。 + +此后,客户端和服务器就拥有了**加密的 TCP 连接**,这就是 TLS 提供的功能。 然后他们可以使用该连接来启动实际的 **HTTP 通信**。 + +这就是 **HTTPS**,它只是 **安全 TLS 连接** 内的普通 **HTTP**,而不是纯粹的(未加密的)TCP 连接。 + +!!! tip + 请注意,通信加密发生在 **TCP 层**,而不是 HTTP 层。 + +### HTTPS 请求 + +现在客户端和服务器(特别是浏览器和 TLS 终止代理)具有 **加密的 TCP 连接**,它们可以开始 **HTTP 通信**。 + +接下来,客户端发送一个 **HTTPS 请求**。 这其实只是一个通过 TLS 加密连接的 HTTP 请求。 + + + +### 解密请求 + +TLS 终止代理将使用协商好的加密算法**解密请求**,并将**(解密的)HTTP 请求**传输到运行应用程序的进程(例如运行 FastAPI 应用的 Uvicorn 进程)。 + + + +### HTTP 响应 + +应用程序将处理请求并向 TLS 终止代理发送**(未加密)HTTP 响应**。 + + + +### HTTPS 响应 + +然后,TLS 终止代理将使用之前协商的加密算法(以`someapp.example.com`的证书开头)对响应进行加密,并将其发送回浏览器。 + +接下来,浏览器将验证响应是否有效和是否使用了正确的加密密钥等。然后它会**解密响应**并处理它。 + + + +客户端(浏览器)将知道响应来自正确的服务器,因为它使用了他们之前使用 **HTTPS 证书** 协商出的加密算法。 + +### 多个应用程序 + +在同一台(或多台)服务器中,可能存在**多个应用程序**,例如其他 API 程序或数据库。 + +只有一个进程可以处理特定的 IP 和端口(在我们的示例中为 TLS 终止代理),但其他应用程序/进程也可以在服务器上运行,只要它们不尝试使用相同的 **公共 IP 和端口的组合**。 + + + +这样,TLS 终止代理就可以为多个应用程序处理**多个域名**的 HTTPS 和证书,然后在每种情况下将请求传输到正确的应用程序。 + +### 证书更新 + +在未来的某个时候,每个证书都会**过期**(大约在获得证书后 3 个月)。 + +然后,会有另一个程序(在某些情况下是另一个程序,在某些情况下可能是同一个 TLS 终止代理)与 Let's Encrypt 通信并更新证书。 + + + +**TLS 证书** **与域名相关联**,而不是与 IP 地址相关联。 + +因此,要更新证书,更新程序需要向权威机构(Let's Encrypt)**证明**它确实**“拥有”并控制该域名**。 + +有多种方法可以做到这一点。 一些流行的方式是: + +* **修改一些DNS记录**。 + * 为此,续订程序需要支持 DNS 提供商的 API,因此,要看你使用的 DNS 提供商是否提供这一功能。 +* **在与域名关联的公共 IP 地址上作为服务器运行**(至少在证书获取过程中)。 + * 正如我们上面所说,只有一个进程可以监听特定的 IP 和端口。 + * 这就是当同一个 TLS 终止代理还负责证书续订过程时它非常有用的原因之一。 + * 否则,你可能需要暂时停止 TLS 终止代理,启动续订程序以获取证书,然后使用 TLS 终止代理配置它们,然后重新启动 TLS 终止代理。 这并不理想,因为你的应用程序在 TLS 终止代理关闭期间将不可用。 + +通过拥有一个**单独的系统来使用 TLS 终止代理来处理 HTTPS**, 而不是直接将 TLS 证书与应用程序服务器一起使用 (例如 Uvicorn),你可以在 +更新证书的过程中同时保持提供服务。 + +## 回顾 + +拥有**HTTPS** 非常重要,并且在大多数情况下相当**关键**。 作为开发人员,你围绕 HTTPS 所做的大部分努力就是**理解这些概念**以及它们的工作原理。 + +一旦你了解了**面向开发人员的 HTTPS** 的基础知识,你就可以轻松组合和配置不同的工具,以帮助你以简单的方式管理一切。 + +在接下来的一些章节中,我将向你展示几个为 **FastAPI** 应用程序设置 **HTTPS** 的具体示例。 🔒 diff --git a/docs/zh/docs/deployment/index.md b/docs/zh/docs/deployment/index.md new file mode 100644 index 0000000000000..1ec0c5c5b5976 --- /dev/null +++ b/docs/zh/docs/deployment/index.md @@ -0,0 +1,21 @@ +# 部署 + +部署 **FastAPI** 应用程序相对容易。 + +## 部署是什么意思 + +**部署**应用程序意味着执行必要的步骤以使其**可供用户使用**。 + +对于**Web API**来说,通常涉及将上传到**云服务器**中,搭配一个性能和稳定性都不错的**服务器程序**,以便你的**用户**可以高效地**访问**你的应用程序,而不会出现中断或其他问题。 + +这与**开发**阶段形成鲜明对比,在**开发**阶段,你不断更改代码、破坏代码、修复代码, 来回停止和重启服务器等。 + +## 部署策略 + +根据你的使用场景和使用的工具,有多种方法可以实现此目的。 + +你可以使用一些工具自行**部署服务器**,你也可以使用能为你完成部分工作的**云服务**,或其他可能的选项。 + +我将向你展示在部署 **FastAPI** 应用程序时你可能应该记住的一些主要概念(尽管其中大部分适用于任何其他类型的 Web 应用程序)。 + +在接下来的部分中,你将看到更多需要记住的细节以及一些技巧。 ✨ diff --git a/docs/zh/docs/deployment/manually.md b/docs/zh/docs/deployment/manually.md new file mode 100644 index 0000000000000..15588043fecbb --- /dev/null +++ b/docs/zh/docs/deployment/manually.md @@ -0,0 +1,148 @@ +# 手动运行服务器 - Uvicorn + +在远程服务器计算机上运行 **FastAPI** 应用程序所需的主要东西是 ASGI 服务器程序,例如 **Uvicorn**。 + +有 3 个主要可选方案: + +* Uvicorn:高性能 ASGI 服务器。 +* Hypercorn:与 HTTP/2 和 Trio 等兼容的 ASGI 服务器。 +* Daphne:为 Django Channels 构建的 ASGI 服务器。 + +## 服务器主机和服务器程序 + +关于名称,有一个小细节需要记住。 💡 + +“**服务器**”一词通常用于指远程/云计算机(物理机或虚拟机)以及在该计算机上运行的程序(例如 Uvicorn)。 + +请记住,当您一般读到“服务器”这个名词时,它可能指的是这两者之一。 + +当提到远程主机时,通常将其称为**服务器**,但也称为**机器**(machine)、**VM**(虚拟机)、**节点**。 这些都是指某种类型的远程计算机,通常运行 Linux,您可以在其中运行程序。 + + +## 安装服务器程序 + +您可以使用以下命令安装 ASGI 兼容服务器: + +=== "Uvicorn" + + * Uvicorn,一个快如闪电 ASGI 服务器,基于 uvloop 和 httptools 构建。 + +
+ + ```console + $ pip install "uvicorn[standard]" + + ---> 100% + ``` + +
+ + !!! tip + 通过添加`standard`,Uvicorn 将安装并使用一些推荐的额外依赖项。 + + 其中包括`uvloop`,它是`asyncio`的高性能替代品,它提供了巨大的并发性能提升。 + +=== "Hypercorn" + + * Hypercorn,一个也与 HTTP/2 兼容的 ASGI 服务器。 + +
+ + ```console + $ pip install hypercorn + + ---> 100% + ``` + +
+ + ...或任何其他 ASGI 服务器。 + + +## 运行服务器程序 + +您可以按照之前教程中的相同方式运行应用程序,但不使用`--reload`选项,例如: + +=== "Uvicorn" + +
+ + ```console + $ uvicorn main:app --host 0.0.0.0 --port 80 + + INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) + ``` + +
+ + +=== "Hypercorn" + +
+ + ```console + $ hypercorn main:app --bind 0.0.0.0:80 + + Running on 0.0.0.0:8080 over http (CTRL + C to quit) + ``` + +
+ +!!! warning + 如果您正在使用`--reload`选项,请记住删除它。 + + `--reload` 选项消耗更多资源,并且更不稳定。 + + 它在**开发**期间有很大帮助,但您**不应该**在**生产环境**中使用它。 + +## Hypercorn with Trio + +Starlette 和 **FastAPI** 基于 AnyIO, 所以它们才能同时与 Python 的标准库 asyncioTrio 兼容。 + +尽管如此,Uvicorn 目前仅与 asyncio 兼容,并且通常使用 `uvloop`, 它是`asyncio`的高性能替代品。 + +但如果你想直接使用**Trio**,那么你可以使用**Hypercorn**,因为它支持它。 ✨ + +### 安装具有 Trio 的 Hypercorn + +首先,您需要安装具有 Trio 支持的 Hypercorn: + +
+ +```console +$ pip install "hypercorn[trio]" +---> 100% +``` + +
+ +### Run with Trio + +然后你可以传递值`trio`给命令行选项`--worker-class`: + +
+ +```console +$ hypercorn main:app --worker-class trio +``` + +
+ +这将通过您的应用程序启动 Hypercorn,并使用 Trio 作为后端。 + +现在您可以在应用程序内部使用 Trio。 或者更好的是,您可以使用 AnyIO,使您的代码与 Trio 和 asyncio 兼容。 🎉 + +## 部署概念 + +这些示例运行服务器程序(例如 Uvicorn),启动**单个进程**,在所有 IP(`0.0.0.0`)上监听预定义端口(例如`80`)。 + +这是基本思路。 但您可能需要处理一些其他事情,例如: + +* 安全性 - HTTPS +* 启动时运行 +* 重新启动 +* Replication(运行的进程数) +* 内存 +* 开始前的步骤 + +在接下来的章节中,我将向您详细介绍每个概念、如何思考它们,以及一些具体示例以及处理它们的策略。 🚀 diff --git a/docs/zh/docs/deployment/server-workers.md b/docs/zh/docs/deployment/server-workers.md new file mode 100644 index 0000000000000..ee3de9b5da406 --- /dev/null +++ b/docs/zh/docs/deployment/server-workers.md @@ -0,0 +1,184 @@ +# Server Workers - Gunicorn with Uvicorn + +让我们回顾一下之前的部署概念: + +* 安全性 - HTTPS +* 启动时运行 +* 重新启动 +* **复制(运行的进程数)** +* 内存 +* 启动前的先前步骤 + +到目前为止,通过文档中的所有教程,您可能已经在**单个进程**上运行了像 Uvicorn 这样的**服务器程序**。 + +部署应用程序时,您可能希望进行一些**进程复制**,以利用**多核**并能够处理更多请求。 + +正如您在上一章有关[部署概念](./concepts.md){.internal-link target=_blank}中看到的,您可以使用多种策略。 + +在这里我将向您展示如何将 **Gunicorn** 与 **Uvicorn worker 进程** 一起使用。 + +!!! info + 如果您正在使用容器,例如 Docker 或 Kubernetes,我将在下一章中告诉您更多相关信息:[容器中的 FastAPI - Docker](./docker.md){.internal-link target=_blank}。 + + 特别是,当在 **Kubernetes** 上运行时,您可能**不想**使用 Gunicorn,而是运行 **每个容器一个 Uvicorn 进程**,但我将在本章后面告诉您这一点。 + + + +## Gunicorn with Uvicorn Workers + +**Gunicorn**主要是一个使用**WSGI标准**的应用服务器。 这意味着 Gunicorn 可以为 Flask 和 Django 等应用程序提供服务。 Gunicorn 本身与 **FastAPI** 不兼容,因为 FastAPI 使用最新的 **ASGI 标准**。 + +但 Gunicorn 支持充当 **进程管理器** 并允许用户告诉它要使用哪个特定的 **worker类**。 然后 Gunicorn 将使用该类启动一个或多个 **worker进程**。 + +**Uvicorn** 有一个 Gunicorn 兼容的worker类。 + +使用这种组合,Gunicorn 将充当 **进程管理器**,监听 **端口** 和 **IP**。 它会将通信**传输**到运行**Uvicorn类**的worker进程。 + +然后与Gunicorn兼容的**Uvicorn worker**类将负责将Gunicorn发送的数据转换为ASGI标准以供FastAPI使用。 + +## 安装 Gunicorn 和 Uvicorn + +
+ +```console +$ pip install "uvicorn[standard]" gunicorn + +---> 100% +``` + +
+ +这将安装带有`standard`扩展包(以获得高性能)的 Uvicorn 和 Gunicorn。 + +## Run Gunicorn with Uvicorn Workers + +接下来你可以通过以下命令运行Gunicorn: + +
+ +```console +$ gunicorn main:app --workers 4 --worker-class uvicorn.workers.UvicornWorker --bind 0.0.0.0:80 + +[19499] [INFO] Starting gunicorn 20.1.0 +[19499] [INFO] Listening at: http://0.0.0.0:80 (19499) +[19499] [INFO] Using worker: uvicorn.workers.UvicornWorker +[19511] [INFO] Booting worker with pid: 19511 +[19513] [INFO] Booting worker with pid: 19513 +[19514] [INFO] Booting worker with pid: 19514 +[19515] [INFO] Booting worker with pid: 19515 +[19511] [INFO] Started server process [19511] +[19511] [INFO] Waiting for application startup. +[19511] [INFO] Application startup complete. +[19513] [INFO] Started server process [19513] +[19513] [INFO] Waiting for application startup. +[19513] [INFO] Application startup complete. +[19514] [INFO] Started server process [19514] +[19514] [INFO] Waiting for application startup. +[19514] [INFO] Application startup complete. +[19515] [INFO] Started server process [19515] +[19515] [INFO] Waiting for application startup. +[19515] [INFO] Application startup complete. +``` + +
+ + +让我们看看每个选项的含义: + +* `main:app`:这与 Uvicorn 使用的语法相同,`main` 表示名为"`main`"的 Python 模块,因此是文件 `main.py`。 `app` 是 **FastAPI** 应用程序的变量名称。 + * 你可以想象 `main:app` 相当于一个 Python `import` 语句,例如: + + ```Python + from main import app + ``` + + * 因此,`main:app` 中的冒号相当于 `from main import app` 中的 Python `import` 部分。 + +* `--workers`:要使用的worker进程数量,每个进程将运行一个 Uvicorn worker进程,在本例中为 4 个worker进程。 + +* `--worker-class`:在worker进程中使用的与 Gunicorn 兼容的工作类。 + * 这里我们传递了 Gunicorn 可以导入和使用的类: + + ```Python + import uvicorn.workers.UvicornWorker + ``` + +* `--bind`:这告诉 Gunicorn 要监听的 IP 和端口,使用冒号 (`:`) 分隔 IP 和端口。 + * 如果您直接运行 Uvicorn,则可以使用`--host 0.0.0.0`和`--port 80`,而不是`--bind 0.0.0.0:80`(Gunicorn 选项)。 + + +在输出中,您可以看到它显示了每个进程的 **PID**(进程 ID)(它只是一个数字)。 + +你可以看到: + +* Gunicorn **进程管理器** 以 PID `19499` 开头(在您的情况下,它将是一个不同的数字)。 +* 然后它开始`Listening at: http://0.0.0.0:80`。 +* 然后它检测到它必须使用 `uvicorn.workers.UvicornWorker` 处的worker类。 +* 然后它启动**4个worker**,每个都有自己的PID:`19511`、`19513`、`19514`和`19515`。 + +Gunicorn 还将负责管理**死进程**和**重新启动**新进程(如果需要保持worker数量)。 因此,这在一定程度上有助于上面列表中**重启**的概念。 + +尽管如此,您可能还希望有一些外部的东西,以确保在必要时**重新启动 Gunicorn**,并且**在启动时运行它**等。 + +## Uvicorn with Workers + +Uvicorn 也有一个选项可以启动和运行多个 **worker进程**。 + +然而,到目前为止,Uvicorn 处理worker进程的能力比 Gunicorn 更有限。 因此,如果您想拥有这个级别(Python 级别)的进程管理器,那么最好尝试使用 Gunicorn 作为进程管理器。 + +无论如何,您都可以像这样运行它: + +
+ +```console +$ uvicorn main:app --host 0.0.0.0 --port 8080 --workers 4 +INFO: Uvicorn running on http://0.0.0.0:8080 (Press CTRL+C to quit) +INFO: Started parent process [27365] +INFO: Started server process [27368] +INFO: Waiting for application startup. +INFO: Application startup complete. +INFO: Started server process [27369] +INFO: Waiting for application startup. +INFO: Application startup complete. +INFO: Started server process [27370] +INFO: Waiting for application startup. +INFO: Application startup complete. +INFO: Started server process [27367] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +这里唯一的新选项是 `--workers` 告诉 Uvicorn 启动 4 个工作进程。 + +您还可以看到它显示了每个进程的 **PID**,父进程(这是 **进程管理器**)的 PID 为`27365`,每个工作进程的 PID 为:`27368`、`27369`, `27370`和`27367`。 + +## 部署概念 + +在这里,您了解了如何使用 **Gunicorn**(或 Uvicorn)管理 **Uvicorn 工作进程**来**并行**应用程序的执行,利用 CPU 中的 **多核**,并 能够满足**更多请求**。 + +从上面的部署概念列表来看,使用worker主要有助于**复制**部分,并对**重新启动**有一点帮助,但您仍然需要照顾其他部分: + +* **安全 - HTTPS** +* **启动时运行** +* ***重新启动*** +* 复制(运行的进程数) +* **内存** +* **启动之前的先前步骤** + +## 容器和 Docker + +在关于 [容器中的 FastAPI - Docker](./docker.md){.internal-link target=_blank} 的下一章中,我将介绍一些可用于处理其他 **部署概念** 的策略。 + +我还将向您展示 **官方 Docker 镜像**,其中包括 **Gunicorn 和 Uvicorn worker** 以及一些对简单情况有用的默认配置。 + +在那里,我还将向您展示如何 **从头开始构建自己的镜像** 以运行单个 Uvicorn 进程(没有 Gunicorn)。 这是一个简单的过程,并且可能是您在使用像 **Kubernetes** 这样的分布式容器管理系统时想要做的事情。 + +## 回顾 + +您可以使用**Gunicorn**(或Uvicorn)作为Uvicorn工作进程的进程管理器,以利用**多核CPU**,**并行运行多个进程**。 + +如果您要设置**自己的部署系统**,同时自己处理其他部署概念,则可以使用这些工具和想法。 + +请查看下一章,了解带有容器(例如 Docker 和 Kubernetes)的 **FastAPI**。 您将看到这些工具也有简单的方法来解决其他**部署概念**。 ✨ diff --git a/docs/zh/docs/learn/index.md b/docs/zh/docs/learn/index.md new file mode 100644 index 0000000000000..38696f6feae03 --- /dev/null +++ b/docs/zh/docs/learn/index.md @@ -0,0 +1,5 @@ +# 学习 + +以下是学习 **FastAPI** 的介绍部分和教程。 + +您可以认为这是一本 **书**,一门 **课程**,是 **官方** 且推荐的学习FastAPI的方法。😎 diff --git a/docs/zh/docs/tutorial/bigger-applications.md b/docs/zh/docs/tutorial/bigger-applications.md index 9f0134f683c9e..1389595669313 100644 --- a/docs/zh/docs/tutorial/bigger-applications.md +++ b/docs/zh/docs/tutorial/bigger-applications.md @@ -79,7 +79,7 @@ 你可以导入它并通过与 `FastAPI` 类相同的方式创建一个「实例」: -```Python hl_lines="1 3" +```Python hl_lines="1 3" title="app/routers/users.py" {!../../../docs_src/bigger_applications/app/routers/users.py!} ``` @@ -89,7 +89,7 @@ 使用方式与 `FastAPI` 类相同: -```Python hl_lines="6 11 16" +```Python hl_lines="6 11 16" title="app/routers/users.py" {!../../../docs_src/bigger_applications/app/routers/users.py!} ``` @@ -112,7 +112,7 @@ 现在我们将使用一个简单的依赖项来读取一个自定义的 `X-Token` 请求首部: -```Python hl_lines="1 4-6" +```Python hl_lines="1 4-6" title="app/dependencies.py" {!../../../docs_src/bigger_applications/app/dependencies.py!} ``` @@ -143,7 +143,7 @@ 因此,我们可以将其添加到 `APIRouter` 中,而不是将其添加到每个路径操作中。 -```Python hl_lines="5-10 16 21" +```Python hl_lines="5-10 16 21" title="app/routers/items.py" {!../../../docs_src/bigger_applications/app/routers/items.py!} ``` @@ -195,7 +195,7 @@ async def read_item(item_id: str): 因此,我们通过 `..` 对依赖项使用了相对导入: -```Python hl_lines="3" +```Python hl_lines="3" title="app/routers/items.py" {!../../../docs_src/bigger_applications/app/routers/items.py!} ``` @@ -265,7 +265,7 @@ from ...dependencies import get_token_header 但是我们仍然可以添加*更多*将会应用于特定的*路径操作*的 `tags`,以及一些特定于该*路径操作*的额外 `responses`: -```Python hl_lines="30-31" +```Python hl_lines="30-31" title="app/routers/items.py" {!../../../docs_src/bigger_applications/app/routers/items.py!} ``` @@ -290,7 +290,7 @@ from ...dependencies import get_token_header 我们甚至可以声明[全局依赖项](dependencies/global-dependencies.md){.internal-link target=_blank},它会和每个 `APIRouter` 的依赖项组合在一起: -```Python hl_lines="1 3 7" +```Python hl_lines="1 3 7" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -298,7 +298,7 @@ from ...dependencies import get_token_header 现在,我们导入具有 `APIRouter` 的其他子模块: -```Python hl_lines="5" +```Python hl_lines="5" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -360,7 +360,7 @@ from .routers.users import router 因此,为了能够在同一个文件中使用它们,我们直接导入子模块: -```Python hl_lines="4" +```Python hl_lines="5" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -368,7 +368,7 @@ from .routers.users import router 现在,让我们来包含来自 `users` 和 `items` 子模块的 `router`。 -```Python hl_lines="10-11" +```Python hl_lines="10-11" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -401,7 +401,7 @@ from .routers.users import router 对于此示例,它将非常简单。但是假设由于它是与组织中的其他项目所共享的,因此我们无法对其进行修改,以及直接在 `APIRouter` 中添加 `prefix`、`dependencies`、`tags` 等: -```Python hl_lines="3" +```Python hl_lines="3" title="app/internal/admin.py" {!../../../docs_src/bigger_applications/app/internal/admin.py!} ``` @@ -409,7 +409,7 @@ from .routers.users import router 我们可以通过将这些参数传递给 `app.include_router()` 来完成所有的声明,而不必修改原始的 `APIRouter`: -```Python hl_lines="14-17" +```Python hl_lines="14-17" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` @@ -432,7 +432,7 @@ from .routers.users import router 这里我们这样做了...只是为了表明我们可以做到🤷: -```Python hl_lines="21-23" +```Python hl_lines="21-23" title="app/main.py" {!../../../docs_src/bigger_applications/app/main.py!} ``` diff --git a/docs/zh/docs/tutorial/extra-data-types.md b/docs/zh/docs/tutorial/extra-data-types.md index a74efa61be48c..f4a77050ca6e0 100644 --- a/docs/zh/docs/tutorial/extra-data-types.md +++ b/docs/zh/docs/tutorial/extra-data-types.md @@ -44,11 +44,11 @@ * 产生的模式将指定那些 `set` 的值是唯一的 (使用 JSON 模式的 `uniqueItems`)。 * `bytes`: * 标准的 Python `bytes`。 - * 在请求和相应中被当作 `str` 处理。 + * 在请求和响应中被当作 `str` 处理。 * 生成的模式将指定这个 `str` 是 `binary` "格式"。 * `Decimal`: * 标准的 Python `Decimal`。 - * 在请求和相应中被当做 `float` 一样处理。 + * 在请求和响应中被当做 `float` 一样处理。 * 您可以在这里检查所有有效的pydantic数据类型: Pydantic data types. ## 例子 diff --git a/docs/zh/docs/tutorial/security/oauth2-jwt.md b/docs/zh/docs/tutorial/security/oauth2-jwt.md index 054198545ef8e..33a4d7fc76171 100644 --- a/docs/zh/docs/tutorial/security/oauth2-jwt.md +++ b/docs/zh/docs/tutorial/security/oauth2-jwt.md @@ -170,7 +170,7 @@ $ openssl rand -hex 32 创建并返回真正的 JWT 访问令牌。 -```Python hl_lines="115-128" +```Python hl_lines="115-130" {!../../../docs_src/security/tutorial004.py!} ``` diff --git a/docs/zh/docs/tutorial/sql-databases.md b/docs/zh/docs/tutorial/sql-databases.md index 8b09dc6771a8f..c49374971eaa0 100644 --- a/docs/zh/docs/tutorial/sql-databases.md +++ b/docs/zh/docs/tutorial/sql-databases.md @@ -78,9 +78,23 @@ ORM 具有在代码和数据库表(“*关系型”)中的**对象**之间 现在让我们看看每个文件/模块的作用。 +## 安装 SQLAlchemy + +先下载`SQLAlchemy`所需要的依赖: + +
+ +```console +$ pip install sqlalchemy + +---> 100% +``` + +
+ ## 创建 SQLAlchemy 部件 -让我们涉及到文件`sql_app/database.py`。 +让我们转到文件`sql_app/database.py`。 ### 导入 SQLAlchemy 部件 @@ -485,7 +499,7 @@ 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/%7B%7Bcookiecutter.project_slug%7D%7D/backend/app/alembic/)。 +您可以在[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/)。 ### 创建依赖项 diff --git a/docs_src/app_testing/app_b/main.py b/docs_src/app_testing/app_b/main.py index 11558b8e813f4..45a103378388a 100644 --- a/docs_src/app_testing/app_b/main.py +++ b/docs_src/app_testing/app_b/main.py @@ -33,6 +33,6 @@ async def create_item(item: Item, x_token: str = Header()): if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item.id in fake_db: - raise HTTPException(status_code=400, detail="Item already exists") + raise HTTPException(status_code=409, detail="Item already exists") fake_db[item.id] = item return item diff --git a/docs_src/app_testing/app_b/test_main.py b/docs_src/app_testing/app_b/test_main.py index d186b8ecbacfa..4e2b98e237c3a 100644 --- a/docs_src/app_testing/app_b/test_main.py +++ b/docs_src/app_testing/app_b/test_main.py @@ -61,5 +61,5 @@ def test_create_existing_item(): "description": "There goes my stealer", }, ) - assert response.status_code == 400 + assert response.status_code == 409 assert response.json() == {"detail": "Item already exists"} diff --git a/docs_src/app_testing/app_b_py310/main.py b/docs_src/app_testing/app_b_py310/main.py index b4c72de5c9431..eccedcc7ce2ec 100644 --- a/docs_src/app_testing/app_b_py310/main.py +++ b/docs_src/app_testing/app_b_py310/main.py @@ -31,6 +31,6 @@ async def create_item(item: Item, x_token: str = Header()): if x_token != fake_secret_token: raise HTTPException(status_code=400, detail="Invalid X-Token header") if item.id in fake_db: - raise HTTPException(status_code=400, detail="Item already exists") + raise HTTPException(status_code=409, detail="Item already exists") fake_db[item.id] = item return item diff --git a/docs_src/app_testing/app_b_py310/test_main.py b/docs_src/app_testing/app_b_py310/test_main.py index d186b8ecbacfa..4e2b98e237c3a 100644 --- a/docs_src/app_testing/app_b_py310/test_main.py +++ b/docs_src/app_testing/app_b_py310/test_main.py @@ -61,5 +61,5 @@ def test_create_existing_item(): "description": "There goes my stealer", }, ) - assert response.status_code == 400 + assert response.status_code == 409 assert response.json() == {"detail": "Item already exists"} diff --git a/docs_src/body/tutorial003.py b/docs_src/body/tutorial003.py index 89a6b833ce237..2f33cc0389694 100644 --- a/docs_src/body/tutorial003.py +++ b/docs_src/body/tutorial003.py @@ -15,5 +15,5 @@ class Item(BaseModel): @app.put("/items/{item_id}") -async def create_item(item_id: int, item: Item): +async def update_item(item_id: int, item: Item): return {"item_id": item_id, **item.dict()} diff --git a/docs_src/body/tutorial003_py310.py b/docs_src/body/tutorial003_py310.py index a936f28fdc65d..440b210e6b47a 100644 --- a/docs_src/body/tutorial003_py310.py +++ b/docs_src/body/tutorial003_py310.py @@ -13,5 +13,5 @@ class Item(BaseModel): @app.put("/items/{item_id}") -async def create_item(item_id: int, item: Item): +async def update_item(item_id: int, item: Item): return {"item_id": item_id, **item.dict()} diff --git a/docs_src/body/tutorial004.py b/docs_src/body/tutorial004.py index e2df0df2baa27..0671e0a278581 100644 --- a/docs_src/body/tutorial004.py +++ b/docs_src/body/tutorial004.py @@ -15,7 +15,7 @@ class Item(BaseModel): @app.put("/items/{item_id}") -async def create_item(item_id: int, item: Item, q: Union[str, None] = None): +async def update_item(item_id: int, item: Item, q: Union[str, None] = None): result = {"item_id": item_id, **item.dict()} if q: result.update({"q": q}) diff --git a/docs_src/body/tutorial004_py310.py b/docs_src/body/tutorial004_py310.py index 60cfd96109b9c..b352b70ab6010 100644 --- a/docs_src/body/tutorial004_py310.py +++ b/docs_src/body/tutorial004_py310.py @@ -13,7 +13,7 @@ class Item(BaseModel): @app.put("/items/{item_id}") -async def create_item(item_id: int, item: Item, q: str | None = None): +async def update_item(item_id: int, item: Item, q: str | None = None): result = {"item_id": item_id, **item.dict()} if q: result.update({"q": q}) diff --git a/docs_src/dependencies/tutorial008b.py b/docs_src/dependencies/tutorial008b.py new file mode 100644 index 0000000000000..163e96600f9b3 --- /dev/null +++ b/docs_src/dependencies/tutorial008b.py @@ -0,0 +1,30 @@ +from fastapi import Depends, FastAPI, HTTPException + +app = FastAPI() + + +data = { + "plumbus": {"description": "Freshly pickled plumbus", "owner": "Morty"}, + "portal-gun": {"description": "Gun to create portals", "owner": "Rick"}, +} + + +class OwnerError(Exception): + pass + + +def get_username(): + try: + yield "Rick" + except OwnerError as e: + raise HTTPException(status_code=400, detail=f"Owner error: {e}") + + +@app.get("/items/{item_id}") +def get_item(item_id: str, username: str = Depends(get_username)): + if item_id not in data: + raise HTTPException(status_code=404, detail="Item not found") + item = data[item_id] + if item["owner"] != username: + raise OwnerError(username) + return item diff --git a/docs_src/dependencies/tutorial008b_an.py b/docs_src/dependencies/tutorial008b_an.py new file mode 100644 index 0000000000000..84d8f12c14887 --- /dev/null +++ b/docs_src/dependencies/tutorial008b_an.py @@ -0,0 +1,31 @@ +from fastapi import Depends, FastAPI, HTTPException +from typing_extensions import Annotated + +app = FastAPI() + + +data = { + "plumbus": {"description": "Freshly pickled plumbus", "owner": "Morty"}, + "portal-gun": {"description": "Gun to create portals", "owner": "Rick"}, +} + + +class OwnerError(Exception): + pass + + +def get_username(): + try: + yield "Rick" + except OwnerError as e: + raise HTTPException(status_code=400, detail=f"Owner error: {e}") + + +@app.get("/items/{item_id}") +def get_item(item_id: str, username: Annotated[str, Depends(get_username)]): + if item_id not in data: + raise HTTPException(status_code=404, detail="Item not found") + item = data[item_id] + if item["owner"] != username: + raise OwnerError(username) + return item diff --git a/docs_src/dependencies/tutorial008b_an_py39.py b/docs_src/dependencies/tutorial008b_an_py39.py new file mode 100644 index 0000000000000..3b8434c816711 --- /dev/null +++ b/docs_src/dependencies/tutorial008b_an_py39.py @@ -0,0 +1,32 @@ +from typing import Annotated + +from fastapi import Depends, FastAPI, HTTPException + +app = FastAPI() + + +data = { + "plumbus": {"description": "Freshly pickled plumbus", "owner": "Morty"}, + "portal-gun": {"description": "Gun to create portals", "owner": "Rick"}, +} + + +class OwnerError(Exception): + pass + + +def get_username(): + try: + yield "Rick" + except OwnerError as e: + raise HTTPException(status_code=400, detail=f"Owner error: {e}") + + +@app.get("/items/{item_id}") +def get_item(item_id: str, username: Annotated[str, Depends(get_username)]): + if item_id not in data: + raise HTTPException(status_code=404, detail="Item not found") + item = data[item_id] + if item["owner"] != username: + raise OwnerError(username) + return item diff --git a/docs_src/generate_clients/tutorial004.js b/docs_src/generate_clients/tutorial004.js new file mode 100644 index 0000000000000..18dc38267bcde --- /dev/null +++ b/docs_src/generate_clients/tutorial004.js @@ -0,0 +1,29 @@ +import * as fs from "fs"; + +const filePath = "./openapi.json"; + +fs.readFile(filePath, (err, data) => { + const openapiContent = JSON.parse(data); + if (err) throw err; + + const paths = openapiContent.paths; + + Object.keys(paths).forEach((pathKey) => { + const pathData = paths[pathKey]; + Object.keys(pathData).forEach((method) => { + const operation = pathData[method]; + if (operation.tags && operation.tags.length > 0) { + const tag = operation.tags[0]; + const operationId = operation.operationId; + const toRemove = `${tag}-`; + if (operationId.startsWith(toRemove)) { + const newOperationId = operationId.substring(toRemove.length); + operation.operationId = newOperationId; + } + } + }); + }); + fs.writeFile(filePath, JSON.stringify(openapiContent, null, 2), (err) => { + if (err) throw err; + }); +}); diff --git a/docs_src/security/tutorial004.py b/docs_src/security/tutorial004.py index 64099abe9cffe..044eec70037da 100644 --- a/docs_src/security/tutorial004.py +++ b/docs_src/security/tutorial004.py @@ -1,4 +1,4 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from typing import Union from fastapi import Depends, FastAPI, HTTPException, status @@ -78,9 +78,9 @@ def authenticate_user(fake_db, username: str, password: str): def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None): to_encode = data.copy() if expires_delta: - expire = datetime.utcnow() + expires_delta + expire = datetime.now(timezone.utc) + expires_delta else: - expire = datetime.utcnow() + timedelta(minutes=15) + expire = datetime.now(timezone.utc) + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt @@ -112,8 +112,10 @@ async def get_current_active_user(current_user: User = Depends(get_current_user) return current_user -@app.post("/token", response_model=Token) -async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()): +@app.post("/token") +async def login_for_access_token( + form_data: OAuth2PasswordRequestForm = Depends() +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException( @@ -125,7 +127,7 @@ async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends( access_token = create_access_token( data={"sub": user.username}, expires_delta=access_token_expires ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) diff --git a/docs_src/security/tutorial004_an.py b/docs_src/security/tutorial004_an.py index ca350343d2082..c78e8496c6427 100644 --- a/docs_src/security/tutorial004_an.py +++ b/docs_src/security/tutorial004_an.py @@ -1,4 +1,4 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from typing import Union from fastapi import Depends, FastAPI, HTTPException, status @@ -79,9 +79,9 @@ def authenticate_user(fake_db, username: str, password: str): def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None): to_encode = data.copy() if expires_delta: - expire = datetime.utcnow() + expires_delta + expire = datetime.now(timezone.utc) + expires_delta else: - expire = datetime.utcnow() + timedelta(minutes=15) + expire = datetime.now(timezone.utc) + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt @@ -115,10 +115,10 @@ async def get_current_active_user( return current_user -@app.post("/token", response_model=Token) +@app.post("/token") async def login_for_access_token( form_data: Annotated[OAuth2PasswordRequestForm, Depends()] -): +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException( @@ -130,7 +130,7 @@ async def login_for_access_token( access_token = create_access_token( data={"sub": user.username}, expires_delta=access_token_expires ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) diff --git a/docs_src/security/tutorial004_an_py310.py b/docs_src/security/tutorial004_an_py310.py index 8bf5f3b7185cd..36dbc677e0638 100644 --- a/docs_src/security/tutorial004_an_py310.py +++ b/docs_src/security/tutorial004_an_py310.py @@ -1,4 +1,4 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from typing import Annotated from fastapi import Depends, FastAPI, HTTPException, status @@ -78,9 +78,9 @@ def authenticate_user(fake_db, username: str, password: str): def create_access_token(data: dict, expires_delta: timedelta | None = None): to_encode = data.copy() if expires_delta: - expire = datetime.utcnow() + expires_delta + expire = datetime.now(timezone.utc) + expires_delta else: - expire = datetime.utcnow() + timedelta(minutes=15) + expire = datetime.now(timezone.utc) + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt @@ -114,10 +114,10 @@ async def get_current_active_user( return current_user -@app.post("/token", response_model=Token) +@app.post("/token") async def login_for_access_token( form_data: Annotated[OAuth2PasswordRequestForm, Depends()] -): +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException( @@ -129,7 +129,7 @@ async def login_for_access_token( access_token = create_access_token( data={"sub": user.username}, expires_delta=access_token_expires ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) diff --git a/docs_src/security/tutorial004_an_py39.py b/docs_src/security/tutorial004_an_py39.py index a634e23de9843..23fc04a721433 100644 --- a/docs_src/security/tutorial004_an_py39.py +++ b/docs_src/security/tutorial004_an_py39.py @@ -1,4 +1,4 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from typing import Annotated, Union from fastapi import Depends, FastAPI, HTTPException, status @@ -78,9 +78,9 @@ def authenticate_user(fake_db, username: str, password: str): def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None): to_encode = data.copy() if expires_delta: - expire = datetime.utcnow() + expires_delta + expire = datetime.now(timezone.utc) + expires_delta else: - expire = datetime.utcnow() + timedelta(minutes=15) + expire = datetime.now(timezone.utc) + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt @@ -114,10 +114,10 @@ async def get_current_active_user( return current_user -@app.post("/token", response_model=Token) +@app.post("/token") async def login_for_access_token( form_data: Annotated[OAuth2PasswordRequestForm, Depends()] -): +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException( @@ -129,7 +129,7 @@ async def login_for_access_token( access_token = create_access_token( data={"sub": user.username}, expires_delta=access_token_expires ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) diff --git a/docs_src/security/tutorial004_py310.py b/docs_src/security/tutorial004_py310.py index 797d56d0431ab..8363d45ab5349 100644 --- a/docs_src/security/tutorial004_py310.py +++ b/docs_src/security/tutorial004_py310.py @@ -1,4 +1,4 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm @@ -77,9 +77,9 @@ def authenticate_user(fake_db, username: str, password: str): def create_access_token(data: dict, expires_delta: timedelta | None = None): to_encode = data.copy() if expires_delta: - expire = datetime.utcnow() + expires_delta + expire = datetime.now(timezone.utc) + expires_delta else: - expire = datetime.utcnow() + timedelta(minutes=15) + expire = datetime.now(timezone.utc) + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt @@ -111,8 +111,10 @@ async def get_current_active_user(current_user: User = Depends(get_current_user) return current_user -@app.post("/token", response_model=Token) -async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()): +@app.post("/token") +async def login_for_access_token( + form_data: OAuth2PasswordRequestForm = Depends() +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException( @@ -124,7 +126,7 @@ async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends( access_token = create_access_token( data={"sub": user.username}, expires_delta=access_token_expires ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) diff --git a/docs_src/security/tutorial005.py b/docs_src/security/tutorial005.py index bd0a33581c21c..b16bf440a51c1 100644 --- a/docs_src/security/tutorial005.py +++ b/docs_src/security/tutorial005.py @@ -1,4 +1,4 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from typing import List, Union from fastapi import Depends, FastAPI, HTTPException, Security, status @@ -93,9 +93,9 @@ def authenticate_user(fake_db, username: str, password: str): def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None): to_encode = data.copy() if expires_delta: - expire = datetime.utcnow() + expires_delta + expire = datetime.now(timezone.utc) + expires_delta else: - expire = datetime.utcnow() + timedelta(minutes=15) + expire = datetime.now(timezone.utc) + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt @@ -143,8 +143,10 @@ async def get_current_active_user( return current_user -@app.post("/token", response_model=Token) -async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()): +@app.post("/token") +async def login_for_access_token( + form_data: OAuth2PasswordRequestForm = Depends() +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException(status_code=400, detail="Incorrect username or password") @@ -153,7 +155,7 @@ async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends( data={"sub": user.username, "scopes": form_data.scopes}, expires_delta=access_token_expires, ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) diff --git a/docs_src/security/tutorial005_an.py b/docs_src/security/tutorial005_an.py index ec4fa1a07e2cd..95e406b32f748 100644 --- a/docs_src/security/tutorial005_an.py +++ b/docs_src/security/tutorial005_an.py @@ -1,4 +1,4 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from typing import List, Union from fastapi import Depends, FastAPI, HTTPException, Security, status @@ -94,9 +94,9 @@ def authenticate_user(fake_db, username: str, password: str): def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None): to_encode = data.copy() if expires_delta: - expire = datetime.utcnow() + expires_delta + expire = datetime.now(timezone.utc) + expires_delta else: - expire = datetime.utcnow() + timedelta(minutes=15) + expire = datetime.now(timezone.utc) + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt @@ -144,10 +144,10 @@ async def get_current_active_user( return current_user -@app.post("/token", response_model=Token) +@app.post("/token") async def login_for_access_token( form_data: Annotated[OAuth2PasswordRequestForm, Depends()] -): +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException(status_code=400, detail="Incorrect username or password") @@ -156,7 +156,7 @@ async def login_for_access_token( data={"sub": user.username, "scopes": form_data.scopes}, expires_delta=access_token_expires, ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) diff --git a/docs_src/security/tutorial005_an_py310.py b/docs_src/security/tutorial005_an_py310.py index 45f3fc0bd6de1..c6116a5ed120f 100644 --- a/docs_src/security/tutorial005_an_py310.py +++ b/docs_src/security/tutorial005_an_py310.py @@ -1,4 +1,4 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from typing import Annotated from fastapi import Depends, FastAPI, HTTPException, Security, status @@ -93,9 +93,9 @@ def authenticate_user(fake_db, username: str, password: str): def create_access_token(data: dict, expires_delta: timedelta | None = None): to_encode = data.copy() if expires_delta: - expire = datetime.utcnow() + expires_delta + expire = datetime.now(timezone.utc) + expires_delta else: - expire = datetime.utcnow() + timedelta(minutes=15) + expire = datetime.now(timezone.utc) + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt @@ -143,10 +143,10 @@ async def get_current_active_user( return current_user -@app.post("/token", response_model=Token) +@app.post("/token") async def login_for_access_token( form_data: Annotated[OAuth2PasswordRequestForm, Depends()] -): +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException(status_code=400, detail="Incorrect username or password") @@ -155,7 +155,7 @@ async def login_for_access_token( data={"sub": user.username, "scopes": form_data.scopes}, expires_delta=access_token_expires, ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) diff --git a/docs_src/security/tutorial005_an_py39.py b/docs_src/security/tutorial005_an_py39.py index ecb5ed5160d86..af51c08b5081d 100644 --- a/docs_src/security/tutorial005_an_py39.py +++ b/docs_src/security/tutorial005_an_py39.py @@ -1,4 +1,4 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from typing import Annotated, List, Union from fastapi import Depends, FastAPI, HTTPException, Security, status @@ -93,9 +93,9 @@ def authenticate_user(fake_db, username: str, password: str): def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None): to_encode = data.copy() if expires_delta: - expire = datetime.utcnow() + expires_delta + expire = datetime.now(timezone.utc) + expires_delta else: - expire = datetime.utcnow() + timedelta(minutes=15) + expire = datetime.now(timezone.utc) + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt @@ -143,10 +143,10 @@ async def get_current_active_user( return current_user -@app.post("/token", response_model=Token) +@app.post("/token") async def login_for_access_token( form_data: Annotated[OAuth2PasswordRequestForm, Depends()] -): +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException(status_code=400, detail="Incorrect username or password") @@ -155,7 +155,7 @@ async def login_for_access_token( data={"sub": user.username, "scopes": form_data.scopes}, expires_delta=access_token_expires, ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) diff --git a/docs_src/security/tutorial005_py310.py b/docs_src/security/tutorial005_py310.py index ba756ef4f4d67..37a22c70907f6 100644 --- a/docs_src/security/tutorial005_py310.py +++ b/docs_src/security/tutorial005_py310.py @@ -1,4 +1,4 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from fastapi import Depends, FastAPI, HTTPException, Security, status from fastapi.security import ( @@ -92,9 +92,9 @@ def authenticate_user(fake_db, username: str, password: str): def create_access_token(data: dict, expires_delta: timedelta | None = None): to_encode = data.copy() if expires_delta: - expire = datetime.utcnow() + expires_delta + expire = datetime.now(timezone.utc) + expires_delta else: - expire = datetime.utcnow() + timedelta(minutes=15) + expire = datetime.now(timezone.utc) + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt @@ -142,8 +142,10 @@ async def get_current_active_user( return current_user -@app.post("/token", response_model=Token) -async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()): +@app.post("/token") +async def login_for_access_token( + form_data: OAuth2PasswordRequestForm = Depends() +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException(status_code=400, detail="Incorrect username or password") @@ -152,7 +154,7 @@ async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends( data={"sub": user.username, "scopes": form_data.scopes}, expires_delta=access_token_expires, ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) diff --git a/docs_src/security/tutorial005_py39.py b/docs_src/security/tutorial005_py39.py index 9e4dbcffba38d..c275807636c4b 100644 --- a/docs_src/security/tutorial005_py39.py +++ b/docs_src/security/tutorial005_py39.py @@ -1,4 +1,4 @@ -from datetime import datetime, timedelta +from datetime import datetime, timedelta, timezone from typing import Union from fastapi import Depends, FastAPI, HTTPException, Security, status @@ -93,9 +93,9 @@ def authenticate_user(fake_db, username: str, password: str): def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None): to_encode = data.copy() if expires_delta: - expire = datetime.utcnow() + expires_delta + expire = datetime.now(timezone.utc) + expires_delta else: - expire = datetime.utcnow() + timedelta(minutes=15) + expire = datetime.now(timezone.utc) + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt @@ -143,8 +143,10 @@ async def get_current_active_user( return current_user -@app.post("/token", response_model=Token) -async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()): +@app.post("/token") +async def login_for_access_token( + form_data: OAuth2PasswordRequestForm = Depends() +) -> Token: user = authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException(status_code=400, detail="Incorrect username or password") @@ -153,7 +155,7 @@ async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends( data={"sub": user.username, "scopes": form_data.scopes}, expires_delta=access_token_expires, ) - return {"access_token": access_token, "token_type": "bearer"} + return Token(access_token=access_token, token_type="bearer") @app.get("/users/me/", response_model=User) diff --git a/docs_src/security/tutorial007.py b/docs_src/security/tutorial007.py index 790ee10bc6b1d..ac816eb0c19d2 100644 --- a/docs_src/security/tutorial007.py +++ b/docs_src/security/tutorial007.py @@ -22,7 +22,7 @@ def get_current_username(credentials: HTTPBasicCredentials = Depends(security)): if not (is_correct_username and is_correct_password): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, - detail="Incorrect email or password", + detail="Incorrect username or password", headers={"WWW-Authenticate": "Basic"}, ) return credentials.username diff --git a/docs_src/security/tutorial007_an.py b/docs_src/security/tutorial007_an.py index 5fb7c8e57560c..9e9c3cd7020f0 100644 --- a/docs_src/security/tutorial007_an.py +++ b/docs_src/security/tutorial007_an.py @@ -25,7 +25,7 @@ def get_current_username( if not (is_correct_username and is_correct_password): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, - detail="Incorrect email or password", + detail="Incorrect username or password", headers={"WWW-Authenticate": "Basic"}, ) return credentials.username diff --git a/docs_src/security/tutorial007_an_py39.py b/docs_src/security/tutorial007_an_py39.py index 17177dabf9e47..3d9ea27269eed 100644 --- a/docs_src/security/tutorial007_an_py39.py +++ b/docs_src/security/tutorial007_an_py39.py @@ -25,7 +25,7 @@ def get_current_username( if not (is_correct_username and is_correct_password): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, - detail="Incorrect email or password", + detail="Incorrect username or password", headers={"WWW-Authenticate": "Basic"}, ) return credentials.username diff --git a/docs_src/sql_databases/sql_app/models.py b/docs_src/sql_databases/sql_app/models.py index 62d8ab4aaac16..09ae2a8077f68 100644 --- a/docs_src/sql_databases/sql_app/models.py +++ b/docs_src/sql_databases/sql_app/models.py @@ -7,7 +7,7 @@ class User(Base): __tablename__ = "users" - id = Column(Integer, primary_key=True, index=True) + id = Column(Integer, primary_key=True) email = Column(String, unique=True, index=True) hashed_password = Column(String) is_active = Column(Boolean, default=True) @@ -18,7 +18,7 @@ class User(Base): class Item(Base): __tablename__ = "items" - id = Column(Integer, primary_key=True, index=True) + id = Column(Integer, primary_key=True) title = Column(String, index=True) description = Column(String, index=True) owner_id = Column(Integer, ForeignKey("users.id")) diff --git a/docs_src/sql_databases/sql_app_py310/models.py b/docs_src/sql_databases/sql_app_py310/models.py index 62d8ab4aaac16..09ae2a8077f68 100644 --- a/docs_src/sql_databases/sql_app_py310/models.py +++ b/docs_src/sql_databases/sql_app_py310/models.py @@ -7,7 +7,7 @@ class User(Base): __tablename__ = "users" - id = Column(Integer, primary_key=True, index=True) + id = Column(Integer, primary_key=True) email = Column(String, unique=True, index=True) hashed_password = Column(String) is_active = Column(Boolean, default=True) @@ -18,7 +18,7 @@ class User(Base): class Item(Base): __tablename__ = "items" - id = Column(Integer, primary_key=True, index=True) + id = Column(Integer, primary_key=True) title = Column(String, index=True) description = Column(String, index=True) owner_id = Column(Integer, ForeignKey("users.id")) diff --git a/docs_src/sql_databases/sql_app_py39/models.py b/docs_src/sql_databases/sql_app_py39/models.py index 62d8ab4aaac16..09ae2a8077f68 100644 --- a/docs_src/sql_databases/sql_app_py39/models.py +++ b/docs_src/sql_databases/sql_app_py39/models.py @@ -7,7 +7,7 @@ class User(Base): __tablename__ = "users" - id = Column(Integer, primary_key=True, index=True) + id = Column(Integer, primary_key=True) email = Column(String, unique=True, index=True) hashed_password = Column(String) is_active = Column(Boolean, default=True) @@ -18,7 +18,7 @@ class User(Base): class Item(Base): __tablename__ = "items" - id = Column(Integer, primary_key=True, index=True) + id = Column(Integer, primary_key=True) title = Column(String, index=True) description = Column(String, index=True) owner_id = Column(Integer, ForeignKey("users.id")) diff --git a/docs_src/templates/templates/item.html b/docs_src/templates/templates/item.html index a70287e77d345..27994ca994b00 100644 --- a/docs_src/templates/templates/item.html +++ b/docs_src/templates/templates/item.html @@ -4,6 +4,6 @@ -

Item ID: {{ id }}

+

Item ID: {{ id }}

diff --git a/docs_src/templates/tutorial001.py b/docs_src/templates/tutorial001.py index 245e7110b195d..81ccc8d4d0b3f 100644 --- a/docs_src/templates/tutorial001.py +++ b/docs_src/templates/tutorial001.py @@ -13,4 +13,6 @@ @app.get("/items/{id}", response_class=HTMLResponse) async def read_item(request: Request, id: str): - return templates.TemplateResponse("item.html", {"request": request, "id": id}) + return templates.TemplateResponse( + request=request, name="item.html", context={"id": id} + ) diff --git a/fastapi/__init__.py b/fastapi/__init__.py index dd16ea34db1eb..f457fafd4aa64 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.105.0" +__version__ = "0.109.0" from starlette import status as status diff --git a/fastapi/applications.py b/fastapi/applications.py index 3021d75937d1c..597c60a56788f 100644 --- a/fastapi/applications.py +++ b/fastapi/applications.py @@ -22,7 +22,6 @@ ) from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError from fastapi.logger import logger -from fastapi.middleware.asyncexitstack import AsyncExitStackMiddleware from fastapi.openapi.docs import ( get_redoc_html, get_swagger_ui_html, @@ -37,8 +36,6 @@ from starlette.exceptions import HTTPException from starlette.middleware import Middleware from starlette.middleware.base import BaseHTTPMiddleware -from starlette.middleware.errors import ServerErrorMiddleware -from starlette.middleware.exceptions import ExceptionMiddleware from starlette.requests import Request from starlette.responses import HTMLResponse, JSONResponse, Response from starlette.routing import BaseRoute @@ -966,55 +963,6 @@ class Item(BaseModel): self.middleware_stack: Union[ASGIApp, None] = None self.setup() - def build_middleware_stack(self) -> ASGIApp: - # Duplicate/override from Starlette to add AsyncExitStackMiddleware - # inside of ExceptionMiddleware, inside of custom user middlewares - debug = self.debug - error_handler = None - exception_handlers = {} - - for key, value in self.exception_handlers.items(): - if key in (500, Exception): - error_handler = value - else: - exception_handlers[key] = value - - middleware = ( - [Middleware(ServerErrorMiddleware, handler=error_handler, debug=debug)] - + self.user_middleware - + [ - Middleware( - ExceptionMiddleware, handlers=exception_handlers, debug=debug - ), - # Add FastAPI-specific AsyncExitStackMiddleware for dependencies with - # contextvars. - # This needs to happen after user middlewares because those create a - # new contextvars context copy by using a new AnyIO task group. - # The initial part of dependencies with 'yield' is executed in the - # FastAPI code, inside all the middlewares. However, the teardown part - # (after 'yield') is executed in the AsyncExitStack in this middleware. - # If the AsyncExitStack lived outside of the custom middlewares and - # contextvars were set in a dependency with 'yield' in that internal - # contextvars context, the values would not be available in the - # outer context of the AsyncExitStack. - # By placing the middleware and the AsyncExitStack here, inside all - # user middlewares, the code before and after 'yield' in dependencies - # with 'yield' is executed in the same contextvars context. Thus, all values - # set in contextvars before 'yield' are still available after 'yield,' as - # expected. - # Additionally, by having this AsyncExitStack here, after the - # ExceptionMiddleware, dependencies can now catch handled exceptions, - # e.g. HTTPException, to customize the teardown code (e.g. DB session - # rollback). - Middleware(AsyncExitStackMiddleware), - ] - ) - - app = self.router - for cls, options in reversed(middleware): - app = cls(app=app, **options) - return app - def openapi(self) -> Dict[str, Any]: """ Generate the OpenAPI schema of the application. This is called by FastAPI diff --git a/fastapi/concurrency.py b/fastapi/concurrency.py index 754061c862dad..894bd3ed11873 100644 --- a/fastapi/concurrency.py +++ b/fastapi/concurrency.py @@ -1,4 +1,3 @@ -from contextlib import AsyncExitStack as AsyncExitStack # noqa from contextlib import asynccontextmanager as asynccontextmanager from typing import AsyncGenerator, ContextManager, TypeVar diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index 4e88410a5ec1f..b73473484159c 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -1,5 +1,5 @@ import inspect -from contextlib import contextmanager +from contextlib import AsyncExitStack, contextmanager from copy import deepcopy from typing import ( Any, @@ -46,7 +46,6 @@ ) from fastapi.background import BackgroundTasks from fastapi.concurrency import ( - AsyncExitStack, asynccontextmanager, contextmanager_in_threadpool, ) @@ -529,6 +528,7 @@ async def solve_dependencies( response: Optional[Response] = None, dependency_overrides_provider: Optional[Any] = None, dependency_cache: Optional[Dict[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, + async_exit_stack: AsyncExitStack, ) -> Tuple[ Dict[str, Any], List[Any], @@ -575,6 +575,7 @@ async def solve_dependencies( response=response, dependency_overrides_provider=dependency_overrides_provider, dependency_cache=dependency_cache, + async_exit_stack=async_exit_stack, ) ( sub_values, @@ -590,10 +591,8 @@ async def solve_dependencies( if sub_dependant.use_cache and sub_dependant.cache_key in dependency_cache: solved = dependency_cache[sub_dependant.cache_key] elif is_gen_callable(call) or is_async_gen_callable(call): - stack = request.scope.get("fastapi_astack") - assert isinstance(stack, AsyncExitStack) solved = await solve_generator( - call=call, stack=stack, sub_values=sub_values + call=call, stack=async_exit_stack, sub_values=sub_values ) elif is_coroutine_callable(call): solved = await call(**sub_values) diff --git a/fastapi/middleware/asyncexitstack.py b/fastapi/middleware/asyncexitstack.py deleted file mode 100644 index 30a0ae626c26c..0000000000000 --- a/fastapi/middleware/asyncexitstack.py +++ /dev/null @@ -1,25 +0,0 @@ -from typing import Optional - -from fastapi.concurrency import AsyncExitStack -from starlette.types import ASGIApp, Receive, Scope, Send - - -class AsyncExitStackMiddleware: - def __init__(self, app: ASGIApp, context_name: str = "fastapi_astack") -> None: - self.app = app - self.context_name = context_name - - async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: - dependency_exception: Optional[Exception] = None - async with AsyncExitStack() as stack: - scope[self.context_name] = stack - try: - await self.app(scope, receive, send) - except Exception as e: - dependency_exception = e - raise e - if dependency_exception: - # This exception was possibly handled by the dependency but it should - # still bubble up so that the ServerErrorMiddleware can return a 500 - # or the ExceptionMiddleware can catch and handle any other exceptions - raise dependency_exception diff --git a/fastapi/routing.py b/fastapi/routing.py index 54d53bbbfb812..acebabfca0566 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -216,95 +216,124 @@ def get_request_handler( actual_response_class = response_class async def app(request: Request) -> Response: - try: - body: Any = None - if body_field: - if is_body_form: - body = await request.form() - stack = request.scope.get("fastapi_astack") - assert isinstance(stack, AsyncExitStack) - stack.push_async_callback(body.close) + exception_to_reraise: Optional[Exception] = None + response: Union[Response, None] = None + async with AsyncExitStack() as async_exit_stack: + # TODO: remove this scope later, after a few releases + # This scope fastapi_astack is no longer used by FastAPI, kept for + # compatibility, just in case + request.scope["fastapi_astack"] = async_exit_stack + try: + body: Any = None + if body_field: + if is_body_form: + body = await request.form() + async_exit_stack.push_async_callback(body.close) + else: + body_bytes = await request.body() + if body_bytes: + json_body: Any = Undefined + content_type_value = request.headers.get("content-type") + if not content_type_value: + json_body = await request.json() + else: + message = email.message.Message() + message["content-type"] = content_type_value + if message.get_content_maintype() == "application": + subtype = message.get_content_subtype() + if subtype == "json" or subtype.endswith("+json"): + json_body = await request.json() + if json_body != Undefined: + body = json_body + else: + body = body_bytes + except json.JSONDecodeError as e: + validation_error = RequestValidationError( + [ + { + "type": "json_invalid", + "loc": ("body", e.pos), + "msg": "JSON decode error", + "input": {}, + "ctx": {"error": e.msg}, + } + ], + body=e.doc, + ) + exception_to_reraise = validation_error + raise validation_error from e + except HTTPException as e: + exception_to_reraise = e + raise + except Exception as e: + http_error = HTTPException( + status_code=400, detail="There was an error parsing the body" + ) + exception_to_reraise = http_error + raise http_error from e + try: + solved_result = await solve_dependencies( + request=request, + dependant=dependant, + body=body, + dependency_overrides_provider=dependency_overrides_provider, + async_exit_stack=async_exit_stack, + ) + values, errors, background_tasks, sub_response, _ = solved_result + except Exception as e: + exception_to_reraise = e + raise e + if errors: + validation_error = RequestValidationError( + _normalize_errors(errors), body=body + ) + exception_to_reraise = validation_error + raise validation_error + else: + try: + raw_response = await run_endpoint_function( + dependant=dependant, values=values, is_coroutine=is_coroutine + ) + except Exception as e: + exception_to_reraise = e + raise e + if isinstance(raw_response, Response): + if raw_response.background is None: + raw_response.background = background_tasks + response = raw_response else: - body_bytes = await request.body() - if body_bytes: - json_body: Any = Undefined - content_type_value = request.headers.get("content-type") - if not content_type_value: - json_body = await request.json() - else: - message = email.message.Message() - message["content-type"] = content_type_value - if message.get_content_maintype() == "application": - subtype = message.get_content_subtype() - if subtype == "json" or subtype.endswith("+json"): - json_body = await request.json() - if json_body != Undefined: - body = json_body - else: - body = body_bytes - except json.JSONDecodeError as e: - raise RequestValidationError( - [ - { - "type": "json_invalid", - "loc": ("body", e.pos), - "msg": "JSON decode error", - "input": {}, - "ctx": {"error": e.msg}, - } - ], - body=e.doc, - ) from e - except HTTPException: - raise - except Exception as e: - raise HTTPException( - status_code=400, detail="There was an error parsing the body" - ) from e - solved_result = await solve_dependencies( - request=request, - dependant=dependant, - body=body, - dependency_overrides_provider=dependency_overrides_provider, - ) - values, errors, background_tasks, sub_response, _ = solved_result - if errors: - raise RequestValidationError(_normalize_errors(errors), body=body) - else: - raw_response = await run_endpoint_function( - dependant=dependant, values=values, is_coroutine=is_coroutine - ) - - if isinstance(raw_response, Response): - if raw_response.background is None: - raw_response.background = background_tasks - return raw_response - response_args: Dict[str, Any] = {"background": background_tasks} - # If status_code was set, use it, otherwise use the default from the - # response class, in the case of redirect it's 307 - current_status_code = ( - status_code if status_code else sub_response.status_code - ) - if current_status_code is not None: - response_args["status_code"] = current_status_code - if sub_response.status_code: - response_args["status_code"] = sub_response.status_code - content = await serialize_response( - field=response_field, - response_content=raw_response, - include=response_model_include, - exclude=response_model_exclude, - by_alias=response_model_by_alias, - exclude_unset=response_model_exclude_unset, - exclude_defaults=response_model_exclude_defaults, - exclude_none=response_model_exclude_none, - is_coroutine=is_coroutine, - ) - response = actual_response_class(content, **response_args) - if not is_body_allowed_for_status_code(response.status_code): - response.body = b"" - response.headers.raw.extend(sub_response.headers.raw) - return response + response_args: Dict[str, Any] = {"background": background_tasks} + # If status_code was set, use it, otherwise use the default from the + # response class, in the case of redirect it's 307 + current_status_code = ( + status_code if status_code else sub_response.status_code + ) + if current_status_code is not None: + response_args["status_code"] = current_status_code + if sub_response.status_code: + response_args["status_code"] = sub_response.status_code + content = await serialize_response( + field=response_field, + response_content=raw_response, + include=response_model_include, + exclude=response_model_exclude, + by_alias=response_model_by_alias, + exclude_unset=response_model_exclude_unset, + exclude_defaults=response_model_exclude_defaults, + exclude_none=response_model_exclude_none, + is_coroutine=is_coroutine, + ) + response = actual_response_class(content, **response_args) + if not is_body_allowed_for_status_code(response.status_code): + response.body = b"" + response.headers.raw.extend(sub_response.headers.raw) + # This exception was possibly handled by the dependency but it should + # still bubble up so that the ServerErrorMiddleware can return a 500 + # or the ExceptionMiddleware can catch and handle any other exceptions + if exception_to_reraise: + raise exception_to_reraise + assert response is not None, "An error occurred while generating the request" + return response return app @@ -313,16 +342,22 @@ def get_websocket_app( dependant: Dependant, dependency_overrides_provider: Optional[Any] = None ) -> Callable[[WebSocket], Coroutine[Any, Any, Any]]: async def app(websocket: WebSocket) -> None: - solved_result = await solve_dependencies( - request=websocket, - dependant=dependant, - dependency_overrides_provider=dependency_overrides_provider, - ) - values, errors, _, _2, _3 = solved_result - if errors: - raise WebSocketRequestValidationError(_normalize_errors(errors)) - assert dependant.call is not None, "dependant.call must be a function" - await dependant.call(**values) + async with AsyncExitStack() as async_exit_stack: + # TODO: remove this scope later, after a few releases + # This scope fastapi_astack is no longer used by FastAPI, kept for + # compatibility, just in case + websocket.scope["fastapi_astack"] = async_exit_stack + solved_result = await solve_dependencies( + request=websocket, + dependant=dependant, + dependency_overrides_provider=dependency_overrides_provider, + async_exit_stack=async_exit_stack, + ) + values, errors, _, _2, _3 = solved_result + if errors: + raise WebSocketRequestValidationError(_normalize_errors(errors)) + assert dependant.call is not None, "dependant.call must be a function" + await dependant.call(**values) return app @@ -4293,7 +4328,7 @@ class Item(BaseModel): app = FastAPI() router = APIRouter() - @router.put("/items/{item_id}") + @router.trace("/items/{item_id}") def trace_item(item_id: str): return None diff --git a/fastapi/utils.py b/fastapi/utils.py index f8463dda24675..53b2fa0c36ba6 100644 --- a/fastapi/utils.py +++ b/fastapi/utils.py @@ -53,7 +53,7 @@ def is_body_allowed_for_status_code(status_code: Union[int, str, None]) -> bool: }: return True current_status_code = int(status_code) - return not (current_status_code < 200 or current_status_code in {204, 304}) + return not (current_status_code < 200 or current_status_code in {204, 205, 304}) def get_path_param_names(path: str) -> Set[str]: @@ -173,17 +173,17 @@ def generate_operation_id_for_path( DeprecationWarning, stacklevel=2, ) - operation_id = name + path + operation_id = f"{name}{path}" operation_id = re.sub(r"\W", "_", operation_id) - operation_id = operation_id + "_" + method.lower() + operation_id = f"{operation_id}_{method.lower()}" return operation_id def generate_unique_id(route: "APIRoute") -> str: - operation_id = route.name + route.path_format + operation_id = f"{route.name}{route.path_format}" operation_id = re.sub(r"\W", "_", operation_id) assert route.methods - operation_id = operation_id + "_" + list(route.methods)[0].lower() + operation_id = f"{operation_id}_{list(route.methods)[0].lower()}" return operation_id diff --git a/pyproject.toml b/pyproject.toml index e67486ae31bf8..3e43f35e17cac 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -36,15 +36,14 @@ classifiers = [ "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", "Topic :: Internet :: WWW/HTTP :: HTTP Servers", "Topic :: Internet :: WWW/HTTP", ] dependencies = [ - "starlette>=0.27.0,<0.28.0", + "starlette>=0.35.0,<0.36.0", "pydantic>=1.7.4,!=1.8,!=1.8.1,!=2.0.0,!=2.0.1,!=2.1.0,<3.0.0", "typing-extensions>=4.8.0", - # TODO: remove this pin after upgrading Starlette 0.31.1 - "anyio>=3.7.1,<4.0.0", ] dynamic = ["version"] @@ -84,6 +83,12 @@ module = "fastapi.tests.*" ignore_missing_imports = true check_untyped_defs = true +[[tool.mypy.overrides]] +module = "docs_src.*" +disallow_incomplete_defs = false +disallow_untyped_defs = false +disallow_untyped_calls = false + [tool.pytest.ini_options] addopts = [ "--strict-config", @@ -107,6 +112,18 @@ filterwarnings = [ "ignore::trio.TrioDeprecationWarning", # TODO remove pytest-cov 'ignore::pytest.PytestDeprecationWarning:pytest_cov', + # TODO: remove after upgrading SQLAlchemy to a version that includes the following changes + # https://github.com/sqlalchemy/sqlalchemy/commit/59521abcc0676e936b31a523bd968fc157fef0c2 + 'ignore:datetime\.datetime\.utcfromtimestamp\(\) is deprecated and scheduled for removal in a future version\..*:DeprecationWarning:sqlalchemy', + # TODO: remove after upgrading python-jose to a version that explicitly supports Python 3.12 + # also, if it won't receive an update, consider replacing python-jose with some alternative + # related issues: + # - https://github.com/mpdavis/python-jose/issues/332 + # - https://github.com/mpdavis/python-jose/issues/334 + 'ignore:datetime\.datetime\.utcnow\(\) is deprecated and scheduled for removal in a future version\..*:DeprecationWarning:jose', + # TODO: remove after upgrading Starlette to a version including https://github.com/encode/starlette/pull/2406 + # Probably Starlette 0.36.0 + "ignore: The 'method' parameter is not used, and it will be removed.:DeprecationWarning:starlette", ] [tool.coverage.run] @@ -128,15 +145,14 @@ select = [ "W", # pycodestyle warnings "F", # pyflakes "I", # isort - "C", # flake8-comprehensions "B", # flake8-bugbear + "C4", # flake8-comprehensions "UP", # pyupgrade ] ignore = [ "E501", # line too long, handled by black "B008", # do not perform function calls in argument defaults - "C901", # too complex - "W191", # indentation contains tabs + "W191", # indentation contains tabs ] [tool.ruff.per-file-ignores] @@ -167,6 +183,9 @@ ignore = [ "docs_src/security/tutorial005_an_py39.py" = ["B904"] "docs_src/security/tutorial005_py310.py" = ["B904"] "docs_src/security/tutorial005_py39.py" = ["B904"] +"docs_src/dependencies/tutorial008b.py" = ["B904"] +"docs_src/dependencies/tutorial008b_an.py" = ["B904"] +"docs_src/dependencies/tutorial008b_an_py39.py" = ["B904"] [tool.ruff.isort] diff --git a/scripts/docs.py b/scripts/docs.py index 73e1900ada0c4..37a7a34779d1a 100644 --- a/scripts/docs.py +++ b/scripts/docs.py @@ -53,9 +53,6 @@ def get_lang_paths() -> List[Path]: def lang_callback(lang: Optional[str]) -> Union[str, None]: if lang is None: return None - if not lang.isalpha() or len(lang) != 2: - typer.echo("Use a 2 letter language code, like: es") - raise typer.Abort() lang = lang.lower() return lang @@ -274,22 +271,30 @@ def live( def update_config() -> None: config = get_en_config() languages = [{"en": "/"}] - alternate: List[Dict[str, str]] = config["extra"].get("alternate", []) - alternate_dict = {alt["link"]: alt["name"] for alt in alternate} new_alternate: List[Dict[str, str]] = [] + # Language names sourced from https://quickref.me/iso-639-1 + # Contributors may wish to update or change these, e.g. to fix capitalization. + language_names_path = Path(__file__).parent / "../docs/language_names.yml" + local_language_names: Dict[str, str] = mkdocs.utils.yaml_load( + language_names_path.read_text(encoding="utf-8") + ) for lang_path in get_lang_paths(): - if lang_path.name == "en" or not lang_path.is_dir(): + if lang_path.name in {"en", "em"} or not lang_path.is_dir(): continue - name = lang_path.name - languages.append({name: f"/{name}/"}) + code = lang_path.name + languages.append({code: f"/{code}/"}) for lang_dict in languages: - name = list(lang_dict.keys())[0] - url = lang_dict[name] - if url not in alternate_dict: - new_alternate.append({"link": url, "name": name}) - else: - use_name = alternate_dict[url] - new_alternate.append({"link": url, "name": use_name}) + code = list(lang_dict.keys())[0] + url = lang_dict[code] + if code not in local_language_names: + print( + f"Missing language name for: {code}, " + "update it in docs/language_names.yml" + ) + raise typer.Abort() + use_name = f"{code} - {local_language_names[code]}" + new_alternate.append({"link": url, "name": use_name}) + new_alternate.append({"link": "/em/", "name": "😉"}) config["extra"]["alternate"] = new_alternate en_config_path.write_text( yaml.dump(config, sort_keys=False, width=200, allow_unicode=True), diff --git a/tests/test_dependency_contextmanager.py b/tests/test_dependency_contextmanager.py index 03ef56c4d7e5b..b07f9aa5b6c6b 100644 --- a/tests/test_dependency_contextmanager.py +++ b/tests/test_dependency_contextmanager.py @@ -1,7 +1,9 @@ +import json from typing import Dict import pytest from fastapi import BackgroundTasks, Depends, FastAPI +from fastapi.responses import StreamingResponse from fastapi.testclient import TestClient app = FastAPI() @@ -200,6 +202,13 @@ async def bg(state: dict): return state +@app.middleware("http") +async def middleware(request, call_next): + response: StreamingResponse = await call_next(request) + response.headers["x-state"] = json.dumps(state.copy()) + return response + + client = TestClient(app) @@ -274,9 +283,13 @@ def test_background_tasks(): assert data["context_b"] == "started b" assert data["context_a"] == "started a" assert data["bg"] == "not set" + middleware_state = json.loads(response.headers["x-state"]) + assert middleware_state["context_b"] == "finished b with a: started a" + assert middleware_state["context_a"] == "finished a" + assert middleware_state["bg"] == "not set" assert state["context_b"] == "finished b with a: started a" assert state["context_a"] == "finished a" - assert state["bg"] == "bg set - b: started b - a: started a" + assert state["bg"] == "bg set - b: finished b with a: started a - a: finished a" def test_sync_raise_raises(): @@ -382,4 +395,7 @@ def test_sync_background_tasks(): assert data["sync_bg"] == "not set" assert state["context_b"] == "finished b with a: started a" assert state["context_a"] == "finished a" - assert state["sync_bg"] == "sync_bg set - b: started b - a: started a" + assert ( + state["sync_bg"] + == "sync_bg set - b: finished b with a: started a - a: finished a" + ) diff --git a/tests/test_generate_unique_id_function.py b/tests/test_generate_unique_id_function.py index c5ef5182b73f7..5aeec66367a7c 100644 --- a/tests/test_generate_unique_id_function.py +++ b/tests/test_generate_unique_id_function.py @@ -1626,6 +1626,9 @@ def post_third(item1: Item): with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") client.get("/openapi.json") - assert len(w) == 2 - assert issubclass(w[-1].category, UserWarning) - assert "Duplicate Operation ID" in str(w[-1].message) + assert len(w) >= 2 + duplicate_warnings = [ + warning for warning in w if issubclass(warning.category, UserWarning) + ] + assert len(duplicate_warnings) > 0 + assert "Duplicate Operation ID" in str(duplicate_warnings[0].message) diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008b.py b/tests/test_tutorial/test_dependencies/test_tutorial008b.py new file mode 100644 index 0000000000000..86acba9e4ff95 --- /dev/null +++ b/tests/test_tutorial/test_dependencies/test_tutorial008b.py @@ -0,0 +1,23 @@ +from fastapi.testclient import TestClient + +from docs_src.dependencies.tutorial008b import app + +client = TestClient(app) + + +def test_get_no_item(): + response = client.get("/items/foo") + assert response.status_code == 404, response.text + assert response.json() == {"detail": "Item not found"} + + +def test_owner_error(): + response = client.get("/items/plumbus") + assert response.status_code == 400, response.text + assert response.json() == {"detail": "Owner error: Rick"} + + +def test_get_item(): + response = client.get("/items/portal-gun") + assert response.status_code == 200, response.text + assert response.json() == {"description": "Gun to create portals", "owner": "Rick"} diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008b_an.py b/tests/test_tutorial/test_dependencies/test_tutorial008b_an.py new file mode 100644 index 0000000000000..7f51fc52a5133 --- /dev/null +++ b/tests/test_tutorial/test_dependencies/test_tutorial008b_an.py @@ -0,0 +1,23 @@ +from fastapi.testclient import TestClient + +from docs_src.dependencies.tutorial008b_an import app + +client = TestClient(app) + + +def test_get_no_item(): + response = client.get("/items/foo") + assert response.status_code == 404, response.text + assert response.json() == {"detail": "Item not found"} + + +def test_owner_error(): + response = client.get("/items/plumbus") + assert response.status_code == 400, response.text + assert response.json() == {"detail": "Owner error: Rick"} + + +def test_get_item(): + response = client.get("/items/portal-gun") + assert response.status_code == 200, response.text + assert response.json() == {"description": "Gun to create portals", "owner": "Rick"} diff --git a/tests/test_tutorial/test_dependencies/test_tutorial008b_an_py39.py b/tests/test_tutorial/test_dependencies/test_tutorial008b_an_py39.py new file mode 100644 index 0000000000000..7f51fc52a5133 --- /dev/null +++ b/tests/test_tutorial/test_dependencies/test_tutorial008b_an_py39.py @@ -0,0 +1,23 @@ +from fastapi.testclient import TestClient + +from docs_src.dependencies.tutorial008b_an import app + +client = TestClient(app) + + +def test_get_no_item(): + response = client.get("/items/foo") + assert response.status_code == 404, response.text + assert response.json() == {"detail": "Item not found"} + + +def test_owner_error(): + response = client.get("/items/plumbus") + assert response.status_code == 400, response.text + assert response.json() == {"detail": "Owner error: Rick"} + + +def test_get_item(): + response = client.get("/items/portal-gun") + assert response.status_code == 200, response.text + assert response.json() == {"description": "Gun to create portals", "owner": "Rick"} diff --git a/tests/test_tutorial/test_header_params/test_tutorial003.py b/tests/test_tutorial/test_header_params/test_tutorial003.py index 268df7a3e9a80..6f7de8ed41acd 100644 --- a/tests/test_tutorial/test_header_params/test_tutorial003.py +++ b/tests/test_tutorial/test_header_params/test_tutorial003.py @@ -12,8 +12,12 @@ [ ("/items", None, 200, {"X-Token values": None}), ("/items", {"x-token": "foo"}, 200, {"X-Token values": ["foo"]}), - # TODO: fix this, is it a bug? - # ("/items", [("x-token", "foo"), ("x-token", "bar")], 200, {"X-Token values": ["foo", "bar"]}), + ( + "/items", + [("x-token", "foo"), ("x-token", "bar")], + 200, + {"X-Token values": ["foo", "bar"]}, + ), ], ) def test(path, headers, expected_status, expected_response): diff --git a/tests/test_tutorial/test_templates/test_tutorial001.py b/tests/test_tutorial/test_templates/test_tutorial001.py index bfee5c0902dbc..4d4729425e845 100644 --- a/tests/test_tutorial/test_templates/test_tutorial001.py +++ b/tests/test_tutorial/test_templates/test_tutorial001.py @@ -16,7 +16,10 @@ def test_main(): client = TestClient(app) response = client.get("/items/foo") assert response.status_code == 200, response.text - assert b"

Item ID: foo

" in response.content + assert ( + b'

Item ID: foo

' + in response.content + ) response = client.get("/static/styles.css") assert response.status_code == 200, response.text assert b"color: green;" in response.content