diff --git a/.github/workflows/build-docs.yml b/.github/workflows/build-docs.yml index 6ecdf487c..e84e4e4ab 100644 --- a/.github/workflows/build-docs.yml +++ b/.github/workflows/build-docs.yml @@ -53,7 +53,7 @@ jobs: with: python-version: "3.11" - name: Setup uv - uses: astral-sh/setup-uv@v5 + uses: astral-sh/setup-uv@v6 with: version: "0.4.15" enable-cache: true @@ -95,7 +95,7 @@ jobs: with: python-version: "3.11" - name: Setup uv - uses: astral-sh/setup-uv@v5 + uses: astral-sh/setup-uv@v6 with: version: "0.4.15" enable-cache: true diff --git a/.github/workflows/contributors.yml b/.github/workflows/contributors.yml index 87abfe3a1..34b54b452 100644 --- a/.github/workflows/contributors.yml +++ b/.github/workflows/contributors.yml @@ -30,7 +30,7 @@ jobs: with: python-version: "3.11" - name: Setup uv - uses: astral-sh/setup-uv@v5 + uses: astral-sh/setup-uv@v6 with: version: "0.4.15" enable-cache: true diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index d9ed61910..9ca69b208 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -29,7 +29,7 @@ jobs: with: python-version: "3.11" - name: Setup uv - uses: astral-sh/setup-uv@v5 + uses: astral-sh/setup-uv@v6 with: version: "0.4.15" enable-cache: true @@ -62,10 +62,7 @@ jobs: env: PROJECT_NAME: fastapitiangolo BRANCH: ${{ ( github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.head_branch == 'master' && 'main' ) || ( github.event.workflow_run.head_sha ) }} - # TODO: Use v3 when it's fixed, probably in v3.11 - # https://github.com/cloudflare/wrangler-action/issues/307 - uses: cloudflare/wrangler-action@v3.13 - # uses: cloudflare/wrangler-action@v3 + uses: cloudflare/wrangler-action@v3 with: apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} diff --git a/.github/workflows/label-approved.yml b/.github/workflows/label-approved.yml index 02070146c..908a9453d 100644 --- a/.github/workflows/label-approved.yml +++ b/.github/workflows/label-approved.yml @@ -26,7 +26,7 @@ jobs: with: python-version: "3.11" - name: Setup uv - uses: astral-sh/setup-uv@v5 + uses: astral-sh/setup-uv@v6 with: version: "0.4.15" enable-cache: true diff --git a/.github/workflows/notify-translations.yml b/.github/workflows/notify-translations.yml index c96992689..621d1253a 100644 --- a/.github/workflows/notify-translations.yml +++ b/.github/workflows/notify-translations.yml @@ -34,7 +34,7 @@ jobs: with: python-version: "3.11" - name: Setup uv - uses: astral-sh/setup-uv@v5 + uses: astral-sh/setup-uv@v6 with: version: "0.4.15" enable-cache: true diff --git a/.github/workflows/people.yml b/.github/workflows/people.yml index 6ec3c1ad2..11931a05a 100644 --- a/.github/workflows/people.yml +++ b/.github/workflows/people.yml @@ -30,7 +30,7 @@ jobs: with: python-version: "3.11" - name: Setup uv - uses: astral-sh/setup-uv@v5 + uses: astral-sh/setup-uv@v6 with: version: "0.4.15" enable-cache: true diff --git a/.github/workflows/smokeshow.yml b/.github/workflows/smokeshow.yml index a0ffd55e6..d8a5dfb30 100644 --- a/.github/workflows/smokeshow.yml +++ b/.github/workflows/smokeshow.yml @@ -26,7 +26,7 @@ jobs: with: python-version: '3.9' - name: Setup uv - uses: astral-sh/setup-uv@v5 + uses: astral-sh/setup-uv@v6 with: version: "0.4.15" enable-cache: true diff --git a/.github/workflows/sponsors.yml b/.github/workflows/sponsors.yml index a5230c834..6da4d90e1 100644 --- a/.github/workflows/sponsors.yml +++ b/.github/workflows/sponsors.yml @@ -30,7 +30,7 @@ jobs: with: python-version: "3.11" - name: Setup uv - uses: astral-sh/setup-uv@v5 + uses: astral-sh/setup-uv@v6 with: version: "0.4.15" enable-cache: true diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 5e8092641..c3940be01 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -29,7 +29,7 @@ jobs: with: python-version: "3.11" - name: Setup uv - uses: astral-sh/setup-uv@v5 + uses: astral-sh/setup-uv@v6 with: version: "0.4.15" enable-cache: true @@ -67,7 +67,7 @@ jobs: with: python-version: ${{ matrix.python-version }} - name: Setup uv - uses: astral-sh/setup-uv@v5 + uses: astral-sh/setup-uv@v6 with: version: "0.4.15" enable-cache: true @@ -112,7 +112,7 @@ jobs: with: python-version: '3.8' - name: Setup uv - uses: astral-sh/setup-uv@v5 + uses: astral-sh/setup-uv@v6 with: version: "0.4.15" enable-cache: true diff --git a/.github/workflows/topic-repos.yml b/.github/workflows/topic-repos.yml index 3c5c881f1..433aeb00b 100644 --- a/.github/workflows/topic-repos.yml +++ b/.github/workflows/topic-repos.yml @@ -25,7 +25,7 @@ jobs: with: python-version: "3.11" - name: Setup uv - uses: astral-sh/setup-uv@v5 + uses: astral-sh/setup-uv@v6 with: version: "0.4.15" enable-cache: true diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 767ef8d9e..445676b8b 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -14,7 +14,7 @@ repos: - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.7.4 + rev: v0.11.11 hooks: - id: ruff args: diff --git a/README.md b/README.md index f6da22b21..78ae6b10e 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@

- Test + Test Coverage @@ -49,20 +49,19 @@ The key features are: - - - - + - + + + @@ -149,7 +148,7 @@ $ pip install "fastapi[standard]" ### Create it -* Create a file `main.py` with: +Create a file `main.py` with: ```Python from typing import Union diff --git a/docs/az/docs/index.md b/docs/az/docs/index.md index ad78d7d06..fbbbce130 100644 --- a/docs/az/docs/index.md +++ b/docs/az/docs/index.md @@ -6,7 +6,7 @@

- Test + Test Əhatə diff --git a/docs/bn/docs/environment-variables.md b/docs/bn/docs/environment-variables.md new file mode 100644 index 000000000..9122ca5bf --- /dev/null +++ b/docs/bn/docs/environment-variables.md @@ -0,0 +1,298 @@ +# এনভায়রনমেন্ট ভেরিয়েবলস + +/// tip + +আপনি যদি "এনভায়রনমেন্ট ভেরিয়েবলস" কী এবং সেগুলো কীভাবে ব্যবহার করতে হয় সেটা জানেন, তাহলে এই অংশটি স্কিপ করে যেতে পারেন। + +/// + +এনভায়রনমেন্ট ভেরিয়েবল (সংক্ষেপে "**env var**" নামেও পরিচিত) হলো এমন একটি ভেরিয়েবল যা পাইথন কোডের **বাইরে**, **অপারেটিং সিস্টেমে** থাকে এবং আপনার পাইথন কোড (বা অন্যান্য প্রোগ্রাম) দ্বারা যাকে রিড করা যায়। + +এনভায়রনমেন্ট ভেরিয়েবলস অ্যাপ্লিকেশনের **সেটিংস** পরিচালনা করতে, পাইথনের **ইনস্টলেশন** প্রক্রিয়ার অংশ হিসেবে, ইত্যাদি কাজে উপযোগী হতে পারে। + +## Env Vars তৈরী এবং ব্যবহার + +আপনি **শেল (টার্মিনাল)**-এ, পাইথনের প্রয়োজন ছাড়াই, এনভায়রনমেন্ট ভেরিয়েবলস **তৈরি** এবং ব্যবহার করতে পারবেনঃ + +//// tab | লিনাক্স, ম্যাকওএস, উইন্ডোজ Bash + +

+ +```console +// আপনি চাইলে MY_NAME নামে একটি env var তৈরি করতে পারেন +$ export MY_NAME="Wade Wilson" + +// তারপরে এটিকে চাইলে অন্যান্য প্রোগ্রামে ব্যবহার করতে পারেন +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +//// tab | উইন্ডোজ পাওয়ারশেল + +
+ +```console +// MY_NAME নামে env var তৈরি +$ $Env:MY_NAME = "Wade Wilson" + +// অন্যান্য প্রোগ্রামে এটিকে ব্যবহার +$ echo "Hello $Env:MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +## পাইথনে env vars রিড করা + +আপনি চাইলে পাইথনের **বাইরে**, টার্মিনালে (বা অন্য কোনো উপায়ে) এনভায়রনমেন্ট ভেরিয়েবলস তৈরি করতে পারেন, এবং পরে সেগুলো **পাইথনে রিড** (অ্যাক্সেস করতে) পারেন। + +উদাহরণস্বরূপ, আপনার `main.py` নামে একটি ফাইল থাকতে পারেঃ + +```Python hl_lines="3" +import os + +name = os.getenv("MY_NAME", "World") +print(f"Hello {name} from Python") +``` + +/// tip + +
`os.getenv()` এর দ্বিতীয় আর্গুমেন্টটি হলো এর ডিফল্ট ভ্যালু যা রিটার্ন করা হবে। + +যদি এটি দেওয়া না হয়, ডিফল্টভাবে `None` ব্যবহৃত হবে, এখানে আমরা ডিফল্ট ভ্যালু হিসেবে `"World"` ব্যবহার করেছি। + +/// + +তারপরে পাইথন প্রোগ্রামটিকে নিম্নোক্তভাবে কল করা যাবেঃ + +//// tab | লিনাক্স, ম্যাকওএস, উইন্ডোজ Bash + +
+ +```console +// এখনো আমরা এনভায়রনমেন্ট ভেরিয়েবল সেট করিনি +$ python main.py + +// যেহেতু env var সেট করা হয়নি, তাই আমরা ডিফল্ট ভ্যালু পাচ্ছি + +Hello World from Python + +// কিন্তু আমরা প্রথমে যদি একটা এনভায়রনমেন্ট ভারিয়েবল তৈরি করে নেই +$ export MY_NAME="Wade Wilson" + +// এবং তারপর আবার প্রোগ্রাটিকে কল করি +$ python main.py + +// এখন এটি এনভায়রনমেন্ট ভেরিয়েবল রিড করতে পারবে + +Hello Wade Wilson from Python +``` + +
+ +//// + +//// tab | উইন্ডোজ পাওয়ারশেল + +
+ +```console +// এখনো আমরা এনভায়রনমেন্ট ভেরিয়েবল সেট করিনি +$ python main.py + +// যেহেতু env var সেট করা হয়নি, তাই আমরা ডিফল্ট ভ্যালু পাচ্ছি + +Hello World from Python + +// কিন্তু আমরা প্রথমে যদি একটা এনভায়রনমেন্ট ভারিয়েবল তৈরি করে নেই +$ $Env:MY_NAME = "Wade Wilson" + +// এবং তারপর আবার প্রোগ্রাটিকে কল করি +$ python main.py + +// এখন এটি এনভায়রনমেন্ট ভেরিয়েবল রিড করতে পারবে + +Hello Wade Wilson from Python +``` + +
+ +//// + +যেহেতু এনভায়রনমেন্ট ভেরিয়েবলস কোডের বাইরে সেট করা যায়, কিন্তু পরবর্তীতে কোড দ্বারা রিড করা যায়, এবং বাকি ফাইলগুলোর সাথে রাখতে (`git` এ কমিট) হয় না, তাই কনফিগারেশনস বা **সেটিংস** এর জন্য এগুলো সাধারণত ব্যবহৃত হয়ে থাকে। + +আপনি একটি এনভায়রনমেন্ট ভেরিয়েবল শুধুমাত্র একটি **নির্দিষ্ট প্রোগ্রাম ইনভোকেশনের** জন্যও তৈরি করতে পারেন, যা শুধুমাত্র সেই প্রোগ্রামের জন্যই এভেইলেবল থাকবে এবং শুধুমাত্র তার চলাকালীন সময় পর্যন্তই সক্রিয় থাকবে। + +এটি করতে, প্রোগ্রামটি রান করার ঠিক আগেই, একই লাইনে এনভায়রনমেন্ট ভেরিয়েবল তৈরি করুন: + +
+ +```console +// প্রোগ্রামটি কল করার সময় একই লাইনে MY_NAME এনভায়রনমেন্ট ভেরিয়েবল তৈরি করুন +$ MY_NAME="Wade Wilson" python main.py + +// এখন এটি এনভায়রনমেন্ট ভ্যরিয়েবলটিকে রিড করতে পারবে + +Hello Wade Wilson from Python + +// পরবর্তীতে এনভায়রনমেন্ট ভেরিয়েবলটিকে আর ব্যবহার করা যাচ্ছে না +$ python main.py + +Hello World from Python +``` + +
+ +/// tip + +এটি নিয়ে আরো বিস্তারিত পড়তে পারেন এখানে The Twelve-Factor App: Config। + +/// + +## টাইপস এবং ভ্যালিডেশন + +এই এনভায়রনমেন্ট ভেরিয়েবলগুলো শুধুমাত্র **টেক্সট স্ট্রিংস** হ্যান্ডেল করতে পারে, যেহেতু এগুলো পাইথনের বাইরে অবস্থিত এবং অন্যান্য প্রোগ্রাম এবং সিস্টেমের বাকি অংশের (এমনকি বিভিন্ন অপারেটিং সিস্টেম যেমন লিনাক্স, উইন্ডোজ, ম্যাকওএস) সাথে সামঞ্জস্যপূর্ণ হতে হয়। + +এর অর্থ হচ্ছে পাইথনে এনভায়রনমেন্ট ভেরিয়েবল থেকে রিড করা **যেকোনো ভ্যালু** একটি `str` হবে, এবং অন্য কোনো টাইপে কনভার্সন বা যেকোনো ভেলিডেশন কোডে আলাদাভাবে করতে হবে। + +এনভায়রনমেন্ট ভেরিয়েবল ব্যবহার করে **এপ্লিকেশন সেটিংস** হ্যান্ডেল করা নিয়ে আরো বিস্তারিত জানা যাবে [Advanced User Guide - Settings and Environment Variables](./advanced/settings.md){.internal-link target=_blank}. + +## `PATH` এনভায়রনমেন্ট ভেরিয়েবল + +**`PATH`** নামে একটি **বিশেষ** এনভায়রনমেন্ট ভেরিয়েবল রয়েছে, যেটি প্রোগ্রাম রান করার জন্য অপারেটিং সিস্টেমস (লিনাক্স, ম্যাকওএস, উইন্ডোজ) দ্বারা ব্যবহৃত হয়। + +`PATH` ভেরিয়েবল এর ভ্যালু হচ্ছে একটি বিশাল স্ট্রিং যা ডিরেক্টরিকে কোলন `:` দিয়ে আলাদা করার মাধ্যমে লিনাক্সে ও ম্যাকওএস এ, এবং সেমিকোলন `;` এর মাধ্যমে উইন্ডোজ এ তৈরি করা থাকে। + +উদাহরণস্বরূপ, `PATH` ভেরিয়েবল নিচের মতো দেখতে হতে পারেঃ + +//// tab | লিনাক্স, ম্যাকওএস + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +তারমানে হলো সিস্টেম প্রোগ্রামগুলোকে নিচের ডিরেক্টরিগুলোতে খুঁজবেঃ + +* `/usr/local/bin` +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | উইন্ডোজ + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32 +``` + +তারমানে হলো সিস্টেম প্রোগ্রামগুলোকে নিচের ডিরেক্টরিগুলোতে খুঁজবেঃ + +* `C:\Program Files\Python312\Scripts` +* `C:\Program Files\Python312` +* `C:\Windows\System32` + +//// + +যখন আপনি টার্মিনালে কোনো **কমান্ড** লিখবেন, অপারেটিং সিস্টেম **প্রত্যেকটি ডিরেক্টরিতে** প্রোগ্রামটি **খুঁজবে** যেগুলো `PATH` এনভায়রনমেন্ট ভেরিয়েবল এ লিস্ট করা আছে। + +উদাহরণস্বরূপ, যখন আপনি টার্মিনালে `python` টাইপ করবেন, অপারেটিং সিস্টেম এই লিস্ট এর **প্রথম ডিরেক্টরিতে** `python` নামের একটি প্রোগ্রাম খুঁজবে। + +যদি এটি খুঁজে পায়, তাহলে এটি প্রোগ্রামটিকে ব্যবহার করবে। অন্যথায় এটি **অন্যান্য ডিরেক্টরিগুলোতে** এটিকে খুঁজতে থাকবে। + +### পাইথন ইনস্টল এবং `PATH` আপডেট + +যখন আপনি পাইথন ইনস্টল করেন, আপনি `PATH` এনভায়রনমেন্ট ভেরিয়েবল আপডেট করতে চান কিনা সেটা জিজ্ঞেস করা হতে পারে। + +//// tab | লিনাক্স, ম্যাকওএস + +ধরা যাক আপনি পাইথন ইনস্টল করলেন এবং এটি `/opt/custompython/bin` ডিরেক্টরিতে ইনস্টল হচ্ছে। + +যদি আপনি "Yes" সিলেক্ট করে `PATH` এনভায়রনমেন্ট ভেরিয়েবল আপডেট করতে চান, তাহলে ইনস্টলার `/opt/custompython/bin` কে `PATH` এনভায়রনমেন্ট ভেরিয়েবল এ এড করে দিবে। + +এটা দেখতে এমনটা হতে পারেঃ + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin +``` + +এইভাবে, আপনি যখন টার্মিনালে `python` টাইপ করেন, সিস্টেম পাইথন প্রোগ্রামটিকে `/opt/custompython/bin` (সর্বশেষ ডিরেক্টরি) তে খুঁজে পাবে এবং এটাকে ব্যবহার করবে। + +//// + +//// tab | উইন্ডোজ + +ধরা যাক আপনি পাইথন ইনস্টল করলেন এবং এটি `C:\opt\custompython\bin` ডিরেক্টরিতে ইনস্টল হচ্ছে। + +যদি আপনি "Yes" সিলেক্ট করে `PATH` এনভায়রনমেন্ট ভেরিয়েবল আপডেট করতে চান, তাহলে ইনস্টলার `C:\opt\custompython\bin` কে `PATH` এনভায়রনমেন্ট ভেরিয়েবল এ এড করে দিবে। + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin +``` + +এইভাবে, আপনি যখন টার্মিনালে `python` টাইপ করেন, সিস্টেম পাইথন প্রোগ্রামটিকে `C:\opt\custompython\bin` (সর্বশেষ ডিরেক্টরি) তে খুঁজে পাবে এবং এটাকে ব্যবহার করবে। + +//// + +তাই, আপনি যদি টাইপ করেনঃ + +
+ +```console +$ python +``` + +
+ +//// tab | লিনাক্স, ম্যাকওএস + +সিস্টেম `python` প্রোগ্রামকে `/opt/custompython/bin` এ **খুঁজে পাবে** এবং এটাকে রান করবে। + +এটা মোটামুটিভাবে নিচের মতো করে লেখার সমান হবেঃ + +
+ +```console +$ /opt/custompython/bin/python +``` + +
+ +//// + +//// tab | উইন্ডোজ + +সিস্টেম `python` প্রোগ্রামকে `C:\opt\custompython\bin\python` এ **খুঁজে পাবে** এবং এটাকে রান করবে। + +এটা মোটামুটিভাবে নিচের মতো করে লেখার সমান হবেঃ + +
+ +```console +$ C:\opt\custompython\bin\python +``` + +
+ +//// + +এই তথ্যগুলো [ভার্চুয়াল এনভায়রনমেন্টস](virtual-environments.md){.internal-link target=_blank} শেখার ক্ষেত্রে সহায়ক হবে। + +## উপসংহার + +এর মাধ্যমে আপনি **এনভায়রনমেন্ট ভেরিয়েবলস** কি এবং এটিকে পাইথনে কিভাবে ব্যবহার করতে হয় তার সম্পর্কে বেসিক ধারনা পেলেন। + +চাইলে এই সম্পর্কে আরো বিস্তারিত পড়তে পারেন Wikipedia for Environment Variable এ। + +অনেক ক্ষেত্রে, দেখা মাত্রই এনভায়রনমেন্ট ভেরিয়েবল কীভাবে প্রয়োজন হবে তা স্পষ্ট হয় না। কিন্তু ডেভেলপমেন্টের সময় আপনি নানা রকম পরিস্থিতিতে এগুলোর সম্মুখীন হবেন, তাই এগুলো সম্পর্কে জেনে রাখা ভালো। + +উদাহরণস্বরূপ, আপনার এই ইনফরমেশনটি পরবর্তী, [ভার্চুয়াল এনভায়রনমেন্টস](virtual-environments.md) অংশে দরকার হবে। diff --git a/docs/bn/docs/index.md b/docs/bn/docs/index.md index 678ac9ca9..74ee230a1 100644 --- a/docs/bn/docs/index.md +++ b/docs/bn/docs/index.md @@ -5,15 +5,18 @@ FastAPI উচ্চক্ষমতা সম্পন্ন, সহজে শেখার এবং দ্রুত কোড করে প্রোডাকশনের জন্য ফ্রামওয়ার্ক।

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

--- diff --git a/docs/de/docs/deployment/concepts.md b/docs/de/docs/deployment/concepts.md index 97ad854e2..907598e54 100644 --- a/docs/de/docs/deployment/concepts.md +++ b/docs/de/docs/deployment/concepts.md @@ -216,7 +216,7 @@ Dieser Manager-Prozess wäre wahrscheinlich derjenige, welcher der IP am **Port* Diese Workerprozesse würden Ihre Anwendung ausführen, sie würden die Hauptberechnungen durchführen, um einen **Request** entgegenzunehmen und eine **Response** zurückzugeben, und sie würden alles, was Sie in Variablen einfügen, in den RAM laden. - + Und natürlich würden auf derselben Maschine neben Ihrer Anwendung wahrscheinlich auch **andere Prozesse** laufen. diff --git a/docs/de/docs/deployment/https.md b/docs/de/docs/deployment/https.md index 630582995..a216f44af 100644 --- a/docs/de/docs/deployment/https.md +++ b/docs/de/docs/deployment/https.md @@ -85,7 +85,7 @@ Zuerst würde der Browser mithilfe der **DNS-Server** herausfinden, welches die Die DNS-Server geben dem Browser eine bestimmte **IP-Adresse** zurück. Das wäre die von Ihrem Server verwendete öffentliche IP-Adresse, die Sie in den DNS-Servern konfiguriert haben. - + ### TLS-Handshake-Start @@ -93,7 +93,7 @@ Der Browser kommuniziert dann mit dieser IP-Adresse über **Port 443** (den HTTP Der erste Teil der Kommunikation besteht lediglich darin, die Verbindung zwischen dem Client und dem Server herzustellen und die zu verwendenden kryptografischen Schlüssel usw. zu vereinbaren. - + Diese Interaktion zwischen dem Client und dem Server zum Aufbau der TLS-Verbindung wird als **TLS-Handshake** bezeichnet. @@ -111,7 +111,7 @@ Mithilfe der oben beschriebenen **SNI-Erweiterung** würde der TLS-Terminierungs In diesem Fall würde er das Zertifikat für `someapp.example.com` verwenden. - + Der Client **vertraut** bereits der Entität, die das TLS-Zertifikat generiert hat (in diesem Fall Let's Encrypt, aber wir werden später mehr darüber erfahren), sodass er **verifizieren** kann, dass das Zertifikat gültig ist. @@ -133,19 +133,19 @@ Da Client und Server (sprich, der Browser und der TLS-Terminierungsproxy) nun ü Der Client sendet also einen **HTTPS-Request**. Das ist einfach ein HTTP-Request über eine verschlüsselte TLS-Verbindung. - + ### Den Request entschlüsseln Der TLS-Terminierungsproxy würde die vereinbarte Verschlüsselung zum **Entschlüsseln des Requests** verwenden und den **einfachen (entschlüsselten) HTTP-Request** an den Prozess weiterleiten, der die Anwendung ausführt (z. B. einen Prozess, bei dem Uvicorn die FastAPI-Anwendung ausführt). - + ### HTTP-Response Die Anwendung würde den Request verarbeiten und eine **einfache (unverschlüsselte) HTTP-Response** an den TLS-Terminierungsproxy senden. - + ### HTTPS-Response @@ -153,7 +153,7 @@ Der TLS-Terminierungsproxy würde dann die Response mithilfe der zuvor vereinbar Als Nächstes überprüft der Browser, ob die Response gültig und mit dem richtigen kryptografischen Schlüssel usw. verschlüsselt ist. Anschließend **entschlüsselt er die Response** und verarbeitet sie. - + Der Client (Browser) weiß, dass die Response vom richtigen Server kommt, da dieser die Kryptografie verwendet, die zuvor mit dem **HTTPS-Zertifikat** vereinbart wurde. @@ -163,7 +163,7 @@ Auf demselben Server (oder denselben Servern) könnten sich **mehrere Anwendunge Nur ein Prozess kann diese spezifische IP und den Port verarbeiten (in unserem Beispiel der TLS-Terminierungsproxy), aber die anderen Anwendungen/Prozesse können auch auf dem/den Server(n) ausgeführt werden, solange sie nicht versuchen, dieselbe **Kombination aus öffentlicher IP und Port** zu verwenden. - + Auf diese Weise könnte der TLS-Terminierungsproxy HTTPS und Zertifikate für **mehrere Domains**, für mehrere Anwendungen, verarbeiten und die Requests dann jeweils an die richtige Anwendung weiterleiten. @@ -173,7 +173,7 @@ Irgendwann in der Zukunft würde jedes Zertifikat **ablaufen** (etwa 3 Monate na Und dann gäbe es ein anderes Programm (in manchen Fällen ist es ein anderes Programm, in manchen Fällen ist es derselbe TLS-Terminierungsproxy), das mit Let's Encrypt kommuniziert und das/die Zertifikat(e) erneuert. - + Die **TLS-Zertifikate** sind **einem Domainnamen zugeordnet**, nicht einer IP-Adresse. diff --git a/docs/de/docs/how-to/custom-docs-ui-assets.md b/docs/de/docs/how-to/custom-docs-ui-assets.md index ab8cd9f6b..f68902b99 100644 --- a/docs/de/docs/how-to/custom-docs-ui-assets.md +++ b/docs/de/docs/how-to/custom-docs-ui-assets.md @@ -98,7 +98,7 @@ Sie können wahrscheinlich mit der rechten Maustaste auf jeden Link klicken und Und **ReDoc** verwendet diese Datei: -* `redoc.standalone.js` +* `redoc.standalone.js` Danach könnte Ihre Dateistruktur wie folgt aussehen: @@ -129,14 +129,8 @@ Sie sollten eine sehr lange JavaScript-Datei für **ReDoc** sehen. Sie könnte beginnen mit etwas wie: ```JavaScript -/*! - * ReDoc - OpenAPI/Swagger-generated API Reference Documentation - * ------------------------------------------------------------- - * Version: "2.0.0-rc.18" - * Repo: https://github.com/Redocly/redoc - */ -!function(e,t){"object"==typeof exports&&"object"==typeof m - +/*! For license information please see redoc.standalone.js.LICENSE.txt */ +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("null")): ... ``` diff --git a/docs/de/docs/index.md b/docs/de/docs/index.md index 411c8e969..d239f0815 100644 --- a/docs/de/docs/index.md +++ b/docs/de/docs/index.md @@ -12,7 +12,7 @@

- Test + Test Coverage diff --git a/docs/de/docs/tutorial/bigger-applications.md b/docs/de/docs/tutorial/bigger-applications.md index 59e91bdcc..514e3fd3a 100644 --- a/docs/de/docs/tutorial/bigger-applications.md +++ b/docs/de/docs/tutorial/bigger-applications.md @@ -52,7 +52,7 @@ from app.routers import items * Es gibt auch ein Unterverzeichnis `app/internal/` mit einer weiteren Datei `__init__.py`, es handelt sich also um ein weiteres „Python-Subpackage“: `app.internal`. * Und die Datei `app/internal/admin.py` ist ein weiteres Submodul: `app.internal.admin`. - + Die gleiche Dateistruktur mit Kommentaren: @@ -270,7 +270,7 @@ Aber diese Datei existiert nicht, unsere Abhängigkeiten befinden sich in einer Erinnern Sie sich, wie unsere Anwendungs-/Dateistruktur aussieht: - + --- diff --git a/docs/de/docs/tutorial/query-params-str-validations.md b/docs/de/docs/tutorial/query-params-str-validations.md index f181d501c..de8879ce8 100644 --- a/docs/de/docs/tutorial/query-params-str-validations.md +++ b/docs/de/docs/tutorial/query-params-str-validations.md @@ -315,22 +315,6 @@ Wenn Sie einen Parameter erforderlich machen wollen, während Sie `Query` verwen {* ../../docs_src/query_params_str_validations/tutorial006_an_py39.py hl[9] *} -### Erforderlich mit Ellipse (`...`) - -Es gibt eine Alternative, die explizit deklariert, dass ein Wert erforderlich ist. Sie können als Default das Literal `...` setzen: - -{* ../../docs_src/query_params_str_validations/tutorial006b_an_py39.py hl[9] *} - -/// info - -Falls Sie das `...` bisher noch nicht gesehen haben: Es ist ein spezieller einzelner Wert, Teil von Python und wird „Ellipsis“ genannt (Deutsch: Ellipse). - -Es wird von Pydantic und FastAPI verwendet, um explizit zu deklarieren, dass ein Wert erforderlich ist. - -/// - -Dies wird **FastAPI** wissen lassen, dass dieser Parameter erforderlich ist. - ### Erforderlich, kann `None` sein Sie können deklarieren, dass ein Parameter `None` akzeptiert, aber dennoch erforderlich ist. Das zwingt Clients, den Wert zu senden, selbst wenn er `None` ist. diff --git a/docs/em/docs/deployment/concepts.md b/docs/em/docs/deployment/concepts.md index 019703296..bbb017277 100644 --- a/docs/em/docs/deployment/concepts.md +++ b/docs/em/docs/deployment/concepts.md @@ -216,7 +216,7 @@ 👈 👨‍🏭 🛠️ 🔜 🕐 🏃‍♂ 👆 🈸, 👫 🔜 🎭 👑 📊 📨 **📨** & 📨 **📨**, & 👫 🔜 📐 🕳 👆 🚮 🔢 💾. - + & ↗️, 🎏 🎰 🔜 🎲 ✔️ **🎏 🛠️** 🏃 👍, ↖️ ⚪️➡️ 👆 🈸. diff --git a/docs/em/docs/deployment/https.md b/docs/em/docs/deployment/https.md index 31cf99001..6d2641a92 100644 --- a/docs/em/docs/deployment/https.md +++ b/docs/em/docs/deployment/https.md @@ -85,7 +85,7 @@ 🏓 💽 🔜 💬 🖥 ⚙️ 🎯 **📢 📢**. 👈 🔜 📢 📢 📢 ⚙️ 👆 💽, 👈 👆 🔗 🏓 💽. - + ### 🤝 🤝 ▶️ @@ -93,7 +93,7 @@ 🥇 🍕 📻 🛠️ 🔗 🖖 👩‍💻 & 💽 & 💭 🔐 🔑 👫 🔜 ⚙️, ♒️. - + 👉 🔗 🖖 👩‍💻 & 💽 🛠️ 🤝 🔗 🤙 **🤝 🤝**. @@ -111,7 +111,7 @@ 👉 💼, ⚫️ 🔜 ⚙️ 📄 `someapp.example.com`. - + 👩‍💻 ⏪ **💙** 👨‍💼 👈 🏗 👈 🤝 📄 (👉 💼 ➡️ 🗜, ✋️ 👥 🔜 👀 🔃 👈 ⏪), ⚫️ 💪 **✔** 👈 📄 ☑. @@ -133,19 +133,19 @@ , 👩‍💻 📨 **🇺🇸🔍 📨**. 👉 🇺🇸🔍 📨 🔘 🗜 🤝 🔗. - + ### 🗜 📨 🤝 ❎ 🗳 🔜 ⚙️ 🔐 ✔ **🗜 📨**, & 🔜 📶 **✅ (🗜) 🇺🇸🔍 📨** 🛠️ 🏃 🈸 (🖼 🛠️ ⏮️ Uvicorn 🏃‍♂ FastAPI 🈸). - + ### 🇺🇸🔍 📨 🈸 🔜 🛠️ 📨 & 📨 **✅ (💽) 🇺🇸🔍 📨** 🤝 ❎ 🗳. - + ### 🇺🇸🔍 📨 @@ -153,7 +153,7 @@ ⏭, 🖥 🔜 ✔ 👈 📨 ☑ & 🗜 ⏮️ ▶️️ 🔐 🔑, ♒️. ⚫️ 🔜 ⤴️ **🗜 📨** & 🛠️ ⚫️. - + 👩‍💻 (🖥) 🔜 💭 👈 📨 👟 ⚪️➡️ ☑ 💽 ↩️ ⚫️ ⚙️ ⚛ 👫 ✔ ⚙️ **🇺🇸🔍 📄** ⏭. @@ -163,7 +163,7 @@ 🕴 1️⃣ 🛠️ 💪 🚚 🎯 📢 & ⛴ (🤝 ❎ 🗳 👆 🖼) ✋️ 🎏 🈸/🛠️ 💪 🏃 🔛 💽(Ⓜ) 💁‍♂️, 📏 👫 🚫 🔄 ⚙️ 🎏 **🌀 📢 📢 & ⛴**. - + 👈 🌌, 🤝 ❎ 🗳 💪 🍵 🇺🇸🔍 & 📄 **💗 🆔**, 💗 🈸, & ⤴️ 📶 📨 ▶️️ 🈸 🔠 💼. @@ -173,7 +173,7 @@ & ⤴️, 📤 🔜 ➕1️⃣ 📋 (💼 ⚫️ ➕1️⃣ 📋, 💼 ⚫️ 💪 🎏 🤝 ❎ 🗳) 👈 🔜 💬 ➡️ 🗜, & ♻ 📄(Ⓜ). - + **🤝 📄** **🔗 ⏮️ 🆔 📛**, 🚫 ⏮️ 📢 📢. diff --git a/docs/em/docs/index.md b/docs/em/docs/index.md index 16b2019d3..57be59b07 100644 --- a/docs/em/docs/index.md +++ b/docs/em/docs/index.md @@ -12,7 +12,7 @@

- Test + Test Coverage diff --git a/docs/em/docs/tutorial/bigger-applications.md b/docs/em/docs/tutorial/bigger-applications.md index 68f506f27..78a321ae6 100644 --- a/docs/em/docs/tutorial/bigger-applications.md +++ b/docs/em/docs/tutorial/bigger-applications.md @@ -52,7 +52,7 @@ from app.routers import items * 📤 📁 `app/internal/` ⏮️ ➕1️⃣ 📁 `__init__.py`, ⚫️ ➕1️⃣ "🐍 📦": `app.internal`. * & 📁 `app/internal/admin.py` ➕1️⃣ 🔁: `app.internal.admin`. - + 🎏 📁 📊 ⏮️ 🏤: @@ -244,7 +244,7 @@ from .dependencies import get_token_header 💭 ❔ 👆 📱/📁 📊 👀 💖: - + --- diff --git a/docs/em/docs/tutorial/query-params-str-validations.md b/docs/em/docs/tutorial/query-params-str-validations.md index dbaab5735..fd077bf8f 100644 --- a/docs/em/docs/tutorial/query-params-str-validations.md +++ b/docs/em/docs/tutorial/query-params-str-validations.md @@ -148,22 +148,6 @@ q: Union[str, None] = Query(default=None, min_length=3) {* ../../docs_src/query_params_str_validations/tutorial006.py hl[7] *} -### ✔ ⏮️ ❕ (`...`) - -📤 🎛 🌌 🎯 📣 👈 💲 ✔. 👆 💪 ⚒ `default` 🔢 🔑 💲 `...`: - -{* ../../docs_src/query_params_str_validations/tutorial006b.py hl[7] *} - -/// info - -🚥 👆 🚫 👀 👈 `...` ⏭: ⚫️ 🎁 👁 💲, ⚫️ 🍕 🐍 & 🤙 "❕". - -⚫️ ⚙️ Pydantic & FastAPI 🎯 📣 👈 💲 ✔. - -/// - -👉 🔜 ➡️ **FastAPI** 💭 👈 👉 🔢 ✔. - ### ✔ ⏮️ `None` 👆 💪 📣 👈 🔢 💪 🚫 `None`, ✋️ 👈 ⚫️ ✔. 👉 🔜 ⚡ 👩‍💻 📨 💲, 🚥 💲 `None`. @@ -178,18 +162,6 @@ Pydantic, ❔ ⚫️❔ 🏋️ 🌐 💽 🔬 & 🛠️ FastAPI, ✔️ /// -### ⚙️ Pydantic `Required` ↩️ ❕ (`...`) - -🚥 👆 💭 😬 ⚙️ `...`, 👆 💪 🗄 & ⚙️ `Required` ⚪️➡️ Pydantic: - -{* ../../docs_src/query_params_str_validations/tutorial006d.py hl[2,8] *} - -/// tip - -💭 👈 🌅 💼, 🕐❔ 🕳 🚚, 👆 💪 🎯 🚫 `default` 🔢, 👆 🛎 🚫 ✔️ ⚙️ `...` 🚫 `Required`. - -/// - ## 🔢 🔢 📇 / 💗 💲 🕐❔ 👆 🔬 🔢 🔢 🎯 ⏮️ `Query` 👆 💪 📣 ⚫️ 📨 📇 💲, ⚖️ 🙆‍♀ 🎏 🌌, 📨 💗 💲. diff --git a/docs/en/data/contributors.yml b/docs/en/data/contributors.yml index 0e1a6505b..f3f7c9133 100644 --- a/docs/en/data/contributors.yml +++ b/docs/en/data/contributors.yml @@ -1,18 +1,23 @@ tiangolo: login: tiangolo - count: 713 + count: 747 avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4 url: https://github.com/tiangolo dependabot: login: dependabot - count: 90 + count: 102 avatarUrl: https://avatars.githubusercontent.com/in/29110?v=4 url: https://github.com/apps/dependabot alejsdev: login: alejsdev count: 47 - avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=356f39ff3f0211c720b06d3dbb060e98884085e3&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=638c65283ac9e9e2c3a0f9d1e3370db4b8a2c58d&v=4 url: https://github.com/alejsdev +pre-commit-ci: + login: pre-commit-ci + count: 30 + avatarUrl: https://avatars.githubusercontent.com/in/68672?v=4 + url: https://github.com/apps/pre-commit-ci github-actions: login: github-actions count: 26 @@ -23,11 +28,6 @@ Kludex: count: 23 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=df8a3f06ba8f55ae1967a3e2d5ed882903a4e330&v=4 url: https://github.com/Kludex -pre-commit-ci: - login: pre-commit-ci - count: 22 - avatarUrl: https://avatars.githubusercontent.com/in/68672?v=4 - url: https://github.com/apps/pre-commit-ci dmontagu: login: dmontagu count: 17 @@ -68,6 +68,11 @@ vishnuvskvkl: count: 8 avatarUrl: https://avatars.githubusercontent.com/u/84698110?u=8af5de0520dd4fa195f53c2850a26f57c0f6bc64&v=4 url: https://github.com/vishnuvskvkl +svlandeg: + login: svlandeg + count: 7 + avatarUrl: https://avatars.githubusercontent.com/u/8796347?u=556c97650c27021911b0b9447ec55e75987b0e8a&v=4 + url: https://github.com/svlandeg alissadb: login: alissadb count: 6 @@ -88,16 +93,16 @@ waynerv: count: 5 avatarUrl: https://avatars.githubusercontent.com/u/39515546?u=ec35139777597cdbbbddda29bf8b9d4396b429a9&v=4 url: https://github.com/waynerv -svlandeg: - login: svlandeg - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/8796347?u=556c97650c27021911b0b9447ec55e75987b0e8a&v=4 - url: https://github.com/svlandeg krishnamadhavan: login: krishnamadhavan count: 5 avatarUrl: https://avatars.githubusercontent.com/u/31798870?u=950693b28f3ae01105fd545c046e46ca3d31ab06&v=4 url: https://github.com/krishnamadhavan +alv2017: + login: alv2017 + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 + url: https://github.com/alv2017 jekirl: login: jekirl count: 4 @@ -121,7 +126,7 @@ adriangb: iudeen: login: iudeen count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=f09cdd745e5bf16138f29b42732dd57c7f02bee1&v=4 url: https://github.com/iudeen philipokiokio: login: philipokiokio @@ -166,7 +171,7 @@ hukkin: marcosmmb: login: marcosmmb count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/6181089?u=b8567a842b38c5570c315b2b7ca766fa7be6721e&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/6181089?u=03c50eec631857d84df5232890780d00a3f76903&v=4 url: https://github.com/marcosmmb Serrones: login: Serrones @@ -178,11 +183,11 @@ uriyyo: count: 3 avatarUrl: https://avatars.githubusercontent.com/u/32038156?u=a27b65a9ec3420586a827a0facccbb8b6df1ffb3&v=4 url: https://github.com/uriyyo -amacfie: - login: amacfie +andrew222651: + login: andrew222651 count: 3 avatarUrl: https://avatars.githubusercontent.com/u/889657?u=d70187989940b085bcbfa3bedad8dbc5f3ab1fe7&v=4 - url: https://github.com/amacfie + url: https://github.com/andrew222651 rkbeatss: login: rkbeatss count: 3 @@ -211,7 +216,7 @@ TeoZosa: graingert: login: graingert count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/413772?u=64b77b6aa405c68a9c6bcf45f84257c66eea5f32&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/413772?v=4 url: https://github.com/graingert jaystone776: login: jaystone776 @@ -233,6 +238,11 @@ papb: count: 3 avatarUrl: https://avatars.githubusercontent.com/u/20914054?u=890511fae7ea90d887e2a65ce44a1775abba38d5&v=4 url: https://github.com/papb +musicinmybrain: + login: musicinmybrain + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/6898909?u=9010312053e7141383b9bdf538036c7f37fbaba0&v=4 + url: https://github.com/musicinmybrain gitworkflows: login: gitworkflows count: 3 @@ -301,7 +311,7 @@ dconathan: Jamim: login: Jamim count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/5607572?u=0cf3027bec78ba4f0b89802430c136bc69847d7a&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/5607572?u=9ce0b6a6d1a5124e28b3c04d8d26827ca328713a&v=4 url: https://github.com/Jamim svalouch: login: svalouch @@ -356,7 +366,7 @@ sattosan: michaeloliverx: login: michaeloliverx count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/55017335?u=e606eb5cc397c07523be47637b1ee796904fbb59&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/55017335?u=efb0cb6e261ff64d862fafb91ee80fc2e1f8a2ed&v=4 url: https://github.com/michaeloliverx voegtlel: login: voegtlel @@ -468,11 +478,6 @@ yezz123: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/52716203?u=d7062cbc6eb7671d5dc9cc0e32a24ae335e0f225&v=4 url: https://github.com/yezz123 -musicinmybrain: - login: musicinmybrain - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/6898909?u=9010312053e7141383b9bdf538036c7f37fbaba0&v=4 - url: https://github.com/musicinmybrain softwarebloat: login: softwarebloat count: 2 @@ -483,6 +488,11 @@ Lancetnik: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/44573917?u=f9a18be7324333daf9cc314c35c3051f0a20a7a6&v=4 url: https://github.com/Lancetnik +joakimnordling: + login: joakimnordling + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/6637576?u=df5d99db9b899b399effd429f4358baaa6f7199c&v=4 + url: https://github.com/joakimnordling yogabonito: login: yogabonito count: 2 @@ -513,8 +523,23 @@ AyushSinghal1794: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/89984761?v=4 url: https://github.com/AyushSinghal1794 +gsheni: + login: gsheni + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/8726321?u=ee3bd9ff6320f4715d1dd9671a3d55cccb65b984&v=4 + url: https://github.com/gsheni DanielKusyDev: login: DanielKusyDev count: 2 avatarUrl: https://avatars.githubusercontent.com/u/36250676?u=2ea6114ff751fc48b55f231987a0e2582c6b1bd2&v=4 url: https://github.com/DanielKusyDev +DanielYang59: + login: DanielYang59 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/80093591?u=63873f701c7c74aac83c906800a1dddc0bc8c92f&v=4 + url: https://github.com/DanielYang59 +blueswen: + login: blueswen + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1564148?u=6d6b8cc8f2b5cef715e68d6175154a8a94d518ee&v=4 + url: https://github.com/blueswen diff --git a/docs/en/data/external_links.yml b/docs/en/data/external_links.yml index 9e411a631..50f84ecbf 100644 --- a/docs/en/data/external_links.yml +++ b/docs/en/data/external_links.yml @@ -411,3 +411,8 @@ Talks: author_link: https://twitter.com/chriswithers13 link: https://www.youtube.com/watch?v=3DLwPcrE5mA title: 'PyCon UK 2019: FastAPI from the ground up' + Taiwanese: + - author: Blueswen + author_link: https://github.com/blueswen + link: https://www.youtube.com/watch?v=y3sumuoDq4w + title: 'PyCon TW 2024: 全方位強化 Python 服務可觀測性:以 FastAPI 和 Grafana Stack 為例' diff --git a/docs/en/data/github_sponsors.yml b/docs/en/data/github_sponsors.yml index feb4e727f..efc5cbfcc 100644 --- a/docs/en/data/github_sponsors.yml +++ b/docs/en/data/github_sponsors.yml @@ -1,28 +1,25 @@ sponsors: -- - login: bump-sh - avatarUrl: https://avatars.githubusercontent.com/u/33217836?v=4 - url: https://github.com/bump-sh - - login: renderinc +- - login: renderinc avatarUrl: https://avatars.githubusercontent.com/u/36424661?v=4 url: https://github.com/renderinc - login: Nixtla avatarUrl: https://avatars.githubusercontent.com/u/79945230?v=4 url: https://github.com/Nixtla - login: andrew-propelauth - avatarUrl: https://avatars.githubusercontent.com/u/89474256?u=1188c27cb744bbec36447a2cfd4453126b2ddb5c&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/89474256?u=c98993dec8553c09d424ede67bbe86e5c35f48c9&v=4 url: https://github.com/andrew-propelauth - - login: liblaber - avatarUrl: https://avatars.githubusercontent.com/u/100821118?v=4 - url: https://github.com/liblaber - - login: zanfaruqui - avatarUrl: https://avatars.githubusercontent.com/u/104461687?v=4 - url: https://github.com/zanfaruqui - login: blockbee-io avatarUrl: https://avatars.githubusercontent.com/u/115143449?u=1b8620c2d6567c4df2111a371b85a51f448f9b85&v=4 url: https://github.com/blockbee-io - login: zuplo avatarUrl: https://avatars.githubusercontent.com/u/85497839?v=4 url: https://github.com/zuplo + - login: coderabbitai + avatarUrl: https://avatars.githubusercontent.com/u/132028505?v=4 + url: https://github.com/coderabbitai + - login: subtotal + avatarUrl: https://avatars.githubusercontent.com/u/176449348?v=4 + url: https://github.com/subtotal - login: porter-dev avatarUrl: https://avatars.githubusercontent.com/u/62078005?v=4 url: https://github.com/porter-dev @@ -32,7 +29,10 @@ sponsors: - - login: ObliviousAI avatarUrl: https://avatars.githubusercontent.com/u/65656077?v=4 url: https://github.com/ObliviousAI -- - login: svix +- - login: dribia + avatarUrl: https://avatars.githubusercontent.com/u/41189616?v=4 + url: https://github.com/dribia + - login: svix avatarUrl: https://avatars.githubusercontent.com/u/80175132?v=4 url: https://github.com/svix - login: stainless-api @@ -41,6 +41,9 @@ sponsors: - login: speakeasy-api avatarUrl: https://avatars.githubusercontent.com/u/91446104?v=4 url: https://github.com/speakeasy-api + - login: snapit-cypher + avatarUrl: https://avatars.githubusercontent.com/u/115662654?v=4 + url: https://github.com/snapit-cypher - login: databento avatarUrl: https://avatars.githubusercontent.com/u/64141749?v=4 url: https://github.com/databento @@ -59,6 +62,9 @@ sponsors: - login: Ponte-Energy-Partners avatarUrl: https://avatars.githubusercontent.com/u/114745848?v=4 url: https://github.com/Ponte-Energy-Partners + - login: LambdaTest-Inc + avatarUrl: https://avatars.githubusercontent.com/u/171592363?u=96606606a45fa170427206199014f2a5a2a4920b&v=4 + url: https://github.com/LambdaTest-Inc - login: BoostryJP avatarUrl: https://avatars.githubusercontent.com/u/57932412?v=4 url: https://github.com/BoostryJP @@ -71,68 +77,44 @@ sponsors: - - login: takashi-yoneya avatarUrl: https://avatars.githubusercontent.com/u/33813153?u=2d0522bceba0b8b69adf1f2db866503bd96f944e&v=4 url: https://github.com/takashi-yoneya + - login: Doist + avatarUrl: https://avatars.githubusercontent.com/u/2565372?v=4 + url: https://github.com/Doist - - login: mainframeindustries avatarUrl: https://avatars.githubusercontent.com/u/55092103?v=4 url: https://github.com/mainframeindustries - - login: CanoaPBC - avatarUrl: https://avatars.githubusercontent.com/u/64223768?v=4 - url: https://github.com/CanoaPBC - login: yasyf avatarUrl: https://avatars.githubusercontent.com/u/709645?u=f36736b3c6a85f578886ecc42a740e7b436e7a01&v=4 url: https://github.com/yasyf -- - login: genzou9201 - avatarUrl: https://avatars.githubusercontent.com/u/42960762?u=1ca6c18c59e8b327ae584c545b72de31ebc05275&v=4 - url: https://github.com/genzou9201 +- - login: alixlahuec + avatarUrl: https://avatars.githubusercontent.com/u/29543316?u=44357eb2a93bccf30fb9d389b8befe94a3d00985&v=4 + url: https://github.com/alixlahuec - - login: primer-io avatarUrl: https://avatars.githubusercontent.com/u/62146168?v=4 url: https://github.com/primer-io - - login: povilasb - avatarUrl: https://avatars.githubusercontent.com/u/1213442?u=b11f58ed6ceea6e8297c9b310030478ebdac894d&v=4 - url: https://github.com/povilasb - - login: upciti avatarUrl: https://avatars.githubusercontent.com/u/43346262?v=4 url: https://github.com/upciti - - login: freddiev4 - avatarUrl: https://avatars.githubusercontent.com/u/8339018?u=1aad5b4f5a04cb750852b843d5e1d8f4ce339c2e&v=4 - url: https://github.com/freddiev4 - - login: samuelcolvin avatarUrl: https://avatars.githubusercontent.com/u/4039449?u=42eb3b833047c8c4b4f647a031eaef148c16d93f&v=4 url: https://github.com/samuelcolvin - - login: ProteinQure - avatarUrl: https://avatars.githubusercontent.com/u/33707203?v=4 - url: https://github.com/ProteinQure - - login: ddilidili - avatarUrl: https://avatars.githubusercontent.com/u/42176885?u=c0a849dde06987434653197b5f638d3deb55fc6c&v=4 - url: https://github.com/ddilidili - login: otosky avatarUrl: https://avatars.githubusercontent.com/u/42260747?u=69d089387c743d89427aa4ad8740cfb34045a9e0&v=4 url: https://github.com/otosky - - login: khadrawy - avatarUrl: https://avatars.githubusercontent.com/u/13686061?u=59f25ef42ecf04c22657aac4238ce0e2d3d30304&v=4 - url: https://github.com/khadrawy - - login: mjohnsey - avatarUrl: https://avatars.githubusercontent.com/u/16784016?u=38fad2e6b411244560b3af99c5f5a4751bc81865&v=4 - url: https://github.com/mjohnsey + - login: ramonalmeidam + avatarUrl: https://avatars.githubusercontent.com/u/45269580?u=3358750b3a5854d7c3ed77aaca7dd20a0f529d32&v=4 + url: https://github.com/ramonalmeidam - login: ashi-agrawal avatarUrl: https://avatars.githubusercontent.com/u/17105294?u=99c7a854035e5398d8e7b674f2d42baae6c957f8&v=4 url: https://github.com/ashi-agrawal - - login: sepsi77 - avatarUrl: https://avatars.githubusercontent.com/u/18682303?v=4 - url: https://github.com/sepsi77 - login: RaamEEIL avatarUrl: https://avatars.githubusercontent.com/u/20320552?v=4 url: https://github.com/RaamEEIL - - login: jhundman - avatarUrl: https://avatars.githubusercontent.com/u/24263908?v=4 - url: https://github.com/jhundman - - login: b-rad-c - avatarUrl: https://avatars.githubusercontent.com/u/25362581?u=5bb10629f4015b62bec1f9a366675d5085551af9&v=4 - url: https://github.com/b-rad-c - login: ehaca avatarUrl: https://avatars.githubusercontent.com/u/25950317?u=cec1a3e0643b785288ae8260cc295a85ab344995&v=4 url: https://github.com/ehaca - login: raphaellaude - avatarUrl: https://avatars.githubusercontent.com/u/28026311?u=28faad3e62250ef91a0c3c5d0faba39592d9ab39&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/28026311?u=91e1c00d9ac4f8045527e13de8050d504531cbc0&v=4 url: https://github.com/raphaellaude - login: timlrx avatarUrl: https://avatars.githubusercontent.com/u/28362229?u=9a745ca31372ee324af682715ae88ce8522f9094&v=4 @@ -140,12 +122,9 @@ sponsors: - login: Leay15 avatarUrl: https://avatars.githubusercontent.com/u/32212558?u=c4aa9c1737e515959382a5515381757b1fd86c53&v=4 url: https://github.com/Leay15 - - login: ygorpontelo - avatarUrl: https://avatars.githubusercontent.com/u/32963605?u=35f7103f9c4c4c2589ae5737ee882e9375ef072e&v=4 - url: https://github.com/ygorpontelo - - login: chickenandstats - avatarUrl: https://avatars.githubusercontent.com/u/79477966?v=4 - url: https://github.com/chickenandstats + - login: ProteinQure + avatarUrl: https://avatars.githubusercontent.com/u/33707203?v=4 + url: https://github.com/ProteinQure - login: kaoru0310 avatarUrl: https://avatars.githubusercontent.com/u/80977929?u=1b61d10142b490e56af932ddf08a390fae8ee94f&v=4 url: https://github.com/kaoru0310 @@ -164,12 +143,6 @@ sponsors: - login: logic-automation avatarUrl: https://avatars.githubusercontent.com/u/144732884?v=4 url: https://github.com/logic-automation - - login: Torqsight-Labs - avatarUrl: https://avatars.githubusercontent.com/u/169598176?v=4 - url: https://github.com/Torqsight-Labs - - login: ramonalmeidam - avatarUrl: https://avatars.githubusercontent.com/u/45269580?u=3358750b3a5854d7c3ed77aaca7dd20a0f529d32&v=4 - url: https://github.com/ramonalmeidam - login: roboflow avatarUrl: https://avatars.githubusercontent.com/u/53104118?v=4 url: https://github.com/roboflow @@ -185,12 +158,9 @@ sponsors: - login: patricioperezv avatarUrl: https://avatars.githubusercontent.com/u/73832292?u=5f471f156e19ee7920e62ae0f4a47b95580e61cf&v=4 url: https://github.com/patricioperezv - - 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: chickenandstats + avatarUrl: https://avatars.githubusercontent.com/u/79477966?u=ae2b894aa954070db1d7830dab99b49eba4e4567&v=4 + url: https://github.com/chickenandstats - login: dodo5522 avatarUrl: https://avatars.githubusercontent.com/u/1362607?u=9bf1e0e520cccc547c046610c468ce6115bbcf9f&v=4 url: https://github.com/dodo5522 @@ -200,9 +170,6 @@ sponsors: - login: knallgelb avatarUrl: https://avatars.githubusercontent.com/u/2358812?u=c48cb6362b309d74cbf144bd6ad3aed3eb443e82&v=4 url: https://github.com/knallgelb - - login: Shark009 - avatarUrl: https://avatars.githubusercontent.com/u/3163309?u=0c6f4091b0eda05c44c390466199826e6dc6e431&v=4 - url: https://github.com/Shark009 - login: dblackrun avatarUrl: https://avatars.githubusercontent.com/u/3528486?v=4 url: https://github.com/dblackrun @@ -218,6 +185,15 @@ sponsors: - login: anomaly avatarUrl: https://avatars.githubusercontent.com/u/3654837?v=4 url: https://github.com/anomaly + - login: mj0331 + avatarUrl: https://avatars.githubusercontent.com/u/3890353?u=1c627ac1a024515b4871de5c3ebbfaa1a57f65d4&v=4 + url: https://github.com/mj0331 + - login: gorhack + avatarUrl: https://avatars.githubusercontent.com/u/4141690?u=ec119ebc4bdf00a7bc84657a71aa17834f4f27f3&v=4 + url: https://github.com/gorhack + - login: Ryandaydev + avatarUrl: https://avatars.githubusercontent.com/u/4292423?u=679ff84cb7b988c5795a5fa583857f574a055763&v=4 + url: https://github.com/Ryandaydev - login: vincentkoc avatarUrl: https://avatars.githubusercontent.com/u/25068?u=fbd5b2d51142daa4bdbc21e21953a3b8b8188a4a&v=4 url: https://github.com/vincentkoc @@ -242,21 +218,18 @@ sponsors: - login: wshayes avatarUrl: https://avatars.githubusercontent.com/u/365303?u=07ca03c5ee811eb0920e633cc3c3db73dbec1aa5&v=4 url: https://github.com/wshayes - - login: gaetanBloch - avatarUrl: https://avatars.githubusercontent.com/u/583199?u=50c49e83d6b4feb78a091901ea02ead1462f442b&v=4 - url: https://github.com/gaetanBloch - login: koxudaxi avatarUrl: https://avatars.githubusercontent.com/u/630670?u=507d8577b4b3670546b449c4c2ccbc5af40d72f7&v=4 url: https://github.com/koxudaxi - login: falkben avatarUrl: https://avatars.githubusercontent.com/u/653031?u=ad9838e089058c9e5a0bab94c0eec7cc181e0cd0&v=4 url: https://github.com/falkben + - login: mintuhouse + avatarUrl: https://avatars.githubusercontent.com/u/769950?u=ecfbd79a97d33177e0d093ddb088283cf7fe8444&v=4 + url: https://github.com/mintuhouse - login: TrevorBenson avatarUrl: https://avatars.githubusercontent.com/u/9167887?u=dccbea3327a57750923333d8ebf1a0b3f1948949&v=4 url: https://github.com/TrevorBenson - - login: kaangiray26 - avatarUrl: https://avatars.githubusercontent.com/u/11297495?u=e85327a77db45906d44f3ff06dd7f3303c644096&v=4 - url: https://github.com/kaangiray26 - login: wdwinslow avatarUrl: https://avatars.githubusercontent.com/u/11562137?u=dc01daafb354135603a263729e3d26d939c0c452&v=4 url: https://github.com/wdwinslow @@ -272,21 +245,18 @@ sponsors: - login: dannywade avatarUrl: https://avatars.githubusercontent.com/u/13680237?u=418ee985bd41577b20fde81417fb2d901e875e8a&v=4 url: https://github.com/dannywade - - login: gorhack - avatarUrl: https://avatars.githubusercontent.com/u/4141690?u=ec119ebc4bdf00a7bc84657a71aa17834f4f27f3&v=4 - url: https://github.com/gorhack - - login: Ryandaydev - avatarUrl: https://avatars.githubusercontent.com/u/4292423?u=48f68868db8886fce31a1d802c1003914c6cd7c6&v=4 - url: https://github.com/Ryandaydev + - login: khadrawy + avatarUrl: https://avatars.githubusercontent.com/u/13686061?u=59f25ef42ecf04c22657aac4238ce0e2d3d30304&v=4 + url: https://github.com/khadrawy + - login: mjohnsey + avatarUrl: https://avatars.githubusercontent.com/u/16784016?u=38fad2e6b411244560b3af99c5f5a4751bc81865&v=4 + url: https://github.com/mjohnsey - login: jaredtrog avatarUrl: https://avatars.githubusercontent.com/u/4381365?v=4 url: https://github.com/jaredtrog - login: oliverxchen avatarUrl: https://avatars.githubusercontent.com/u/4471774?u=534191f25e32eeaadda22dfab4b0a428733d5489&v=4 url: https://github.com/oliverxchen - - login: ennui93 - avatarUrl: https://avatars.githubusercontent.com/u/5300907?u=5b5452725ddb391b2caaebf34e05aba873591c3a&v=4 - url: https://github.com/ennui93 - login: ternaus avatarUrl: https://avatars.githubusercontent.com/u/5481618?u=513a26b02a39e7a28d587cd37c6cc877ea368e6e&v=4 url: https://github.com/ternaus @@ -294,23 +264,20 @@ sponsors: avatarUrl: https://avatars.githubusercontent.com/u/5920492?u=208d419cf667b8ac594c82a8db01932c7e50d057&v=4 url: https://github.com/eseglem - login: FernandoCelmer - avatarUrl: https://avatars.githubusercontent.com/u/6262214?u=d29fff3fd862fda4ca752079f13f32e84c762ea4&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/6262214?u=58ba6d5888fa7f355934e52db19f950e20b38162&v=4 url: https://github.com/FernandoCelmer - - login: simw - avatarUrl: https://avatars.githubusercontent.com/u/6322526?v=4 - url: https://github.com/simw - login: Rehket avatarUrl: https://avatars.githubusercontent.com/u/7015688?u=3afb0ba200feebbc7f958950e92db34df2a3c172&v=4 url: https://github.com/Rehket - login: hiancdtrsnm avatarUrl: https://avatars.githubusercontent.com/u/7343177?v=4 url: https://github.com/hiancdtrsnm +- - login: jpizquierdo + avatarUrl: https://avatars.githubusercontent.com/u/6716239?v=4 + url: https://github.com/jpizquierdo - - login: pawamoy avatarUrl: https://avatars.githubusercontent.com/u/3999221?u=b030e4c89df2f3a36bc4710b925bdeb6745c9856&v=4 url: https://github.com/pawamoy - - login: engineerjoe440 - avatarUrl: https://avatars.githubusercontent.com/u/33275230?u=eb223cad27017bb1e936ee9b429b450d092d0236&v=4 - url: https://github.com/engineerjoe440 - login: bnkc avatarUrl: https://avatars.githubusercontent.com/u/34930566?u=db5e6f4f87836cad26c2aa90ce390ce49041c5a9&v=4 url: https://github.com/bnkc @@ -323,12 +290,18 @@ sponsors: - login: mobyw avatarUrl: https://avatars.githubusercontent.com/u/44370805?v=4 url: https://github.com/mobyw - - login: PelicanQ - avatarUrl: https://avatars.githubusercontent.com/u/77930606?v=4 - url: https://github.com/PelicanQ - - login: TheR1D - avatarUrl: https://avatars.githubusercontent.com/u/16740832?u=b0dfdbdb27b79729430c71c6128962f77b7b53f7&v=4 - url: https://github.com/TheR1D + - login: ArtyomVancyan + avatarUrl: https://avatars.githubusercontent.com/u/44609997?v=4 + url: https://github.com/ArtyomVancyan + - login: caviri + avatarUrl: https://avatars.githubusercontent.com/u/45425937?u=4e14bd64282bad8f385eafbdb004b5a279366d6e&v=4 + url: https://github.com/caviri + - login: hgalytoby + avatarUrl: https://avatars.githubusercontent.com/u/50397689?u=62c7ff3519858423579676cd0efbd7e3f1ffe63a&v=4 + url: https://github.com/hgalytoby + - login: browniebroke + avatarUrl: https://avatars.githubusercontent.com/u/861044?u=5abfca5588f3e906b31583d7ee62f6de4b68aa24&v=4 + url: https://github.com/browniebroke - login: joshuatz avatarUrl: https://avatars.githubusercontent.com/u/17817563?u=f1bf05b690d1fc164218f0b420cdd3acb7913e21&v=4 url: https://github.com/joshuatz @@ -347,18 +320,12 @@ sponsors: - login: rlnchow avatarUrl: https://avatars.githubusercontent.com/u/28018479?u=a93ca9cf1422b9ece155784a72d5f2fdbce7adff&v=4 url: https://github.com/rlnchow - - login: dvlpjrs - avatarUrl: https://avatars.githubusercontent.com/u/32254642?u=fbd6ad0324d4f1eb6231cf775be1c7bd4404e961&v=4 - url: https://github.com/dvlpjrs - - login: ArtyomVancyan - avatarUrl: https://avatars.githubusercontent.com/u/44609997?v=4 - url: https://github.com/ArtyomVancyan - - login: caviri - avatarUrl: https://avatars.githubusercontent.com/u/45425937?u=4e14bd64282bad8f385eafbdb004b5a279366d6e&v=4 - url: https://github.com/caviri - - login: hgalytoby - avatarUrl: https://avatars.githubusercontent.com/u/50397689?u=62c7ff3519858423579676cd0efbd7e3f1ffe63a&v=4 - url: https://github.com/hgalytoby + - login: engineerjoe440 + avatarUrl: https://avatars.githubusercontent.com/u/33275230?u=eb223cad27017bb1e936ee9b429b450d092d0236&v=4 + url: https://github.com/engineerjoe440 + - login: lukzmu + avatarUrl: https://avatars.githubusercontent.com/u/175964415?u=83ea9b0b7b7b0f15bcb5747d93f303447a19a00b&v=4 + url: https://github.com/lukzmu - login: conservative-dude avatarUrl: https://avatars.githubusercontent.com/u/55538308?u=f250c44942ea6e73a6bd90739b381c470c192c11&v=4 url: https://github.com/conservative-dude @@ -368,17 +335,14 @@ sponsors: - login: PunRabbit avatarUrl: https://avatars.githubusercontent.com/u/70463212?u=1a835cfbc99295a60c8282f6aa6199d1b42241a5&v=4 url: https://github.com/PunRabbit - - login: tochikuji - avatarUrl: https://avatars.githubusercontent.com/u/851759?v=4 - url: https://github.com/tochikuji - - login: browniebroke - avatarUrl: https://avatars.githubusercontent.com/u/861044?u=5abfca5588f3e906b31583d7ee62f6de4b68aa24&v=4 - url: https://github.com/browniebroke + - login: PelicanQ + avatarUrl: https://avatars.githubusercontent.com/u/77930606?v=4 + url: https://github.com/PelicanQ - 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 + avatarUrl: https://avatars.githubusercontent.com/u/1661551?u=8a80356e3e7d5a417157aba7ea565dabc8678327&v=4 url: https://github.com/WillHogan - login: my3 avatarUrl: https://avatars.githubusercontent.com/u/1825270?v=4 @@ -389,9 +353,6 @@ sponsors: - login: Alisa-lisa avatarUrl: https://avatars.githubusercontent.com/u/4137964?u=e7e393504f554f4ff15863a1e01a5746863ef9ce&v=4 url: https://github.com/Alisa-lisa - - login: hcristea - avatarUrl: https://avatars.githubusercontent.com/u/7814406?u=61d7a4fcf846983a4606788eac25e1c6c1209ba8&v=4 - url: https://github.com/hcristea - login: ddanier avatarUrl: https://avatars.githubusercontent.com/u/113563?u=ed1dc79de72f93bd78581f88ebc6952b62f472da&v=4 url: https://github.com/ddanier @@ -404,12 +365,9 @@ sponsors: - login: ceb10n avatarUrl: https://avatars.githubusercontent.com/u/235213?u=edcce471814a1eba9f0cdaa4cd0de18921a940a6&v=4 url: https://github.com/ceb10n - - login: eteq - avatarUrl: https://avatars.githubusercontent.com/u/346587?v=4 - url: https://github.com/eteq - - login: securancy - avatarUrl: https://avatars.githubusercontent.com/u/606673?v=4 - url: https://github.com/securancy + - login: tochikuji + avatarUrl: https://avatars.githubusercontent.com/u/851759?v=4 + url: https://github.com/tochikuji - login: moonape1226 avatarUrl: https://avatars.githubusercontent.com/u/8532038?u=d9f8b855a429fff9397c3833c2ff83849ebf989d&v=4 url: https://github.com/moonape1226 @@ -420,7 +378,7 @@ sponsors: avatarUrl: https://avatars.githubusercontent.com/u/9462045?u=a80a7bb349555b277645632ed66639ff43400614&v=4 url: https://github.com/xncbf - login: DMantis - avatarUrl: https://avatars.githubusercontent.com/u/9536869?v=4 + avatarUrl: https://avatars.githubusercontent.com/u/9536869?u=652dd0d49717803c0cbcbf44f7740e53cf2d4892&v=4 url: https://github.com/DMantis - login: hard-coders avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=95db33927bbff1ed1c07efddeb97ac2ff33068ed&v=4 @@ -434,18 +392,15 @@ 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: Zuzah avatarUrl: https://avatars.githubusercontent.com/u/10934846?u=1ef43e075ddc87bd1178372bf4d95ee6175cae27&v=4 url: https://github.com/Zuzah - login: artempronevskiy avatarUrl: https://avatars.githubusercontent.com/u/12235104?u=03df6e1e55c9c6fe5d230adabb8dd7d43d8bbe8f&v=4 url: https://github.com/artempronevskiy - - login: Graeme22 - avatarUrl: https://avatars.githubusercontent.com/u/4185684?u=498182a42300d7bcd4de1215190cb17eb501136c&v=4 - url: https://github.com/Graeme22 + - login: TheR1D + avatarUrl: https://avatars.githubusercontent.com/u/16740832?u=b0dfdbdb27b79729430c71c6128962f77b7b53f7&v=4 + url: https://github.com/TheR1D - login: danielunderwood avatarUrl: https://avatars.githubusercontent.com/u/4472301?v=4 url: https://github.com/danielunderwood @@ -470,36 +425,36 @@ sponsors: - login: harsh183 avatarUrl: https://avatars.githubusercontent.com/u/7780198?v=4 url: https://github.com/harsh183 -- - login: larsyngvelundin - avatarUrl: https://avatars.githubusercontent.com/u/34173819?u=74958599695bf83ac9f1addd935a51548a10c6b0&v=4 - url: https://github.com/larsyngvelundin - - login: andrecorumba + - login: hcristea + avatarUrl: https://avatars.githubusercontent.com/u/7814406?u=19092923a4ea5b338567961c8270b9206a6d81bb&v=4 + url: https://github.com/hcristea +- - login: andrecorumba avatarUrl: https://avatars.githubusercontent.com/u/37807517?u=9b9be3b41da9bda60957da9ef37b50dbf65baa61&v=4 url: https://github.com/andrecorumba - login: rwxd avatarUrl: https://avatars.githubusercontent.com/u/40308458?u=cd04a39e3655923be4f25c2ba8a5a07b3da3230a&v=4 url: https://github.com/rwxd + - login: morzan1001 + avatarUrl: https://avatars.githubusercontent.com/u/47593005?u=c30ab7230f82a12a9b938dcb54f84a996931409a&v=4 + url: https://github.com/morzan1001 - login: sadikkuzu avatarUrl: https://avatars.githubusercontent.com/u/23168063?u=d179c06bb9f65c4167fcab118526819f8e0dac17&v=4 url: https://github.com/sadikkuzu - login: Olegt0rr avatarUrl: https://avatars.githubusercontent.com/u/25399456?u=3e87b5239a2f4600975ba13be73054f8567c6060&v=4 url: https://github.com/Olegt0rr - - login: FabulousCodingFox - avatarUrl: https://avatars.githubusercontent.com/u/78906517?u=924a27cbee3db7e0ece5cc1509921402e1445e74&v=4 - url: https://github.com/FabulousCodingFox - - login: gateremark - avatarUrl: https://avatars.githubusercontent.com/u/91592218?u=969314eb2cfb035196f4d19499ec6f5050d7583a&v=4 - url: https://github.com/gateremark - - login: morzan1001 - avatarUrl: https://avatars.githubusercontent.com/u/47593005?u=c30ab7230f82a12a9b938dcb54f84a996931409a&v=4 - url: https://github.com/morzan1001 + - login: larsyngvelundin + avatarUrl: https://avatars.githubusercontent.com/u/34173819?u=74958599695bf83ac9f1addd935a51548a10c6b0&v=4 + url: https://github.com/larsyngvelundin + - login: one-st-one + avatarUrl: https://avatars.githubusercontent.com/u/62360849?u=746dd21c34e7e06eefb11b03e8bb01aaae3c2a4f&v=4 + url: https://github.com/one-st-one + - login: federicsp + avatarUrl: https://avatars.githubusercontent.com/u/62903636?u=05004f4a2c590f1d18c200e17978bf2e17acb632&v=4 + url: https://github.com/federicsp - login: Toothwitch avatarUrl: https://avatars.githubusercontent.com/u/1710406?u=5eebb23b46cd26e48643b9e5179536cad491c17a&v=4 url: https://github.com/Toothwitch - - login: ssbarnea - avatarUrl: https://avatars.githubusercontent.com/u/102495?u=c7bd9ddf127785286fc939dd18cb02db0a453bce&v=4 - url: https://github.com/ssbarnea - login: andreagrandi avatarUrl: https://avatars.githubusercontent.com/u/636391?u=13d90cb8ec313593a5b71fbd4e33b78d6da736f5&v=4 url: https://github.com/andreagrandi diff --git a/docs/en/data/members.yml b/docs/en/data/members.yml index cf016eae1..7ec16e917 100644 --- a/docs/en/data/members.yml +++ b/docs/en/data/members.yml @@ -17,3 +17,6 @@ members: - login: patrick91 avatar_url: https://avatars.githubusercontent.com/u/667029 url: https://github.com/patrick91 +- login: luzzodev + avatar_url: https://avatars.githubusercontent.com/u/27291415 + url: https://github.com/luzzodev diff --git a/docs/en/data/people.yml b/docs/en/data/people.yml index 7f910ab34..a94c7c63c 100644 --- a/docs/en/data/people.yml +++ b/docs/en/data/people.yml @@ -1,11 +1,11 @@ maintainers: - login: tiangolo - answers: 1894 + answers: 1898 avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4 url: https://github.com/tiangolo experts: - login: tiangolo - count: 1894 + count: 1898 avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4 url: https://github.com/tiangolo - login: github-actions @@ -13,28 +13,28 @@ experts: avatarUrl: https://avatars.githubusercontent.com/in/15368?v=4 url: https://github.com/apps/github-actions - login: Kludex - count: 645 + count: 655 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=df8a3f06ba8f55ae1967a3e2d5ed882903a4e330&v=4 url: https://github.com/Kludex - login: jgould22 - count: 250 + count: 263 avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 url: https://github.com/jgould22 +- login: YuriiMotov + count: 247 + avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 + url: https://github.com/YuriiMotov - login: dmontagu count: 240 avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=540f30c937a6450812628b9592a1dfe91bbe148e&v=4 url: https://github.com/dmontagu -- login: YuriiMotov - count: 223 - avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 - url: https://github.com/YuriiMotov - login: Mause count: 219 avatarUrl: https://avatars.githubusercontent.com/u/1405026?v=4 url: https://github.com/Mause - login: ycd count: 217 - avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=29682e4b6ac7d5293742ccf818188394b9a82972&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=f1e7bae394a315da950912c92dc861a8eaf95d4c&v=4 url: https://github.com/ycd - login: JarroVGIT count: 192 @@ -46,14 +46,14 @@ experts: url: https://github.com/euri10 - login: iudeen count: 128 - avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=f09cdd745e5bf16138f29b42732dd57c7f02bee1&v=4 url: https://github.com/iudeen - login: phy25 count: 126 avatarUrl: https://avatars.githubusercontent.com/u/331403?v=4 url: https://github.com/phy25 - login: JavierSanchezCastro - count: 85 + count: 91 avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 url: https://github.com/JavierSanchezCastro - login: raphaelauv @@ -69,9 +69,13 @@ experts: avatarUrl: https://avatars.githubusercontent.com/u/31127044?u=b0f2c37142f4b762e41ad65dc49581813422bd71&v=4 url: https://github.com/ArcLightSlavik - login: n8sty - count: 66 + count: 67 avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 url: https://github.com/n8sty +- login: luzzodev + count: 61 + avatarUrl: https://avatars.githubusercontent.com/u/27291415?u=5607ae1ce75c5f54f09500ca854227f7bfd2033b&v=4 + url: https://github.com/luzzodev - login: falkben count: 59 avatarUrl: https://avatars.githubusercontent.com/u/653031?u=ad9838e089058c9e5a0bab94c0eec7cc181e0cd0&v=4 @@ -80,26 +84,26 @@ experts: count: 50 avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 url: https://github.com/acidjunk -- login: sm-Fifteen - count: 49 - avatarUrl: https://avatars.githubusercontent.com/u/516999?u=437c0c5038558c67e887ccd863c1ba0f846c03da&v=4 - url: https://github.com/sm-Fifteen - login: yinziyan1206 count: 49 avatarUrl: https://avatars.githubusercontent.com/u/37829370?u=da44ca53aefd5c23f346fab8e9fd2e108294c179&v=4 url: https://github.com/yinziyan1206 +- login: sm-Fifteen + count: 49 + avatarUrl: https://avatars.githubusercontent.com/u/516999?u=437c0c5038558c67e887ccd863c1ba0f846c03da&v=4 + url: https://github.com/sm-Fifteen - login: adriangb count: 46 avatarUrl: https://avatars.githubusercontent.com/u/1755071?u=612704256e38d6ac9cbed24f10e4b6ac2da74ecb&v=4 url: https://github.com/adriangb -- login: Dustyposa - count: 45 - avatarUrl: https://avatars.githubusercontent.com/u/27180793?u=5cf2877f50b3eb2bc55086089a78a36f07042889&v=4 - url: https://github.com/Dustyposa - login: insomnes count: 45 avatarUrl: https://avatars.githubusercontent.com/u/16958893?u=f8be7088d5076d963984a21f95f44e559192d912&v=4 url: https://github.com/insomnes +- login: 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 @@ -108,18 +112,14 @@ experts: count: 43 avatarUrl: https://avatars.githubusercontent.com/u/1144727?u=c159fe047727aedecbbeeaa96a1b03ceb9d39add&v=4 url: https://github.com/frankie567 +- login: sinisaos + count: 41 + avatarUrl: https://avatars.githubusercontent.com/u/30960668?v=4 + url: https://github.com/sinisaos - login: includeamin count: 40 avatarUrl: https://avatars.githubusercontent.com/u/11836741?u=8bd5ef7e62fe6a82055e33c4c0e0a7879ff8cfb6&v=4 url: https://github.com/includeamin -- login: sinisaos - count: 39 - avatarUrl: https://avatars.githubusercontent.com/u/30960668?v=4 - url: https://github.com/sinisaos -- login: luzzodev - count: 37 - avatarUrl: https://avatars.githubusercontent.com/u/27291415?v=4 - url: https://github.com/luzzodev - login: chbndrhnns count: 37 avatarUrl: https://avatars.githubusercontent.com/u/7534547?v=4 @@ -146,8 +146,12 @@ experts: url: https://github.com/hasansezertasan - login: dbanty count: 26 - avatarUrl: https://avatars.githubusercontent.com/u/43723790?u=9bcce836bbce55835291c5b2ac93a4e311f4b3c3&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/43723790?u=9d726785d08e50b1e1cd96505800c8ea8405bce2&v=4 url: https://github.com/dbanty +- login: alv2017 + count: 25 + avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 + url: https://github.com/alv2017 - login: wshayes count: 25 avatarUrl: https://avatars.githubusercontent.com/u/365303?u=07ca03c5ee811eb0920e633cc3c3db73dbec1aa5&v=4 @@ -156,14 +160,14 @@ experts: count: 23 avatarUrl: https://avatars.githubusercontent.com/u/9435877?u=719327b7d2c4c62212456d771bfa7c6b8dbb9eac&v=4 url: https://github.com/SirTelemak +- login: connebs + count: 22 + avatarUrl: https://avatars.githubusercontent.com/u/9054108?u=e151d5f545a3395136d711c227c22032fda67cfa&v=4 + url: https://github.com/connebs - login: nymous count: 22 avatarUrl: https://avatars.githubusercontent.com/u/4216559?u=360a36fb602cded27273cbfc0afc296eece90662&v=4 url: https://github.com/nymous -- login: acnebs - count: 22 - avatarUrl: https://avatars.githubusercontent.com/u/9054108?v=4 - url: https://github.com/acnebs - login: chrisK824 count: 22 avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 @@ -188,14 +192,14 @@ experts: count: 19 avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 url: https://github.com/estebanx64 -- login: sehraramiz - count: 18 - avatarUrl: https://avatars.githubusercontent.com/u/14166324?u=8fac65e84dfff24245d304a5b5b09f7b5bd69dc9&v=4 - url: https://github.com/sehraramiz - login: zoliknemet count: 18 avatarUrl: https://avatars.githubusercontent.com/u/22326718?u=31ba446ac290e23e56eea8e4f0c558aaf0b40779&v=4 url: https://github.com/zoliknemet +- login: sehraramiz + count: 18 + avatarUrl: https://avatars.githubusercontent.com/u/14166324?u=8fac65e84dfff24245d304a5b5b09f7b5bd69dc9&v=4 + url: https://github.com/sehraramiz - login: retnikt count: 18 avatarUrl: https://avatars.githubusercontent.com/u/24581770?v=4 @@ -218,12 +222,16 @@ experts: url: https://github.com/nkhitrov - login: jonatasoli count: 16 - avatarUrl: https://avatars.githubusercontent.com/u/26334101?u=071c062d2861d3dd127f6b4a5258cd8ef55d4c50&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/26334101?u=f601c3f111f2148bd9244c2cb3ebbd57b592e674&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 + count: 15 + avatarUrl: https://avatars.githubusercontent.com/u/25699289?u=b5d219277b4d001ac26fb8be357fddd88c29d51b&v=4 + url: https://github.com/abhint - login: ceb10n count: 15 avatarUrl: https://avatars.githubusercontent.com/u/235213?u=edcce471814a1eba9f0cdaa4cd0de18921a940a6&v=4 @@ -236,261 +244,185 @@ experts: count: 15 avatarUrl: https://avatars.githubusercontent.com/u/33907262?u=2721fb37014d50daf473267c808aa678ecaefe09&v=4 url: https://github.com/simondale00 -- login: ghost - count: 15 - avatarUrl: https://avatars.githubusercontent.com/u/10137?u=b1951d34a583cf12ec0d3b0781ba19be97726318&v=4 - url: https://github.com/ghost -- login: abhint - count: 15 - avatarUrl: https://avatars.githubusercontent.com/u/25699289?u=b5d219277b4d001ac26fb8be357fddd88c29d51b&v=4 - url: https://github.com/abhint last_month_experts: -- login: Kludex - count: 14 - avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=df8a3f06ba8f55ae1967a3e2d5ed882903a4e330&v=4 - url: https://github.com/Kludex - login: YuriiMotov - count: 10 + count: 9 avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 url: https://github.com/YuriiMotov -- login: sehraramiz - count: 7 - avatarUrl: https://avatars.githubusercontent.com/u/14166324?u=8fac65e84dfff24245d304a5b5b09f7b5bd69dc9&v=4 - url: https://github.com/sehraramiz - login: luzzodev - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/27291415?v=4 + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/27291415?u=5607ae1ce75c5f54f09500ca854227f7bfd2033b&v=4 url: https://github.com/luzzodev -- login: yokwejuste - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/71908316?u=592c1e42aa0ee5cb94890e0b863e2acc78cc3bbc&v=4 - url: https://github.com/yokwejuste - login: alv2017 count: 3 avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 url: https://github.com/alv2017 -- login: Trinkes +- login: sachinh35 count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/9466879?v=4 - url: https://github.com/Trinkes -- login: PREPONDERANCE + avatarUrl: https://avatars.githubusercontent.com/u/21972708?u=8560b97b8b41e175f476270b56de8a493b84f302&v=4 + url: https://github.com/sachinh35 +- login: KianAnbarestani count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/112809059?u=30ab12dc9ddba2f94ab90e6ad4ad8bc5cfa7fccd&v=4 - url: https://github.com/PREPONDERANCE -- login: nbx3 - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/34649527?u=943812f69e0d40adbd3fa1c9b8ef50dd971a2a45&v=4 - url: https://github.com/nbx3 -- login: XiaoXinYo - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/56395004?u=b3b7cb758997f283c271a581833e407229dab82c&v=4 - url: https://github.com/XiaoXinYo -- login: iloveitaly + avatarUrl: https://avatars.githubusercontent.com/u/145364424?u=dcc3d8fb4ca07d36fb52a17f38b6650565de40be&v=4 + url: https://github.com/KianAnbarestani +- login: tiangolo count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/150855?v=4 - url: https://github.com/iloveitaly + avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4 + url: https://github.com/tiangolo three_months_experts: - login: luzzodev - count: 33 - avatarUrl: https://avatars.githubusercontent.com/u/27291415?v=4 + count: 25 + avatarUrl: https://avatars.githubusercontent.com/u/27291415?u=5607ae1ce75c5f54f09500ca854227f7bfd2033b&v=4 url: https://github.com/luzzodev - login: YuriiMotov - count: 31 + count: 24 avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 url: https://github.com/YuriiMotov +- login: alv2017 + count: 22 + avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 + url: https://github.com/alv2017 +- login: jgould22 + count: 13 + avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 + url: https://github.com/jgould22 - login: Kludex - count: 24 + count: 10 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=df8a3f06ba8f55ae1967a3e2d5ed882903a4e330&v=4 url: https://github.com/Kludex -- login: sehraramiz - count: 11 - avatarUrl: https://avatars.githubusercontent.com/u/14166324?u=8fac65e84dfff24245d304a5b5b09f7b5bd69dc9&v=4 - url: https://github.com/sehraramiz -- login: estebanx64 +- login: yauhen-sobaleu + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/51629535?u=fc1817060daf2df438bfca86c44f33da5cd667db&v=4 + url: https://github.com/yauhen-sobaleu +- login: JavierSanchezCastro count: 7 - avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 - url: https://github.com/estebanx64 -- login: yvallois + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro +- login: tiangolo count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/36999744?v=4 - url: https://github.com/yvallois -- login: yokwejuste - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/71908316?u=592c1e42aa0ee5cb94890e0b863e2acc78cc3bbc&v=4 - url: https://github.com/yokwejuste -- login: jgould22 - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 - url: https://github.com/jgould22 -- login: alv2017 + avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4 + url: https://github.com/tiangolo +- login: sachinh35 count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 - url: https://github.com/alv2017 -- login: viniciusCalcantara + avatarUrl: https://avatars.githubusercontent.com/u/21972708?u=8560b97b8b41e175f476270b56de8a493b84f302&v=4 + url: https://github.com/sachinh35 +- login: SobikXexe count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/108818737?u=3d7ffe5808843ee4372f9cc5a559ff1674cf1792&v=4 - url: https://github.com/viniciusCalcantara -- login: Trinkes - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/9466879?v=4 - url: https://github.com/Trinkes -- login: PREPONDERANCE + avatarUrl: https://avatars.githubusercontent.com/u/87701130?v=4 + url: https://github.com/SobikXexe +- login: KianAnbarestani count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/112809059?u=30ab12dc9ddba2f94ab90e6ad4ad8bc5cfa7fccd&v=4 - url: https://github.com/PREPONDERANCE -- login: nbx3 - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/34649527?u=943812f69e0d40adbd3fa1c9b8ef50dd971a2a45&v=4 - url: https://github.com/nbx3 -- login: XiaoXinYo - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/56395004?u=b3b7cb758997f283c271a581833e407229dab82c&v=4 - url: https://github.com/XiaoXinYo -- login: JavierSanchezCastro - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 - url: https://github.com/JavierSanchezCastro -- login: iloveitaly - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/150855?v=4 - url: https://github.com/iloveitaly -- login: LincolnPuzey - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/18750802?v=4 - url: https://github.com/LincolnPuzey -- login: Knighthawk-Leo - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/72437494?u=27c68db94a3107b605e603cc136f4ba83f0106d5&v=4 - url: https://github.com/Knighthawk-Leo -- login: gelezo43 + avatarUrl: https://avatars.githubusercontent.com/u/145364424?u=dcc3d8fb4ca07d36fb52a17f38b6650565de40be&v=4 + url: https://github.com/KianAnbarestani +- login: sinisaos count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/40732698?u=611f39d3c1d2f4207a590937a78c1f10eed6232c&v=4 - url: https://github.com/gelezo43 -- login: AliYmn + avatarUrl: https://avatars.githubusercontent.com/u/30960668?v=4 + url: https://github.com/sinisaos +- login: Ale-Cas count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/18416653?u=98c1fca46c7e4dabe8c39d17b5e55d1511d41cf9&v=4 - url: https://github.com/AliYmn -- login: RichieB2B + avatarUrl: https://avatars.githubusercontent.com/u/64859146?u=d52a6ecf8d83d2927e2ae270bdfcc83495dba8c9&v=4 + url: https://github.com/Ale-Cas +- login: adsouza count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/1461970?u=edaa57d1077705244ea5c9244f4783d94ff11f12&v=4 - url: https://github.com/RichieB2B -- login: Synrom + avatarUrl: https://avatars.githubusercontent.com/u/275832?v=4 + url: https://github.com/adsouza +- login: marsboy02 count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/30272537?v=4 - url: https://github.com/Synrom -- login: iiotsrc + avatarUrl: https://avatars.githubusercontent.com/u/86903678?u=fa4a6b91eea3a11ae93c162616ca5edf51c68572&v=4 + url: https://github.com/marsboy02 +- login: EverStarck count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/131771119?u=bcaf2559ef6266af70b151b7fda31a1ee3dbecb3&v=4 - url: https://github.com/iiotsrc -- login: Kfir-G + avatarUrl: https://avatars.githubusercontent.com/u/51029456?u=343409b7cb6b3ea6a59359f4e8370d9c3f140ecd&v=4 + url: https://github.com/EverStarck +- login: vtgn count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/57500876?u=0cd29db046a17f12f382d398141319fca7ff230a&v=4 - url: https://github.com/Kfir-G + avatarUrl: https://avatars.githubusercontent.com/u/112889052?v=4 + url: https://github.com/vtgn six_months_experts: +- login: luzzodev + count: 57 + avatarUrl: https://avatars.githubusercontent.com/u/27291415?u=5607ae1ce75c5f54f09500ca854227f7bfd2033b&v=4 + url: https://github.com/luzzodev - login: YuriiMotov - count: 72 + count: 56 avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 url: https://github.com/YuriiMotov - login: Kludex - count: 40 + count: 34 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=df8a3f06ba8f55ae1967a3e2d5ed882903a4e330&v=4 url: https://github.com/Kludex -- login: luzzodev - count: 37 - avatarUrl: https://avatars.githubusercontent.com/u/27291415?v=4 - url: https://github.com/luzzodev -- login: sinisaos - count: 37 - avatarUrl: https://avatars.githubusercontent.com/u/30960668?v=4 - url: https://github.com/sinisaos -- login: JavierSanchezCastro - count: 16 - avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 - url: https://github.com/JavierSanchezCastro -- login: Kfir-G - count: 13 - avatarUrl: https://avatars.githubusercontent.com/u/57500876?u=0cd29db046a17f12f382d398141319fca7ff230a&v=4 - url: https://github.com/Kfir-G -- login: tiangolo - count: 12 - avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4 - url: https://github.com/tiangolo +- login: alv2017 + count: 25 + avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 + url: https://github.com/alv2017 +- login: jgould22 + count: 17 + avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 + url: https://github.com/jgould22 - login: sehraramiz count: 11 avatarUrl: https://avatars.githubusercontent.com/u/14166324?u=8fac65e84dfff24245d304a5b5b09f7b5bd69dc9&v=4 url: https://github.com/sehraramiz -- login: ceb10n - count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/235213?u=edcce471814a1eba9f0cdaa4cd0de18921a940a6&v=4 - url: https://github.com/ceb10n +- login: JavierSanchezCastro + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 + url: https://github.com/JavierSanchezCastro +- login: yauhen-sobaleu + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/51629535?u=fc1817060daf2df438bfca86c44f33da5cd667db&v=4 + url: https://github.com/yauhen-sobaleu - login: estebanx64 count: 7 avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 url: https://github.com/estebanx64 - login: yvallois - count: 6 + count: 7 avatarUrl: https://avatars.githubusercontent.com/u/36999744?v=4 url: https://github.com/yvallois -- login: n8sty - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 - url: https://github.com/n8sty -- login: TomFaulkner - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/14956620?v=4 - url: https://github.com/TomFaulkner +- login: tiangolo + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4 + url: https://github.com/tiangolo - login: yokwejuste count: 4 avatarUrl: https://avatars.githubusercontent.com/u/71908316?u=592c1e42aa0ee5cb94890e0b863e2acc78cc3bbc&v=4 url: https://github.com/yokwejuste -- login: jgould22 - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 - url: https://github.com/jgould22 -- login: alv2017 +- login: sachinh35 count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 - url: https://github.com/alv2017 + avatarUrl: https://avatars.githubusercontent.com/u/21972708?u=8560b97b8b41e175f476270b56de8a493b84f302&v=4 + url: https://github.com/sachinh35 - login: viniciusCalcantara count: 3 avatarUrl: https://avatars.githubusercontent.com/u/108818737?u=3d7ffe5808843ee4372f9cc5a559ff1674cf1792&v=4 url: https://github.com/viniciusCalcantara -- login: pawelad +- login: SobikXexe count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/7062874?u=d27dc220545a8401ad21840590a97d474d7101e6&v=4 - url: https://github.com/pawelad -- login: dbfreem - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/9778569?u=f2f1e9135b5e4f1b0c6821a548b17f97572720fc&v=4 - url: https://github.com/dbfreem -- login: Isuxiz - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/48672727?u=34d7b4ade252687d22a27cf53037b735b244bfc1&v=4 - url: https://github.com/Isuxiz -- login: bertomaniac - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/10235051?u=14484a96833228a7b29fee4a7916d411c242c4f6&v=4 - url: https://github.com/bertomaniac -- login: PhysicallyActive - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4 - url: https://github.com/PhysicallyActive -- login: Minibrams - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/8108085?u=b028dbc308fa8485e0e2e9402b3d03d8deb22bf9&v=4 - url: https://github.com/Minibrams -- login: AIdjis - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/88404339?u=2a80d80b054e9228391e32fb9bb39571509dab6a&v=4 - url: https://github.com/AIdjis -- login: svlandeg - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/8796347?u=556c97650c27021911b0b9447ec55e75987b0e8a&v=4 - url: https://github.com/svlandeg -- login: Trinkes + avatarUrl: https://avatars.githubusercontent.com/u/87701130?v=4 + url: https://github.com/SobikXexe +- login: chaitanyarahalkar count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/9466879?v=4 - url: https://github.com/Trinkes + avatarUrl: https://avatars.githubusercontent.com/u/24942959?u=d3fbbc622540cb50b956585d5aec5037e01e4b1f&v=4 + url: https://github.com/chaitanyarahalkar +- login: KianAnbarestani + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/145364424?u=dcc3d8fb4ca07d36fb52a17f38b6650565de40be&v=4 + url: https://github.com/KianAnbarestani +- login: sinisaos + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/30960668?v=4 + url: https://github.com/sinisaos +- login: Ale-Cas + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/64859146?u=d52a6ecf8d83d2927e2ae270bdfcc83495dba8c9&v=4 + url: https://github.com/Ale-Cas +- login: adsouza + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/275832?v=4 + url: https://github.com/adsouza +- login: Synrom + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/30272537?v=4 + url: https://github.com/Synrom - login: PREPONDERANCE count: 2 avatarUrl: https://avatars.githubusercontent.com/u/112809059?u=30ab12dc9ddba2f94ab90e6ad4ad8bc5cfa7fccd&v=4 @@ -499,26 +431,26 @@ six_months_experts: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/34649527?u=943812f69e0d40adbd3fa1c9b8ef50dd971a2a45&v=4 url: https://github.com/nbx3 -- login: yanggeorge +- login: marsboy02 count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/2434407?v=4 - url: https://github.com/yanggeorge -- login: XiaoXinYo + avatarUrl: https://avatars.githubusercontent.com/u/86903678?u=fa4a6b91eea3a11ae93c162616ca5edf51c68572&v=4 + url: https://github.com/marsboy02 +- login: EverStarck count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/56395004?u=b3b7cb758997f283c271a581833e407229dab82c&v=4 - url: https://github.com/XiaoXinYo -- login: pythonweb2 + avatarUrl: https://avatars.githubusercontent.com/u/51029456?u=343409b7cb6b3ea6a59359f4e8370d9c3f140ecd&v=4 + url: https://github.com/EverStarck +- login: vtgn count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 - url: https://github.com/pythonweb2 -- login: slafs + avatarUrl: https://avatars.githubusercontent.com/u/112889052?v=4 + url: https://github.com/vtgn +- login: Trinkes count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/210173?v=4 - url: https://github.com/slafs -- login: AmirHmZz + avatarUrl: https://avatars.githubusercontent.com/u/9466879?v=4 + url: https://github.com/Trinkes +- login: XiaoXinYo count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/38752106?u=07f80e451bda00a9492bbc764e49d24ad3ada8cc&v=4 - url: https://github.com/AmirHmZz + avatarUrl: https://avatars.githubusercontent.com/u/56395004?u=1eebf5ce25a8067f7bfa6251a24f667be492d9d6&v=4 + url: https://github.com/XiaoXinYo - login: iloveitaly count: 2 avatarUrl: https://avatars.githubusercontent.com/u/150855?v=4 @@ -527,10 +459,6 @@ six_months_experts: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/18750802?v=4 url: https://github.com/LincolnPuzey -- login: alejsdev - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=356f39ff3f0211c720b06d3dbb060e98884085e3&v=4 - url: https://github.com/alejsdev - login: Knighthawk-Leo count: 2 avatarUrl: https://avatars.githubusercontent.com/u/72437494?u=27c68db94a3107b605e603cc136f4ba83f0106d5&v=4 @@ -539,14 +467,6 @@ six_months_experts: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/40732698?u=611f39d3c1d2f4207a590937a78c1f10eed6232c&v=4 url: https://github.com/gelezo43 -- login: christiansicari - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/29756552?v=4 - url: https://github.com/christiansicari -- login: 1001pepi - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/82064861?u=8c6ffdf2275d6970a07294752c545cd2702c57d3&v=4 - url: https://github.com/1001pepi - login: AliYmn count: 2 avatarUrl: https://avatars.githubusercontent.com/u/18416653?u=98c1fca46c7e4dabe8c39d17b5e55d1511d41cf9&v=4 @@ -555,171 +475,107 @@ six_months_experts: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/1461970?u=edaa57d1077705244ea5c9244f4783d94ff11f12&v=4 url: https://github.com/RichieB2B -- login: Synrom - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/30272537?v=4 - url: https://github.com/Synrom -- login: ecly - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/8410422?v=4 - url: https://github.com/ecly - login: iiotsrc count: 2 avatarUrl: https://avatars.githubusercontent.com/u/131771119?u=bcaf2559ef6266af70b151b7fda31a1ee3dbecb3&v=4 url: https://github.com/iiotsrc -- login: simondale00 - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/33907262?u=2721fb37014d50daf473267c808aa678ecaefe09&v=4 - url: https://github.com/simondale00 -- login: jd-solanki - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/47495003?u=6e225cb42c688d0cd70e65c6baedb9f5922b1178&v=4 - url: https://github.com/jd-solanki -- login: AumGupta - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/86357151?u=7d05aa606c0611a18f4db16cf26361ce10a6e195&v=4 - url: https://github.com/AumGupta -- login: DeoLeung - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/3764720?u=4c222ef513814de4c7fb3736d0a7adf11d953d43&v=4 - url: https://github.com/DeoLeung -- login: Reemyos - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/44867003?v=4 - url: https://github.com/Reemyos -- login: deight93 - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/37678115?u=a608798b5bd0034183a9c430ebb42fb266db86ce&v=4 - url: https://github.com/deight93 -- login: Jkrox - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/83181939?u=d6a922d97129f7f3916d6a1c166bc011b3a72b7f&v=4 - url: https://github.com/Jkrox -- login: mmzeynalli - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/33568903?u=19efd0c0722730b83a70b7c86c36e5b7d83e07d2&v=4 - url: https://github.com/mmzeynalli -- login: ddahan - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/1933516?u=1d200a620e8d6841df017e9f2bb7efb58b580f40&v=4 - url: https://github.com/ddahan -- login: jfeaver - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/1091338?u=0bcba366447d8fadad63f6705a52d128da4c7ec2&v=4 - url: https://github.com/jfeaver -- login: Wurstnase - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/8709415?u=f479af475a97aee9a1dab302cfc35d07e9ea245f&v=4 - url: https://github.com/Wurstnase -- login: tristan - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/1412?u=aab8aaa4cc0f1210ac45fc93873a5909d314c965&v=4 - url: https://github.com/tristan -- login: chandanch - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/8663552?u=afc484bc0a952c83f1fb6a1583cda443f807cd66&v=4 - url: https://github.com/chandanch -- login: rvishruth - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/79176273?v=4 - url: https://github.com/rvishruth -- login: mattmess1221 +- login: Kfir-G count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/3409962?u=723662989f2027755e67d200137c13c53ae154ac&v=4 - url: https://github.com/mattmess1221 + avatarUrl: https://avatars.githubusercontent.com/u/57500876?u=0cd29db046a17f12f382d398141319fca7ff230a&v=4 + url: https://github.com/Kfir-G one_year_experts: - login: YuriiMotov - count: 223 + count: 172 avatarUrl: https://avatars.githubusercontent.com/u/109919500?u=e83a39697a2d33ab2ec9bfbced794ee48bc29cec&v=4 url: https://github.com/YuriiMotov - login: Kludex - count: 81 + count: 63 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=df8a3f06ba8f55ae1967a3e2d5ed882903a4e330&v=4 url: https://github.com/Kludex +- login: luzzodev + count: 61 + avatarUrl: https://avatars.githubusercontent.com/u/27291415?u=5607ae1ce75c5f54f09500ca854227f7bfd2033b&v=4 + url: https://github.com/luzzodev +- login: sinisaos + count: 41 + avatarUrl: https://avatars.githubusercontent.com/u/30960668?v=4 + url: https://github.com/sinisaos - login: JavierSanchezCastro - count: 47 + count: 33 avatarUrl: https://avatars.githubusercontent.com/u/72013291?u=ae5679e6bd971d9d98cd5e76e8683f83642ba950&v=4 url: https://github.com/JavierSanchezCastro - login: jgould22 - count: 42 + count: 27 avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 url: https://github.com/jgould22 -- login: sinisaos - count: 39 - avatarUrl: https://avatars.githubusercontent.com/u/30960668?v=4 - url: https://github.com/sinisaos -- login: luzzodev - count: 37 - avatarUrl: https://avatars.githubusercontent.com/u/27291415?v=4 - url: https://github.com/luzzodev +- login: alv2017 + count: 25 + avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 + url: https://github.com/alv2017 - login: tiangolo count: 24 avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4 url: https://github.com/tiangolo -- login: n8sty - count: 23 - avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 - url: https://github.com/n8sty -- login: estebanx64 - count: 19 - avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 - url: https://github.com/estebanx64 - login: ceb10n count: 15 avatarUrl: https://avatars.githubusercontent.com/u/235213?u=edcce471814a1eba9f0cdaa4cd0de18921a940a6&v=4 url: https://github.com/ceb10n +- login: estebanx64 + count: 13 + avatarUrl: https://avatars.githubusercontent.com/u/10840422?u=45f015f95e1c0f06df602be4ab688d4b854cc8a8&v=4 + url: https://github.com/estebanx64 +- login: n8sty + count: 13 + avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 + url: https://github.com/n8sty +- login: Kfir-G + count: 13 + avatarUrl: https://avatars.githubusercontent.com/u/57500876?u=0cd29db046a17f12f382d398141319fca7ff230a&v=4 + url: https://github.com/Kfir-G - login: sehraramiz - count: 15 + count: 11 avatarUrl: https://avatars.githubusercontent.com/u/14166324?u=8fac65e84dfff24245d304a5b5b09f7b5bd69dc9&v=4 url: https://github.com/sehraramiz - login: PhysicallyActive - count: 14 + count: 11 avatarUrl: https://avatars.githubusercontent.com/u/160476156?u=7a8e44f4a43d3bba636f795bb7d9476c9233b4d8&v=4 url: https://github.com/PhysicallyActive -- login: Kfir-G - count: 13 - avatarUrl: https://avatars.githubusercontent.com/u/57500876?u=0cd29db046a17f12f382d398141319fca7ff230a&v=4 - url: https://github.com/Kfir-G - login: mattmess1221 count: 11 - avatarUrl: https://avatars.githubusercontent.com/u/3409962?u=723662989f2027755e67d200137c13c53ae154ac&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/3409962?u=d22ea18aa8ea688af25a45df306134d593621a44&v=4 url: https://github.com/mattmess1221 -- login: hasansezertasan - count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 - url: https://github.com/hasansezertasan +- login: yauhen-sobaleu + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/51629535?u=fc1817060daf2df438bfca86c44f33da5cd667db&v=4 + url: https://github.com/yauhen-sobaleu - login: AIdjis count: 8 avatarUrl: https://avatars.githubusercontent.com/u/88404339?u=2a80d80b054e9228391e32fb9bb39571509dab6a&v=4 url: https://github.com/AIdjis - login: yvallois - count: 6 + count: 7 avatarUrl: https://avatars.githubusercontent.com/u/36999744?v=4 url: https://github.com/yvallois -- login: PREPONDERANCE - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/112809059?u=30ab12dc9ddba2f94ab90e6ad4ad8bc5cfa7fccd&v=4 - url: https://github.com/PREPONDERANCE -- login: pythonweb2 - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/32141163?v=4 - url: https://github.com/pythonweb2 -- login: acidjunk +- login: hasansezertasan count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 - url: https://github.com/acidjunk + avatarUrl: https://avatars.githubusercontent.com/u/13135006?u=99f0b0f0fc47e88e8abb337b4447357939ef93e7&v=4 + url: https://github.com/hasansezertasan - login: gustavosett count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/99373133?u=1739ca547c3d200f1b72450520bce46a97aab184&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/99373133?u=1382fe27034a0179f07cf989f63c4f23017f043c&v=4 url: https://github.com/gustavosett -- login: binbjz - count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/8213913?u=22b68b7a0d5bf5e09c02084c0f5f53d7503114cd&v=4 - url: https://github.com/binbjz - login: chyok count: 5 avatarUrl: https://avatars.githubusercontent.com/u/32629225?u=3b7c30e8a09426a1b9284f6e8a0ae53a525596bf&v=4 url: https://github.com/chyok +- login: PREPONDERANCE + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/112809059?u=30ab12dc9ddba2f94ab90e6ad4ad8bc5cfa7fccd&v=4 + url: https://github.com/PREPONDERANCE +- login: svlandeg + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/8796347?u=556c97650c27021911b0b9447ec55e75987b0e8a&v=4 + url: https://github.com/svlandeg - login: TomFaulkner count: 4 avatarUrl: https://avatars.githubusercontent.com/u/14956620?v=4 @@ -728,118 +584,106 @@ one_year_experts: count: 4 avatarUrl: https://avatars.githubusercontent.com/u/71908316?u=592c1e42aa0ee5cb94890e0b863e2acc78cc3bbc&v=4 url: https://github.com/yokwejuste -- login: DeoLeung - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/3764720?u=4c222ef513814de4c7fb3736d0a7adf11d953d43&v=4 - url: https://github.com/DeoLeung -- login: flo-at - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/564288?v=4 - url: https://github.com/flo-at -- login: GodMoonGoodman - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/29688727?u=7b251da620d999644c37c1feeb292d033eed7ad6&v=4 - url: https://github.com/GodMoonGoodman -- login: bertomaniac +- login: binbjz count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/10235051?u=14484a96833228a7b29fee4a7916d411c242c4f6&v=4 - url: https://github.com/bertomaniac -- login: alv2017 + avatarUrl: https://avatars.githubusercontent.com/u/8213913?u=40b777c625cf53dcdc6afc4aa127de67c48bf610&v=4 + url: https://github.com/binbjz +- login: dbfreem count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 - url: https://github.com/alv2017 -- login: msehnout + avatarUrl: https://avatars.githubusercontent.com/u/9778569?u=f2f1e9135b5e4f1b0c6821a548b17f97572720fc&v=4 + url: https://github.com/dbfreem +- login: sachinh35 count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/9369632?u=8c988f1b008a3f601385a3616f9327820f66e3a5&v=4 - url: https://github.com/msehnout + avatarUrl: https://avatars.githubusercontent.com/u/21972708?u=8560b97b8b41e175f476270b56de8a493b84f302&v=4 + url: https://github.com/sachinh35 - login: viniciusCalcantara count: 3 avatarUrl: https://avatars.githubusercontent.com/u/108818737?u=3d7ffe5808843ee4372f9cc5a559ff1674cf1792&v=4 url: https://github.com/viniciusCalcantara +- login: SobikXexe + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/87701130?v=4 + url: https://github.com/SobikXexe +- login: DeoLeung + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/3764720?u=4c222ef513814de4c7fb3736d0a7adf11d953d43&v=4 + url: https://github.com/DeoLeung - login: pawelad count: 3 avatarUrl: https://avatars.githubusercontent.com/u/7062874?u=d27dc220545a8401ad21840590a97d474d7101e6&v=4 url: https://github.com/pawelad -- login: ThirVondukr - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/50728601?u=167c0bd655e52817082e50979a86d2f98f95b1a3&v=4 - url: https://github.com/ThirVondukr -- login: dbfreem - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/9778569?u=f2f1e9135b5e4f1b0c6821a548b17f97572720fc&v=4 - url: https://github.com/dbfreem - login: Isuxiz count: 3 avatarUrl: https://avatars.githubusercontent.com/u/48672727?u=34d7b4ade252687d22a27cf53037b735b244bfc1&v=4 url: https://github.com/Isuxiz -- login: angely-dev +- login: bertomaniac count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/4362224?v=4 - url: https://github.com/angely-dev + avatarUrl: https://avatars.githubusercontent.com/u/10235051?u=14484a96833228a7b29fee4a7916d411c242c4f6&v=4 + url: https://github.com/bertomaniac - login: deight93 count: 3 avatarUrl: https://avatars.githubusercontent.com/u/37678115?u=a608798b5bd0034183a9c430ebb42fb266db86ce&v=4 url: https://github.com/deight93 -- login: mmzeynalli - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/33568903?u=19efd0c0722730b83a70b7c86c36e5b7d83e07d2&v=4 - url: https://github.com/mmzeynalli - login: Minibrams count: 3 avatarUrl: https://avatars.githubusercontent.com/u/8108085?u=b028dbc308fa8485e0e2e9402b3d03d8deb22bf9&v=4 url: https://github.com/Minibrams -- login: ryanisn - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/53449841?v=4 - url: https://github.com/ryanisn -- login: svlandeg - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/8796347?u=556c97650c27021911b0b9447ec55e75987b0e8a&v=4 - url: https://github.com/svlandeg - login: alexandercronin count: 3 avatarUrl: https://avatars.githubusercontent.com/u/8014288?u=69580504c51a0cdd756fc47b23bb7f404bd694e7&v=4 url: https://github.com/alexandercronin -- login: aanchlia - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/2835374?u=3c3ed29aa8b09ccaf8d66def0ce82bc2f7e5aab6&v=4 - url: https://github.com/aanchlia -- login: chrisK824 - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/79946379?u=03d85b22d696a58a9603e55fbbbe2de6b0f4face&v=4 - url: https://github.com/chrisK824 -- login: omarcruzpantoja - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/15116058?u=4b64c643fad49225d854e1aaecd1ffc6f9071a1b&v=4 - url: https://github.com/omarcruzpantoja -- login: ahmedabdou14 - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/104530599?u=d87b866e7c1db970d6f8e8031643818349b046d5&v=4 - url: https://github.com/ahmedabdou14 -- login: Trinkes +- login: yanggeorge count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/9466879?v=4 - url: https://github.com/Trinkes -- login: Leon0824 + avatarUrl: https://avatars.githubusercontent.com/u/2434407?v=4 + url: https://github.com/yanggeorge +- login: chaitanyarahalkar + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/24942959?u=d3fbbc622540cb50b956585d5aec5037e01e4b1f&v=4 + url: https://github.com/chaitanyarahalkar +- login: KianAnbarestani count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/1922026?v=4 - url: https://github.com/Leon0824 -- login: CarlosOliveira-23 + avatarUrl: https://avatars.githubusercontent.com/u/145364424?u=dcc3d8fb4ca07d36fb52a17f38b6650565de40be&v=4 + url: https://github.com/KianAnbarestani +- login: rustonaut count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/102637302?u=cf350a4db956f30cbb2c27d3be0d15c282e32b14&v=4 - url: https://github.com/CarlosOliveira-23 + avatarUrl: https://avatars.githubusercontent.com/u/7632017?u=652bb86c1399727082c929fd4666fd7fa65923b1&v=4 + url: https://github.com/rustonaut +- login: Ale-Cas + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/64859146?u=d52a6ecf8d83d2927e2ae270bdfcc83495dba8c9&v=4 + url: https://github.com/Ale-Cas +- login: CharlesPerrotMinotHCHB + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/112571330?u=a9628848d6096b491135727435a2a253152995a1&v=4 + url: https://github.com/CharlesPerrotMinotHCHB +- login: adsouza + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/275832?v=4 + url: https://github.com/adsouza +- login: Synrom + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/30272537?v=4 + url: https://github.com/Synrom +- login: gaby + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/835733?u=8c72dec16fa560bdc81113354f2ffd79ad062bde&v=4 + url: https://github.com/gaby - login: nbx3 count: 2 avatarUrl: https://avatars.githubusercontent.com/u/34649527?u=943812f69e0d40adbd3fa1c9b8ef50dd971a2a45&v=4 url: https://github.com/nbx3 -- login: yanggeorge +- login: marsboy02 count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/2434407?v=4 - url: https://github.com/yanggeorge -- login: XiaoXinYo + avatarUrl: https://avatars.githubusercontent.com/u/86903678?u=fa4a6b91eea3a11ae93c162616ca5edf51c68572&v=4 + url: https://github.com/marsboy02 +- login: EverStarck count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/56395004?u=b3b7cb758997f283c271a581833e407229dab82c&v=4 - url: https://github.com/XiaoXinYo + avatarUrl: https://avatars.githubusercontent.com/u/51029456?u=343409b7cb6b3ea6a59359f4e8370d9c3f140ecd&v=4 + url: https://github.com/EverStarck +- login: Trolldemorted + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/10261186?v=4 + url: https://github.com/Trolldemorted - login: anantgupta129 count: 2 avatarUrl: https://avatars.githubusercontent.com/u/66518357?u=6e25dcd84638f17d2c6df5dc26f07fd7c6dc118e&v=4 @@ -848,23 +692,35 @@ one_year_experts: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/210173?v=4 url: https://github.com/slafs -- login: monchin +- login: ddahan count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/18521800?v=4 - url: https://github.com/monchin -- login: AmirHmZz + avatarUrl: https://avatars.githubusercontent.com/u/1933516?u=1d200a620e8d6841df017e9f2bb7efb58b580f40&v=4 + url: https://github.com/ddahan +- login: vtgn count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/38752106?u=07f80e451bda00a9492bbc764e49d24ad3ada8cc&v=4 - url: https://github.com/AmirHmZz -- login: iloveitaly + avatarUrl: https://avatars.githubusercontent.com/u/112889052?v=4 + url: https://github.com/vtgn +- login: redb0 count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/150855?v=4 - url: https://github.com/iloveitaly + avatarUrl: https://avatars.githubusercontent.com/u/30475117?v=4 + url: https://github.com/redb0 +- login: pedroconceicao + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/32837064?u=5a0e6559bc391442629a28b6923790b54deb4464&v=4 + url: https://github.com/pedroconceicao - login: msukmanowsky count: 2 avatarUrl: https://avatars.githubusercontent.com/u/362755?u=782e6bf5b9f0356c3f74b4d894fda9f179252086&v=4 url: https://github.com/msukmanowsky -- login: shurshilov +- login: rishabhc32 count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/11828278?u=6bcadc5ce4f2f56a514331c9f68eb987d4afe29a&v=4 - url: https://github.com/shurshilov + avatarUrl: https://avatars.githubusercontent.com/u/15983714?u=147776509107af8bdf099223e1840d3f40f944da&v=4 + url: https://github.com/rishabhc32 +- login: meower1 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/109747197?u=0a5cc2a6ae74e558f0afc2874da85132e5953d8b&v=4 + url: https://github.com/meower1 +- login: Trinkes + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/9466879?v=4 + url: https://github.com/Trinkes diff --git a/docs/en/data/sponsors.yml b/docs/en/data/sponsors.yml index f9bf33ae9..14a1f3cf3 100644 --- a/docs/en/data/sponsors.yml +++ b/docs/en/data/sponsors.yml @@ -8,23 +8,14 @@ gold: - url: https://www.porter.run title: Deploy FastAPI on AWS with a few clicks img: https://fastapi.tiangolo.com/img/sponsors/porter.png - - url: https://bump.sh/fastapi?utm_source=fastapi&utm_medium=referral&utm_campaign=sponsor - title: Automate FastAPI documentation generation with Bump.sh - img: https://fastapi.tiangolo.com/img/sponsors/bump-sh.svg - url: https://github.com/scalar/scalar/?utm_source=fastapi&utm_medium=website&utm_campaign=main-badge title: "Scalar: Beautiful Open-Source API References from Swagger/OpenAPI files" img: https://fastapi.tiangolo.com/img/sponsors/scalar.svg - url: https://www.propelauth.com/?utm_source=fastapi&utm_campaign=1223&utm_medium=mainbadge title: Auth, user management and more for your B2B product img: https://fastapi.tiangolo.com/img/sponsors/propelauth.png - - url: https://www.withcoherence.com/?utm_medium=advertising&utm_source=fastapi&utm_campaign=website - title: Coherence - img: https://fastapi.tiangolo.com/img/sponsors/coherence.png - - url: https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi/?utm_campaign=fastapi_framework&utm_source=fastapi_sponsorship&utm_medium=web_referral - title: Simplify Full Stack Development with FastAPI & MongoDB - img: https://fastapi.tiangolo.com/img/sponsors/mongodb.png - url: https://zuplo.link/fastapi-gh - title: 'Zuplo: Scale, Protect, Document, and Monetize your FastAPI' + title: 'Zuplo: Deploy, Secure, Document, and Monetize your FastAPI' img: https://fastapi.tiangolo.com/img/sponsors/zuplo.png - url: https://liblab.com?utm_source=fastapi title: liblab - Generate SDKs from FastAPI @@ -32,10 +23,13 @@ gold: - url: https://docs.render.com/deploy-fastapi?utm_source=deploydoc&utm_medium=referral&utm_campaign=fastapi title: Deploy & scale any full-stack web app on Render. Focus on building apps, not infra. img: https://fastapi.tiangolo.com/img/sponsors/render.svg + - url: https://www.coderabbit.ai/?utm_source=fastapi&utm_medium=badge&utm_campaign=fastapi + title: Cut Code Review Time & Bugs in Half with CodeRabbit + img: https://fastapi.tiangolo.com/img/sponsors/coderabbit.png + - url: https://subtotal.com/?utm_source=fastapi&utm_medium=sponsorship&utm_campaign=open-source + title: The Gold Standard in Retail Account Linking + img: https://fastapi.tiangolo.com/img/sponsors/subtotal.svg silver: - - url: https://github.com/deepset-ai/haystack/ - title: Build powerful search from composable, open source building blocks - img: https://fastapi.tiangolo.com/img/sponsors/haystack-fastapi.svg - url: https://databento.com/ title: Pay as you go for market data img: https://fastapi.tiangolo.com/img/sponsors/databento.svg @@ -51,10 +45,16 @@ silver: - url: https://www.permit.io/blog/implement-authorization-in-fastapi?utm_source=github&utm_medium=referral&utm_campaign=fastapi title: Fine-Grained Authorization for FastAPI img: https://fastapi.tiangolo.com/img/sponsors/permit.png + - url: https://www.interviewpal.com/?utm_source=fastapi&utm_medium=open-source&utm_campaign=dev-hiring + title: InterviewPal - AI Interview Coach for Engineers and Devs + img: https://fastapi.tiangolo.com/img/sponsors/interviewpal.png bronze: - url: https://www.exoflare.com/open-source/?utm_source=FastAPI&utm_campaign=open_source title: Biosecurity risk assessments made easy. img: https://fastapi.tiangolo.com/img/sponsors/exoflare.png - - url: https://testdriven.io/courses/tdd-fastapi/ - title: Learn to build high-quality web apps with best practices - img: https://fastapi.tiangolo.com/img/sponsors/testdriven.svg + # - url: https://testdriven.io/courses/tdd-fastapi/ + # title: Learn to build high-quality web apps with best practices + # img: https://fastapi.tiangolo.com/img/sponsors/testdriven.svg + - url: https://lambdatest.com/?utm_source=fastapi&utm_medium=partner&utm_campaign=sponsor&utm_term=opensource&utm_content=webpage + title: LambdaTest, AI-Powered Cloud-based Test Orchestration Platform + img: https://fastapi.tiangolo.com/img/sponsors/lambdatest.png diff --git a/docs/en/data/sponsors_badge.yml b/docs/en/data/sponsors_badge.yml index d507a500f..fd34019b3 100644 --- a/docs/en/data/sponsors_badge.yml +++ b/docs/en/data/sponsors_badge.yml @@ -38,3 +38,7 @@ logins: - render-sponsorships - renderinc - stainless-api + - snapit-cypher + - coderabbitai + - permitio + - LambdaTest-Inc diff --git a/docs/en/data/topic_repos.yml b/docs/en/data/topic_repos.yml index 302dc3bb5..1f6ae55bd 100644 --- a/docs/en/data/topic_repos.yml +++ b/docs/en/data/topic_repos.yml @@ -1,495 +1,495 @@ - name: full-stack-fastapi-template html_url: https://github.com/fastapi/full-stack-fastapi-template - stars: 29409 + stars: 33079 owner_login: fastapi owner_html_url: https://github.com/fastapi - name: Hello-Python html_url: https://github.com/mouredev/Hello-Python - stars: 28113 + stars: 30350 owner_login: mouredev owner_html_url: https://github.com/mouredev - name: serve html_url: https://github.com/jina-ai/serve - stars: 21264 + stars: 21593 owner_login: jina-ai owner_html_url: https://github.com/jina-ai -- name: sqlmodel - html_url: https://github.com/fastapi/sqlmodel - stars: 15109 - owner_login: fastapi - owner_html_url: https://github.com/fastapi - name: HivisionIDPhotos html_url: https://github.com/Zeyi-Lin/HivisionIDPhotos - stars: 14564 + stars: 17229 owner_login: Zeyi-Lin owner_html_url: https://github.com/Zeyi-Lin +- name: sqlmodel + html_url: https://github.com/fastapi/sqlmodel + stars: 16068 + owner_login: fastapi + owner_html_url: https://github.com/fastapi - name: Douyin_TikTok_Download_API html_url: https://github.com/Evil0ctal/Douyin_TikTok_Download_API - stars: 10701 + stars: 12689 owner_login: Evil0ctal owner_html_url: https://github.com/Evil0ctal - name: fastapi-best-practices html_url: https://github.com/zhanymkanov/fastapi-best-practices - stars: 10180 + stars: 11965 owner_login: zhanymkanov owner_html_url: https://github.com/zhanymkanov - name: awesome-fastapi html_url: https://github.com/mjhea0/awesome-fastapi - stars: 9061 + stars: 9773 owner_login: mjhea0 owner_html_url: https://github.com/mjhea0 - name: FastUI html_url: https://github.com/pydantic/FastUI - stars: 8644 + stars: 8829 owner_login: pydantic owner_html_url: https://github.com/pydantic - name: nonebot2 html_url: https://github.com/nonebot/nonebot2 - stars: 6312 + stars: 6779 owner_login: nonebot owner_html_url: https://github.com/nonebot -- name: serge - html_url: https://github.com/serge-chat/serge - stars: 5686 - owner_login: serge-chat - owner_html_url: https://github.com/serge-chat - name: FileCodeBox html_url: https://github.com/vastsa/FileCodeBox - stars: 4933 + stars: 6652 owner_login: vastsa owner_html_url: https://github.com/vastsa -- name: fastapi-users - html_url: https://github.com/fastapi-users/fastapi-users - stars: 4849 - owner_login: fastapi-users - owner_html_url: https://github.com/fastapi-users +- name: serge + html_url: https://github.com/serge-chat/serge + stars: 5722 + owner_login: serge-chat + owner_html_url: https://github.com/serge-chat - name: hatchet html_url: https://github.com/hatchet-dev/hatchet - stars: 4514 + stars: 5607 owner_login: hatchet-dev owner_html_url: https://github.com/hatchet-dev -- name: chatgpt-web-share - html_url: https://github.com/chatpire/chatgpt-web-share - stars: 4319 - owner_login: chatpire - owner_html_url: https://github.com/chatpire - name: polar html_url: https://github.com/polarsource/polar - stars: 4216 + stars: 5327 owner_login: polarsource owner_html_url: https://github.com/polarsource +- name: fastapi-users + html_url: https://github.com/fastapi-users/fastapi-users + stars: 5235 + owner_login: fastapi-users + owner_html_url: https://github.com/fastapi-users +- name: fastapi_mcp + html_url: https://github.com/tadata-org/fastapi_mcp + stars: 5193 + owner_login: tadata-org + owner_html_url: https://github.com/tadata-org +- name: SurfSense + html_url: https://github.com/MODSetter/SurfSense + stars: 4833 + owner_login: MODSetter + owner_html_url: https://github.com/MODSetter +- name: chatgpt-web-share + html_url: https://github.com/chatpire/chatgpt-web-share + stars: 4307 + owner_login: chatpire + owner_html_url: https://github.com/chatpire - name: strawberry html_url: https://github.com/strawberry-graphql/strawberry - stars: 4126 + stars: 4281 owner_login: strawberry-graphql owner_html_url: https://github.com/strawberry-graphql - name: atrilabs-engine html_url: https://github.com/Atri-Labs/atrilabs-engine - stars: 4114 + stars: 4110 owner_login: Atri-Labs owner_html_url: https://github.com/Atri-Labs - name: dynaconf html_url: https://github.com/dynaconf/dynaconf - stars: 3874 + stars: 4008 owner_login: dynaconf owner_html_url: https://github.com/dynaconf - name: poem html_url: https://github.com/poem-web/poem - stars: 3746 + stars: 3977 owner_login: poem-web owner_html_url: https://github.com/poem-web -- name: opyrator - html_url: https://github.com/ml-tooling/opyrator - stars: 3117 - owner_login: ml-tooling - owner_html_url: https://github.com/ml-tooling - name: farfalle html_url: https://github.com/rashadphz/farfalle - stars: 3094 + stars: 3317 owner_login: rashadphz owner_html_url: https://github.com/rashadphz - name: fastapi-admin html_url: https://github.com/fastapi-admin/fastapi-admin - stars: 3040 + stars: 3253 owner_login: fastapi-admin owner_html_url: https://github.com/fastapi-admin -- name: docarray - html_url: https://github.com/docarray/docarray - stars: 3007 - owner_login: docarray - owner_html_url: https://github.com/docarray - name: datamodel-code-generator html_url: https://github.com/koxudaxi/datamodel-code-generator - stars: 2914 + stars: 3228 owner_login: koxudaxi owner_html_url: https://github.com/koxudaxi -- name: fastapi-realworld-example-app - html_url: https://github.com/nsidnev/fastapi-realworld-example-app - stars: 2840 - owner_login: nsidnev - owner_html_url: https://github.com/nsidnev - name: LitServe html_url: https://github.com/Lightning-AI/LitServe - stars: 2804 + stars: 3175 owner_login: Lightning-AI owner_html_url: https://github.com/Lightning-AI -- name: uvicorn-gunicorn-fastapi-docker - html_url: https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker - stars: 2730 - owner_login: tiangolo - owner_html_url: https://github.com/tiangolo - name: logfire html_url: https://github.com/pydantic/logfire - stars: 2620 + stars: 3172 owner_login: pydantic owner_html_url: https://github.com/pydantic +- name: opyrator + html_url: https://github.com/ml-tooling/opyrator + stars: 3122 + owner_login: ml-tooling + owner_html_url: https://github.com/ml-tooling - name: huma html_url: https://github.com/danielgtaylor/huma - stars: 2567 + stars: 3110 owner_login: danielgtaylor owner_html_url: https://github.com/danielgtaylor +- name: docarray + html_url: https://github.com/docarray/docarray + stars: 3068 + owner_login: docarray + owner_html_url: https://github.com/docarray +- name: fastapi-realworld-example-app + html_url: https://github.com/nsidnev/fastapi-realworld-example-app + stars: 2892 + owner_login: nsidnev + owner_html_url: https://github.com/nsidnev +- name: Kokoro-FastAPI + html_url: https://github.com/remsky/Kokoro-FastAPI + stars: 2883 + owner_login: remsky + owner_html_url: https://github.com/remsky +- name: uvicorn-gunicorn-fastapi-docker + html_url: https://github.com/tiangolo/uvicorn-gunicorn-fastapi-docker + stars: 2770 + owner_login: tiangolo + owner_html_url: https://github.com/tiangolo - name: tracecat html_url: https://github.com/TracecatHQ/tracecat - stars: 2494 + stars: 2740 owner_login: TracecatHQ owner_html_url: https://github.com/TracecatHQ - name: best-of-web-python html_url: https://github.com/ml-tooling/best-of-web-python - stars: 2433 + stars: 2517 owner_login: ml-tooling owner_html_url: https://github.com/ml-tooling - name: RasaGPT html_url: https://github.com/paulpierre/RasaGPT - stars: 2386 + stars: 2423 owner_login: paulpierre owner_html_url: https://github.com/paulpierre - name: fastapi-react html_url: https://github.com/Buuntu/fastapi-react - stars: 2293 + stars: 2376 owner_login: Buuntu owner_html_url: https://github.com/Buuntu -- name: nextpy - html_url: https://github.com/dot-agent/nextpy - stars: 2256 - owner_login: dot-agent - owner_html_url: https://github.com/dot-agent -- name: 30-Days-of-Python - html_url: https://github.com/codingforentrepreneurs/30-Days-of-Python - stars: 2155 - owner_login: codingforentrepreneurs - owner_html_url: https://github.com/codingforentrepreneurs - name: FastAPI-template html_url: https://github.com/s3rius/FastAPI-template - stars: 2121 + stars: 2301 owner_login: s3rius owner_html_url: https://github.com/s3rius +- name: nextpy + html_url: https://github.com/dot-agent/nextpy + stars: 2289 + owner_login: dot-agent + owner_html_url: https://github.com/dot-agent - name: sqladmin html_url: https://github.com/aminalaee/sqladmin - stars: 2021 + stars: 2196 owner_login: aminalaee owner_html_url: https://github.com/aminalaee +- name: 30-Days-of-Python + html_url: https://github.com/codingforentrepreneurs/30-Days-of-Python + stars: 2179 + owner_login: codingforentrepreneurs + owner_html_url: https://github.com/codingforentrepreneurs - name: langserve html_url: https://github.com/langchain-ai/langserve - stars: 2006 + stars: 2098 owner_login: langchain-ai owner_html_url: https://github.com/langchain-ai - name: fastapi-utils html_url: https://github.com/fastapiutils/fastapi-utils - stars: 2002 + stars: 2077 owner_login: fastapiutils owner_html_url: https://github.com/fastapiutils -- name: solara - html_url: https://github.com/widgetti/solara - stars: 1967 - owner_login: widgetti - owner_html_url: https://github.com/widgetti - name: supabase-py html_url: https://github.com/supabase/supabase-py - stars: 1848 + stars: 2047 owner_login: supabase owner_html_url: https://github.com/supabase -- name: python-week-2022 - html_url: https://github.com/rochacbruno/python-week-2022 - stars: 1832 - owner_login: rochacbruno - owner_html_url: https://github.com/rochacbruno +- name: solara + html_url: https://github.com/widgetti/solara + stars: 2044 + owner_login: widgetti + owner_html_url: https://github.com/widgetti - name: mangum html_url: https://github.com/Kludex/mangum - stars: 1789 + stars: 1905 owner_login: Kludex owner_html_url: https://github.com/Kludex +- name: python-week-2022 + html_url: https://github.com/rochacbruno/python-week-2022 + stars: 1823 + owner_login: rochacbruno + owner_html_url: https://github.com/rochacbruno - name: manage-fastapi html_url: https://github.com/ycd/manage-fastapi - stars: 1711 + stars: 1754 owner_login: ycd owner_html_url: https://github.com/ycd -- name: ormar - html_url: https://github.com/collerek/ormar - stars: 1701 - owner_login: collerek - owner_html_url: https://github.com/collerek - name: agentkit html_url: https://github.com/BCG-X-Official/agentkit - stars: 1630 + stars: 1746 owner_login: BCG-X-Official owner_html_url: https://github.com/BCG-X-Official +- name: ormar + html_url: https://github.com/collerek/ormar + stars: 1742 + owner_login: collerek + owner_html_url: https://github.com/collerek - name: langchain-serve html_url: https://github.com/jina-ai/langchain-serve - stars: 1617 + stars: 1630 owner_login: jina-ai owner_html_url: https://github.com/jina-ai - name: termpair html_url: https://github.com/cs01/termpair - stars: 1612 + stars: 1611 owner_login: cs01 owner_html_url: https://github.com/cs01 -- name: coronavirus-tracker-api - html_url: https://github.com/ExpDev07/coronavirus-tracker-api - stars: 1590 - owner_login: ExpDev07 - owner_html_url: https://github.com/ExpDev07 - name: piccolo html_url: https://github.com/piccolo-orm/piccolo - stars: 1519 + stars: 1609 owner_login: piccolo-orm owner_html_url: https://github.com/piccolo-orm -- name: fastapi-crudrouter - html_url: https://github.com/awtkns/fastapi-crudrouter - stars: 1449 - owner_login: awtkns - owner_html_url: https://github.com/awtkns +- name: coronavirus-tracker-api + html_url: https://github.com/ExpDev07/coronavirus-tracker-api + stars: 1587 + owner_login: ExpDev07 + owner_html_url: https://github.com/ExpDev07 - name: fastapi-cache html_url: https://github.com/long2ice/fastapi-cache - stars: 1447 + stars: 1575 owner_login: long2ice owner_html_url: https://github.com/long2ice - name: openapi-python-client html_url: https://github.com/openapi-generators/openapi-python-client - stars: 1434 + stars: 1568 owner_login: openapi-generators owner_html_url: https://github.com/openapi-generators +- name: fastapi-crudrouter + html_url: https://github.com/awtkns/fastapi-crudrouter + stars: 1508 + owner_login: awtkns + owner_html_url: https://github.com/awtkns +- name: slowapi + html_url: https://github.com/laurentS/slowapi + stars: 1501 + owner_login: laurentS + owner_html_url: https://github.com/laurentS - name: awesome-fastapi-projects html_url: https://github.com/Kludex/awesome-fastapi-projects - stars: 1398 + stars: 1453 owner_login: Kludex owner_html_url: https://github.com/Kludex - name: awesome-python-resources html_url: https://github.com/DjangoEx/awesome-python-resources - stars: 1380 + stars: 1390 owner_login: DjangoEx owner_html_url: https://github.com/DjangoEx -- name: budgetml - html_url: https://github.com/ebhy/budgetml - stars: 1344 - owner_login: ebhy - owner_html_url: https://github.com/ebhy -- name: slowapi - html_url: https://github.com/laurentS/slowapi - stars: 1339 - owner_login: laurentS - owner_html_url: https://github.com/laurentS - name: fastapi-pagination html_url: https://github.com/uriyyo/fastapi-pagination - stars: 1263 + stars: 1353 owner_login: uriyyo owner_html_url: https://github.com/uriyyo +- name: budgetml + html_url: https://github.com/ebhy/budgetml + stars: 1342 + owner_login: ebhy + owner_html_url: https://github.com/ebhy - name: fastapi-boilerplate html_url: https://github.com/teamhide/fastapi-boilerplate - stars: 1206 + stars: 1325 owner_login: teamhide owner_html_url: https://github.com/teamhide -- name: fastapi-tutorial - html_url: https://github.com/liaogx/fastapi-tutorial - stars: 1178 - owner_login: liaogx - owner_html_url: https://github.com/liaogx +- name: vue-fastapi-admin + html_url: https://github.com/mizhexiaoxiao/vue-fastapi-admin + stars: 1306 + owner_login: mizhexiaoxiao + owner_html_url: https://github.com/mizhexiaoxiao - name: fastapi-amis-admin html_url: https://github.com/amisadmin/fastapi-amis-admin - stars: 1142 + stars: 1256 owner_login: amisadmin owner_html_url: https://github.com/amisadmin +- name: fastapi-tutorial + html_url: https://github.com/liaogx/fastapi-tutorial + stars: 1245 + owner_login: liaogx + owner_html_url: https://github.com/liaogx - name: fastapi-code-generator html_url: https://github.com/koxudaxi/fastapi-code-generator - stars: 1119 + stars: 1201 owner_login: koxudaxi owner_html_url: https://github.com/koxudaxi +- name: bracket + html_url: https://github.com/evroon/bracket + stars: 1201 + owner_login: evroon + owner_html_url: https://github.com/evroon - name: bolt-python html_url: https://github.com/slackapi/bolt-python - stars: 1116 + stars: 1179 owner_login: slackapi owner_html_url: https://github.com/slackapi -- name: odmantic - html_url: https://github.com/art049/odmantic - stars: 1096 - owner_login: art049 - owner_html_url: https://github.com/art049 -- name: langchain-extract - html_url: https://github.com/langchain-ai/langchain-extract - stars: 1093 - owner_login: langchain-ai - owner_html_url: https://github.com/langchain-ai - name: fastapi_production_template html_url: https://github.com/zhanymkanov/fastapi_production_template - stars: 1078 + stars: 1147 owner_login: zhanymkanov owner_html_url: https://github.com/zhanymkanov -- name: fastapi-alembic-sqlmodel-async - html_url: https://github.com/jonra1993/fastapi-alembic-sqlmodel-async - stars: 1055 - owner_login: jonra1993 - owner_html_url: https://github.com/jonra1993 -- name: Kokoro-FastAPI - html_url: https://github.com/remsky/Kokoro-FastAPI - stars: 1047 - owner_login: remsky - owner_html_url: https://github.com/remsky - name: prometheus-fastapi-instrumentator html_url: https://github.com/trallnag/prometheus-fastapi-instrumentator - stars: 1036 + stars: 1145 owner_login: trallnag owner_html_url: https://github.com/trallnag -- name: SurfSense - html_url: https://github.com/MODSetter/SurfSense - stars: 1018 - owner_login: MODSetter - owner_html_url: https://github.com/MODSetter -- name: bedrock-claude-chat - html_url: https://github.com/aws-samples/bedrock-claude-chat - stars: 1010 +- name: bedrock-chat + html_url: https://github.com/aws-samples/bedrock-chat + stars: 1143 owner_login: aws-samples owner_html_url: https://github.com/aws-samples +- name: langchain-extract + html_url: https://github.com/langchain-ai/langchain-extract + stars: 1134 + owner_login: langchain-ai + owner_html_url: https://github.com/langchain-ai +- name: odmantic + html_url: https://github.com/art049/odmantic + stars: 1118 + owner_login: art049 + owner_html_url: https://github.com/art049 +- name: fastapi-alembic-sqlmodel-async + html_url: https://github.com/jonra1993/fastapi-alembic-sqlmodel-async + stars: 1110 + owner_login: jonra1993 + owner_html_url: https://github.com/jonra1993 +- name: fastcrud + html_url: https://github.com/benavlabs/fastcrud + stars: 1080 + owner_login: benavlabs + owner_html_url: https://github.com/benavlabs +- name: restish + html_url: https://github.com/rest-sh/restish + stars: 1056 + owner_login: rest-sh + owner_html_url: https://github.com/rest-sh +- name: fastapi_best_architecture + html_url: https://github.com/fastapi-practices/fastapi_best_architecture + stars: 1050 + owner_login: fastapi-practices + owner_html_url: https://github.com/fastapi-practices - name: runhouse html_url: https://github.com/run-house/runhouse - stars: 1000 + stars: 1034 owner_login: run-house owner_html_url: https://github.com/run-house -- name: lanarky - html_url: https://github.com/ajndkr/lanarky - stars: 986 - owner_login: ajndkr - owner_html_url: https://github.com/ajndkr - name: autollm html_url: https://github.com/viddexa/autollm - stars: 982 + stars: 992 owner_login: viddexa owner_html_url: https://github.com/viddexa -- name: restish - html_url: https://github.com/danielgtaylor/restish - stars: 970 - owner_login: danielgtaylor - owner_html_url: https://github.com/danielgtaylor -- name: fastcrud - html_url: https://github.com/igorbenav/fastcrud - stars: 929 - owner_login: igorbenav - owner_html_url: https://github.com/igorbenav +- name: lanarky + html_url: https://github.com/ajndkr/lanarky + stars: 990 + owner_login: ajndkr + owner_html_url: https://github.com/ajndkr +- name: FastAPI-boilerplate + html_url: https://github.com/benavlabs/FastAPI-boilerplate + stars: 985 + owner_login: benavlabs + owner_html_url: https://github.com/benavlabs +- name: authx + html_url: https://github.com/yezz123/authx + stars: 938 + owner_login: yezz123 + owner_html_url: https://github.com/yezz123 - name: secure html_url: https://github.com/TypeError/secure - stars: 921 + stars: 935 owner_login: TypeError owner_html_url: https://github.com/TypeError - name: langcorn html_url: https://github.com/msoedov/langcorn - stars: 915 + stars: 925 owner_login: msoedov owner_html_url: https://github.com/msoedov -- name: vue-fastapi-admin - html_url: https://github.com/mizhexiaoxiao/vue-fastapi-admin - stars: 915 - owner_login: mizhexiaoxiao - owner_html_url: https://github.com/mizhexiaoxiao - name: energy-forecasting html_url: https://github.com/iusztinpaul/energy-forecasting - stars: 891 + stars: 913 owner_login: iusztinpaul owner_html_url: https://github.com/iusztinpaul -- name: authx - html_url: https://github.com/yezz123/authx - stars: 862 - owner_login: yezz123 - owner_html_url: https://github.com/yezz123 - name: titiler html_url: https://github.com/developmentseed/titiler - stars: 823 + stars: 886 owner_login: developmentseed owner_html_url: https://github.com/developmentseed +- name: flock + html_url: https://github.com/Onelevenvy/flock + stars: 866 + owner_login: Onelevenvy + owner_html_url: https://github.com/Onelevenvy +- name: httpdbg + html_url: https://github.com/cle-b/httpdbg + stars: 863 + owner_login: cle-b + owner_html_url: https://github.com/cle-b - name: marker-api html_url: https://github.com/adithya-s-k/marker-api - stars: 798 + stars: 859 owner_login: adithya-s-k owner_html_url: https://github.com/adithya-s-k -- name: FastAPI-boilerplate - html_url: https://github.com/igorbenav/FastAPI-boilerplate - stars: 774 - owner_login: igorbenav - owner_html_url: https://github.com/igorbenav -- name: fastapi_best_architecture - html_url: https://github.com/fastapi-practices/fastapi_best_architecture - stars: 766 - owner_login: fastapi-practices - owner_html_url: https://github.com/fastapi-practices -- name: fastapi-mail - html_url: https://github.com/sabuhish/fastapi-mail - stars: 735 - owner_login: sabuhish - owner_html_url: https://github.com/sabuhish -- name: annotated-py-projects - html_url: https://github.com/hhstore/annotated-py-projects - stars: 725 - owner_login: hhstore - owner_html_url: https://github.com/hhstore +- name: ludic + html_url: https://github.com/getludic/ludic + stars: 845 + owner_login: getludic + owner_html_url: https://github.com/getludic - name: fastapi-do-zero html_url: https://github.com/dunossauro/fastapi-do-zero - stars: 723 + stars: 827 owner_login: dunossauro owner_html_url: https://github.com/dunossauro -- name: lccn_predictor - html_url: https://github.com/baoliay2008/lccn_predictor - stars: 718 - owner_login: baoliay2008 - owner_html_url: https://github.com/baoliay2008 - name: fastapi-observability html_url: https://github.com/blueswen/fastapi-observability - stars: 718 + stars: 823 owner_login: blueswen owner_html_url: https://github.com/blueswen -- name: chatGPT-web - html_url: https://github.com/mic1on/chatGPT-web - stars: 708 - owner_login: mic1on - owner_html_url: https://github.com/mic1on -- name: learn-generative-ai - html_url: https://github.com/panaverse/learn-generative-ai - stars: 701 - owner_login: panaverse - owner_html_url: https://github.com/panaverse -- name: linbing - html_url: https://github.com/taomujian/linbing - stars: 700 - owner_login: taomujian - owner_html_url: https://github.com/taomujian -- name: FastAPI-Backend-Template - html_url: https://github.com/Aeternalis-Ingenium/FastAPI-Backend-Template - stars: 692 - owner_login: Aeternalis-Ingenium - owner_html_url: https://github.com/Aeternalis-Ingenium +- name: fastapi-langgraph-agent-production-ready-template + html_url: https://github.com/wassim249/fastapi-langgraph-agent-production-ready-template + stars: 803 + owner_login: wassim249 + owner_html_url: https://github.com/wassim249 +- name: fastapi-mail + html_url: https://github.com/sabuhish/fastapi-mail + stars: 798 + owner_login: sabuhish + owner_html_url: https://github.com/sabuhish - name: starlette-admin html_url: https://github.com/jowilf/starlette-admin - stars: 692 + stars: 785 owner_login: jowilf owner_html_url: https://github.com/jowilf -- name: fastapi-jwt-auth - html_url: https://github.com/IndominusByte/fastapi-jwt-auth - stars: 674 - owner_login: IndominusByte - owner_html_url: https://github.com/IndominusByte -- name: pity - html_url: https://github.com/wuranxu/pity - stars: 663 - owner_login: wuranxu - owner_html_url: https://github.com/wuranxu -- name: fastapi_login - html_url: https://github.com/MushroomMaula/fastapi_login - stars: 656 - owner_login: MushroomMaula - owner_html_url: https://github.com/MushroomMaula +- name: lccn_predictor + html_url: https://github.com/baoliay2008/lccn_predictor + stars: 767 + owner_login: baoliay2008 + owner_html_url: https://github.com/baoliay2008 +- name: aktools + html_url: https://github.com/akfamily/aktools + stars: 759 + owner_login: akfamily + owner_html_url: https://github.com/akfamily +- name: KonomiTV + html_url: https://github.com/tsukumijima/KonomiTV + stars: 748 + owner_login: tsukumijima + owner_html_url: https://github.com/tsukumijima diff --git a/docs/en/data/translation_reviewers.yml b/docs/en/data/translation_reviewers.yml index 6f16893ba..aad3e4fac 100644 --- a/docs/en/data/translation_reviewers.yml +++ b/docs/en/data/translation_reviewers.yml @@ -8,9 +8,14 @@ Xewus: count: 140 avatarUrl: https://avatars.githubusercontent.com/u/85196001?u=f8e2dc7e5104f109cef944af79050ea8d1b8f914&v=4 url: https://github.com/Xewus +sodaMelon: + login: sodaMelon + count: 125 + avatarUrl: https://avatars.githubusercontent.com/u/66295123?u=be939db90f1119efee9e6110cc05066ff1f40f00&v=4 + url: https://github.com/sodaMelon ceb10n: login: ceb10n - count: 110 + count: 112 avatarUrl: https://avatars.githubusercontent.com/u/235213?u=edcce471814a1eba9f0cdaa4cd0de18921a940a6&v=4 url: https://github.com/ceb10n tokusumi: @@ -28,31 +33,26 @@ hard-coders: count: 92 avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=95db33927bbff1ed1c07efddeb97ac2ff33068ed&v=4 url: https://github.com/hard-coders -AlertRED: - login: AlertRED - count: 81 - avatarUrl: https://avatars.githubusercontent.com/u/15695000?u=f5a4944c6df443030409c88da7d7fa0b7ead985c&v=4 - url: https://github.com/AlertRED +alv2017: + login: alv2017 + count: 88 + avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 + url: https://github.com/alv2017 nazarepiedady: login: nazarepiedady - count: 81 + count: 83 avatarUrl: https://avatars.githubusercontent.com/u/31008635?u=8dc25777dc9cb51fb0dbba2f137988953d330b78&v=4 url: https://github.com/nazarepiedady -sodaMelon: - login: sodaMelon +AlertRED: + login: AlertRED count: 81 - avatarUrl: https://avatars.githubusercontent.com/u/66295123?u=be939db90f1119efee9e6110cc05066ff1f40f00&v=4 - url: https://github.com/sodaMelon + avatarUrl: https://avatars.githubusercontent.com/u/15695000?u=f5a4944c6df443030409c88da7d7fa0b7ead985c&v=4 + url: https://github.com/AlertRED Alexandrhub: login: Alexandrhub count: 68 avatarUrl: https://avatars.githubusercontent.com/u/119126536?u=9fc0d48f3307817bafecc5861eb2168401a6cb04&v=4 url: https://github.com/Alexandrhub -alv2017: - login: alv2017 - count: 64 - avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 - url: https://github.com/alv2017 waynerv: login: waynerv count: 63 @@ -65,9 +65,14 @@ cassiobotaro: url: https://github.com/cassiobotaro mattwang44: login: mattwang44 - count: 58 + count: 59 avatarUrl: https://avatars.githubusercontent.com/u/24987826?u=58e37fb3927b9124b458945ac4c97aa0f1062d85&v=4 url: https://github.com/mattwang44 +tiangolo: + login: tiangolo + count: 52 + avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4 + url: https://github.com/tiangolo Laineyzhang55: login: Laineyzhang55 count: 48 @@ -83,16 +88,26 @@ komtaki: count: 45 avatarUrl: https://avatars.githubusercontent.com/u/39375566?u=260ad6b1a4b34c07dbfa728da5e586f16f6d1824&v=4 url: https://github.com/komtaki +rostik1410: + login: rostik1410 + count: 42 + avatarUrl: https://avatars.githubusercontent.com/u/11443899?u=e26a635c2ba220467b308a326a579b8ccf4a8701&v=4 + url: https://github.com/rostik1410 +svlandeg: + login: svlandeg + count: 42 + avatarUrl: https://avatars.githubusercontent.com/u/8796347?u=556c97650c27021911b0b9447ec55e75987b0e8a&v=4 + url: https://github.com/svlandeg alperiox: login: alperiox count: 42 avatarUrl: https://avatars.githubusercontent.com/u/34214152?u=2c5acad3461d4dbc2d48371ba86cac56ae9b25cc&v=4 url: https://github.com/alperiox -tiangolo: - login: tiangolo - count: 40 - avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=cb5d06e73a9e1998141b1641aa88e443c6717651&v=4 - url: https://github.com/tiangolo +Rishat-F: + login: Rishat-F + count: 42 + avatarUrl: https://avatars.githubusercontent.com/u/66554797?v=4 + url: https://github.com/Rishat-F Winand: login: Winand count: 40 @@ -118,6 +133,16 @@ SwftAlpc: count: 36 avatarUrl: https://avatars.githubusercontent.com/u/52768429?u=6a3aa15277406520ad37f6236e89466ed44bc5b8&v=4 url: https://github.com/SwftAlpc +alejsdev: + login: alejsdev + count: 36 + avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=638c65283ac9e9e2c3a0f9d1e3370db4b8a2c58d&v=4 + url: https://github.com/alejsdev +timothy-jeong: + login: timothy-jeong + count: 36 + avatarUrl: https://avatars.githubusercontent.com/u/53824764?u=db3d0cea2f5fab64d810113c5039a369699a2774&v=4 + url: https://github.com/timothy-jeong nilslindemann: login: nilslindemann count: 35 @@ -133,6 +158,11 @@ codingjenny: count: 34 avatarUrl: https://avatars.githubusercontent.com/u/103817302?u=3a042740dc0ff58615da0d8679230966fd7693e8&v=4 url: https://github.com/codingjenny +mezgoodle: + login: mezgoodle + count: 33 + avatarUrl: https://avatars.githubusercontent.com/u/41520940?u=4a9c765af688389d54296845d18b8f6cd6ddf09a&v=4 + url: https://github.com/mezgoodle akarev0: login: akarev0 count: 33 @@ -143,21 +173,16 @@ romashevchenko: count: 32 avatarUrl: https://avatars.githubusercontent.com/u/132477732?v=4 url: https://github.com/romashevchenko -alejsdev: - login: alejsdev - count: 32 - avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=356f39ff3f0211c720b06d3dbb060e98884085e3&v=4 - url: https://github.com/alejsdev -wdh99: - login: wdh99 - count: 31 - avatarUrl: https://avatars.githubusercontent.com/u/108172295?u=8a8fb95d5afe3e0fa33257b2aecae88d436249eb&v=4 - url: https://github.com/wdh99 LorhanSohaky: login: LorhanSohaky count: 30 avatarUrl: https://avatars.githubusercontent.com/u/16273730?u=095b66f243a2cd6a0aadba9a095009f8aaf18393&v=4 url: https://github.com/LorhanSohaky +Vincy1230: + login: Vincy1230 + count: 30 + avatarUrl: https://avatars.githubusercontent.com/u/81342412?u=ab5e256a4077a4a91f3f9cd2115ba80780454cbe&v=4 + url: https://github.com/Vincy1230 black-redoc: login: black-redoc count: 29 @@ -181,7 +206,7 @@ dedkot01: hsuanchi: login: hsuanchi count: 28 - avatarUrl: https://avatars.githubusercontent.com/u/24913710?u=0b094ae292292fee093818e37ceb645c114d2bff&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/24913710?u=7d25a398e478b6e63503bf6f26c54efa9e0da07b&v=4 url: https://github.com/hsuanchi dpinezich: login: dpinezich @@ -208,11 +233,6 @@ junah201: count: 26 avatarUrl: https://avatars.githubusercontent.com/u/75025529?u=2451c256e888fa2a06bcfc0646d09b87ddb6a945&v=4 url: https://github.com/junah201 -Vincy1230: - login: Vincy1230 - count: 26 - avatarUrl: https://avatars.githubusercontent.com/u/81342412?u=ab5e256a4077a4a91f3f9cd2115ba80780454cbe&v=4 - url: https://github.com/Vincy1230 zy7y: login: zy7y count: 25 @@ -228,6 +248,11 @@ Aruelius: count: 24 avatarUrl: https://avatars.githubusercontent.com/u/25380989?u=574f8cfcda3ea77a3f81884f6b26a97068e36a9d&v=4 url: https://github.com/Aruelius +wisderfin: + login: wisderfin + count: 24 + avatarUrl: https://avatars.githubusercontent.com/u/77553770?u=9a23740d520d65dc0051cdc1ecd87f31cb900313&v=4 + url: https://github.com/wisderfin OzgunCaglarArslan: login: OzgunCaglarArslan count: 24 @@ -243,16 +268,6 @@ axel584: count: 23 avatarUrl: https://avatars.githubusercontent.com/u/1334088?u=9667041f5b15dc002b6f9665fda8c0412933ac04&v=4 url: https://github.com/axel584 -wisderfin: - login: wisderfin - count: 23 - avatarUrl: https://avatars.githubusercontent.com/u/77553770?u=f3b00a26736ba664e9927a1116c6e8088295e073&v=4 - url: https://github.com/wisderfin -rostik1410: - login: rostik1410 - count: 22 - avatarUrl: https://avatars.githubusercontent.com/u/11443899?u=e26a635c2ba220467b308a326a579b8ccf4a8701&v=4 - url: https://github.com/rostik1410 AGolicyn: login: AGolicyn count: 21 @@ -266,7 +281,7 @@ Attsun1031: ycd: login: ycd count: 20 - avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=29682e4b6ac7d5293742ccf818188394b9a82972&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=f1e7bae394a315da950912c92dc861a8eaf95d4c&v=4 url: https://github.com/ycd delhi09: login: delhi09 @@ -283,26 +298,21 @@ DevDae: count: 20 avatarUrl: https://avatars.githubusercontent.com/u/87962045?u=08e10fa516e844934f4b3fc7c38b33c61697e4a1&v=4 url: https://github.com/DevDae -svlandeg: - login: svlandeg - count: 20 - avatarUrl: https://avatars.githubusercontent.com/u/8796347?u=556c97650c27021911b0b9447ec55e75987b0e8a&v=4 - url: https://github.com/svlandeg sattosan: login: sattosan count: 19 avatarUrl: https://avatars.githubusercontent.com/u/20574756?u=b0d8474d2938189c6954423ae8d81d91013f80a8&v=4 url: https://github.com/sattosan +yes0ng: + login: yes0ng + count: 19 + avatarUrl: https://avatars.githubusercontent.com/u/25501794?u=3aed18b0d491e0220a167a1e9e58bea3638c6707&v=4 + url: https://github.com/yes0ng ComicShrimp: login: ComicShrimp count: 18 avatarUrl: https://avatars.githubusercontent.com/u/43503750?u=d2fbf412e7730183ce91686ca48d4147e1b7dc74&v=4 url: https://github.com/ComicShrimp -mezgoodle: - login: mezgoodle - count: 18 - avatarUrl: https://avatars.githubusercontent.com/u/41520940?u=e871bc26734eb2436d98c19c3fb57a4773e13c24&v=4 - url: https://github.com/mezgoodle simatheone: login: simatheone count: 18 @@ -313,6 +323,11 @@ ivan-abc: count: 18 avatarUrl: https://avatars.githubusercontent.com/u/36765187?u=c6e0ba571c1ccb6db9d94e62e4b8b5eda811a870&v=4 url: https://github.com/ivan-abc +Limsunoh: + login: Limsunoh + count: 18 + avatarUrl: https://avatars.githubusercontent.com/u/90311848?u=f456e0c5709fd50c8cd2898b551558eda14e5f21&v=4 + url: https://github.com/Limsunoh bezaca: login: bezaca count: 17 @@ -338,11 +353,6 @@ jeison-araya: count: 17 avatarUrl: https://avatars.githubusercontent.com/u/57369279?u=17001e68af7d8e5b8c343e5e9df4050f419998d5&v=4 url: https://github.com/jeison-araya -Limsunoh: - login: Limsunoh - count: 17 - avatarUrl: https://avatars.githubusercontent.com/u/90311848?u=f456e0c5709fd50c8cd2898b551558eda14e5f21&v=4 - url: https://github.com/Limsunoh yanever: login: yanever count: 16 @@ -361,8 +371,13 @@ Joao-Pedro-P-Holanda: JaeHyuckSa: login: JaeHyuckSa count: 16 - avatarUrl: https://avatars.githubusercontent.com/u/104830931?v=4 + avatarUrl: https://avatars.githubusercontent.com/u/104830931?u=6e352201714a05154e5d0ccf91b4715a951c622e&v=4 url: https://github.com/JaeHyuckSa +SofiiaTrufanova: + login: SofiiaTrufanova + count: 16 + avatarUrl: https://avatars.githubusercontent.com/u/63260929?u=483e0b64fabc76343b3be39b7e1dcb930a95e1bb&v=4 + url: https://github.com/SofiiaTrufanova Jedore: login: Jedore count: 15 @@ -373,6 +388,11 @@ kim-sangah: count: 15 avatarUrl: https://avatars.githubusercontent.com/u/173775778?v=4 url: https://github.com/kim-sangah +DianaTrufanova: + login: DianaTrufanova + count: 15 + avatarUrl: https://avatars.githubusercontent.com/u/119067607?u=1cd55f841b68b4a187fa6d06a7dafa5f070195aa&v=4 + url: https://github.com/DianaTrufanova PandaHun: login: PandaHun count: 14 @@ -383,11 +403,6 @@ dukkee: count: 14 avatarUrl: https://avatars.githubusercontent.com/u/36825394?u=ccfd86e6a4f2d093dad6f7544cc875af67fa2df8&v=4 url: https://github.com/dukkee -mkdir700: - login: mkdir700 - count: 14 - avatarUrl: https://avatars.githubusercontent.com/u/56359329?u=3d6ea8714f5000829b60dcf7b13a75b1e73aaf47&v=4 - url: https://github.com/mkdir700 BORA040126: login: BORA040126 count: 14 @@ -396,7 +411,7 @@ BORA040126: mattkoehne: login: mattkoehne count: 14 - avatarUrl: https://avatars.githubusercontent.com/u/80362153?u=6e1439582715693407b86182eb66263bb578a761&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/80362153?v=4 url: https://github.com/mattkoehne jovicon: login: jovicon @@ -438,16 +453,16 @@ oandersonmagalhaes: count: 12 avatarUrl: https://avatars.githubusercontent.com/u/83456692?v=4 url: https://github.com/oandersonmagalhaes +mkdir700: + login: mkdir700 + count: 12 + avatarUrl: https://avatars.githubusercontent.com/u/56359329?u=3d6ea8714f5000829b60dcf7b13a75b1e73aaf47&v=4 + url: https://github.com/mkdir700 batlopes: login: batlopes count: 12 avatarUrl: https://avatars.githubusercontent.com/u/33462923?u=0fb3d7acb316764616f11e4947faf080e49ad8d9&v=4 url: https://github.com/batlopes -Lenclove: - login: Lenclove - count: 12 - avatarUrl: https://avatars.githubusercontent.com/u/32355298?u=d0065e01650c63c2b2413f42d983634b2ea85481&v=4 - url: https://github.com/Lenclove joonas-yoon: login: joonas-yoon count: 12 @@ -468,16 +483,16 @@ andersonrocha0: count: 12 avatarUrl: https://avatars.githubusercontent.com/u/22346169?u=93a1359c8c5461d894802c0cc65bcd09217e7a02&v=4 url: https://github.com/andersonrocha0 +gitgernit: + login: gitgernit + count: 12 + avatarUrl: https://avatars.githubusercontent.com/u/129539613?u=d04f10143ab32c93f563ea14bf242d1d2bc991b0&v=4 + url: https://github.com/gitgernit kwang1215: login: kwang1215 count: 12 avatarUrl: https://avatars.githubusercontent.com/u/74170199?u=2a63ff6692119dde3f5e5693365b9fcd6f977b08&v=4 url: https://github.com/kwang1215 -Rishat-F: - login: Rishat-F - count: 12 - avatarUrl: https://avatars.githubusercontent.com/u/66554797?v=4 - url: https://github.com/Rishat-F AdrianDeAnda: login: AdrianDeAnda count: 11 @@ -498,6 +513,11 @@ glsglsgls: count: 11 avatarUrl: https://avatars.githubusercontent.com/u/76133879?v=4 url: https://github.com/glsglsgls +k94-ishi: + login: k94-ishi + count: 11 + avatarUrl: https://avatars.githubusercontent.com/u/32672580?u=bc7c5c07af0656be9fe4f1784a444af8d81ded89&v=4 + url: https://github.com/k94-ishi codespearhead: login: codespearhead count: 11 @@ -518,11 +538,6 @@ KNChiu: count: 11 avatarUrl: https://avatars.githubusercontent.com/u/36751646?v=4 url: https://github.com/KNChiu -gitgernit: - login: gitgernit - count: 11 - avatarUrl: https://avatars.githubusercontent.com/u/129539613?u=d04f10143ab32c93f563ea14bf242d1d2bc991b0&v=4 - url: https://github.com/gitgernit mariacamilagl: login: mariacamilagl count: 10 @@ -586,7 +601,7 @@ waketzheng: lucasbalieiro: login: lucasbalieiro count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/37416577?u=5a395a69384e7fa0f9840ea32ef963d3f1cd9da4&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/37416577?u=eabaf4aebbaa88a94a4886273edba689012cee70&v=4 url: https://github.com/lucasbalieiro RunningIkkyu: login: RunningIkkyu @@ -601,18 +616,18 @@ JulianMaurin: JeongHyeongKim: login: JeongHyeongKim count: 9 - avatarUrl: https://avatars.githubusercontent.com/u/26577800?u=fe653349051c0acf62cd984e74c4ff60ca8d2cb6&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/26577800?u=77f060f4686f32c248907b81b16ee2b3177ca44c&v=4 url: https://github.com/JeongHyeongKim arthurio: login: arthurio count: 9 avatarUrl: https://avatars.githubusercontent.com/u/950449?u=76b997138273ce5e1990b971c4f27c9aff979fd5&v=4 url: https://github.com/arthurio -mahone3297: - login: mahone3297 +Lenclove: + login: Lenclove count: 9 - avatarUrl: https://avatars.githubusercontent.com/u/1701379?u=20588ff0e456d13e8017333eb237595d11410234&v=4 - url: https://github.com/mahone3297 + avatarUrl: https://avatars.githubusercontent.com/u/32355298?u=d0065e01650c63c2b2413f42d983634b2ea85481&v=4 + url: https://github.com/Lenclove eVery1337: login: eVery1337 count: 9 @@ -628,6 +643,11 @@ riroan: count: 9 avatarUrl: https://avatars.githubusercontent.com/u/33053284?u=2d18e3771506ee874b66d6aa2b3b1107fd95c38f&v=4 url: https://github.com/riroan +MinLee0210: + login: MinLee0210 + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/57653278?u=3c4b6e9d69bff148d09fe022ddf867e564acaa44&v=4 + url: https://github.com/MinLee0210 yodai-yodai: login: yodai-yodai count: 9 @@ -648,6 +668,11 @@ Zhongheng-Cheng: count: 9 avatarUrl: https://avatars.githubusercontent.com/u/95612344?u=a0f7730a3cc7486827965e01a119ad610bda4b0a&v=4 url: https://github.com/Zhongheng-Cheng +Yarous: + login: Yarous + count: 9 + avatarUrl: https://avatars.githubusercontent.com/u/61277193?u=5b462347458a373b2d599c6f416d2b75eddbffad&v=4 + url: https://github.com/Yarous dimaqq: login: dimaqq count: 8 @@ -663,11 +688,6 @@ bnzone: count: 8 avatarUrl: https://avatars.githubusercontent.com/u/39371503?u=c16f00c41d88479fa2d57b0d7d233b758eacce2d&v=4 url: https://github.com/bnzone -ChuyuChoyeon: - login: ChuyuChoyeon - count: 8 - avatarUrl: https://avatars.githubusercontent.com/u/129537877?u=f0c76f3327817a8b86b422d62e04a34bf2827f2b&v=4 - url: https://github.com/ChuyuChoyeon shamosishen: login: shamosishen count: 8 @@ -678,6 +698,11 @@ mertssmnoglu: count: 8 avatarUrl: https://avatars.githubusercontent.com/u/61623638?u=59dd885b68ff1832f9ab3b4a4446896358c23442&v=4 url: https://github.com/mertssmnoglu +mahone3297: + login: mahone3297 + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/1701379?u=20588ff0e456d13e8017333eb237595d11410234&v=4 + url: https://github.com/mahone3297 KimJoonSeo: login: KimJoonSeo count: 8 @@ -688,6 +713,21 @@ camigomezdev: count: 8 avatarUrl: https://avatars.githubusercontent.com/u/16061815?u=25b5ebc042fff53fa03dc107ded10e36b1b7a5b9&v=4 url: https://github.com/camigomezdev +maru0123-2004: + login: maru0123-2004 + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/43961566?u=16ed8603a4d6a4665cb6c53a7aece6f31379b769&v=4 + url: https://github.com/maru0123-2004 +minaton-ru: + login: minaton-ru + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/53541518?u=67336ca11a85493f75031508aade588dad3b9910&v=4 + url: https://github.com/minaton-ru +sungchan1: + login: sungchan1 + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/28076127?u=a816d86ef3e60450a7225f128caf9a394c9320f9&v=4 + url: https://github.com/sungchan1 Serrones: login: Serrones count: 7 @@ -733,6 +773,11 @@ d2a-raudenaerde: count: 7 avatarUrl: https://avatars.githubusercontent.com/u/5213150?v=4 url: https://github.com/d2a-raudenaerde +Zerohertz: + login: Zerohertz + count: 7 + avatarUrl: https://avatars.githubusercontent.com/u/42334717?u=5ebf4d33e73b1ad373154f6cdee44f7cab4d05ba&v=4 + url: https://github.com/Zerohertz deniscapeto: login: deniscapeto count: 6 @@ -808,11 +853,6 @@ Kirilex: count: 6 avatarUrl: https://avatars.githubusercontent.com/u/100281552?v=4 url: https://github.com/Kirilex -Mordson: - login: Mordson - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/39025897?u=b94ea96ef35bbe43bc85359cfb31d28ac16d470c&v=4 - url: https://github.com/Mordson arunppsg: login: arunppsg count: 6 @@ -823,11 +863,6 @@ dimastbk: count: 6 avatarUrl: https://avatars.githubusercontent.com/u/3132181?u=66587398d43466a1dc75c238df5f048e0afc77ed&v=4 url: https://github.com/dimastbk -lordqyxz: - login: lordqyxz - count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/31722468?u=974553c0ba53526d9be7e9876544283291be3b0d&v=4 - url: https://github.com/lordqyxz dudyaosuplayer: login: dudyaosuplayer count: 6 @@ -843,6 +878,11 @@ bankofsardine: count: 6 avatarUrl: https://avatars.githubusercontent.com/u/44944207?u=0368e1b698ffab6bf29e202f9fd2dddd352429f1&v=4 url: https://github.com/bankofsardine +valentinDruzhinin: + login: valentinDruzhinin + count: 6 + avatarUrl: https://avatars.githubusercontent.com/u/12831905?u=aae1ebc675c91e8fa582df4fcc4fc4128106344d&v=4 + url: https://github.com/valentinDruzhinin rsip22: login: rsip22 count: 5 @@ -856,7 +896,7 @@ jessicapaz: mohsen-mahmoodi: login: mohsen-mahmoodi count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/2872586?u=9274b3b13d8a992dba29b162fee48473a0fa142d&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/2872586?u=3a9fc1aa16a3a0ab93a1f8550de82a940592857d&v=4 url: https://github.com/mohsen-mahmoodi jeesang7: login: jeesang7 @@ -871,7 +911,7 @@ TemaSpb: BugLight: login: BugLight count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/13618366?u=57572e544e40c2a491db5bf7255bd24886d2cb09&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/13618366?u=7d733749f80e5f7e66a434cf42aedcfc60340f43&v=4 url: https://github.com/BugLight 0x4Dark: login: 0x4Dark @@ -886,13 +926,18 @@ Wuerike: jvmazagao: login: jvmazagao count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/22477816?u=f3b2d503b53e6ec8c808f0601b756a063a07f06e&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/22477816?u=2b57addf5830906bf6ae5f25cd4c8c2fa5c2d68e&v=4 url: https://github.com/jvmazagao cun3yt: login: cun3yt count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/24409240?u=39f651cdcc4991fb9fef5bbd9e9503db2174ac13&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/24409240?u=06abfd77786db859b0602d5369d2ae18c932c17c&v=4 url: https://github.com/cun3yt +Mordson: + login: Mordson + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/39025897?u=b94ea96ef35bbe43bc85359cfb31d28ac16d470c&v=4 + url: https://github.com/Mordson aminkhani: login: aminkhani count: 5 @@ -913,6 +958,11 @@ Chushine: count: 5 avatarUrl: https://avatars.githubusercontent.com/u/135534400?v=4 url: https://github.com/Chushine +ChuyuChoyeon: + login: ChuyuChoyeon + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/129537877?u=f0c76f3327817a8b86b422d62e04a34bf2827f2b&v=4 + url: https://github.com/ChuyuChoyeon frwl404: login: frwl404 count: 5 @@ -958,11 +1008,11 @@ devluisrodrigues: count: 5 avatarUrl: https://avatars.githubusercontent.com/u/103431660?u=d9674a3249edc4601d2c712cdebf899918503c3a&v=4 url: https://github.com/devluisrodrigues -timothy-jeong: - login: timothy-jeong +11kkw: + login: 11kkw count: 5 - avatarUrl: https://avatars.githubusercontent.com/u/53824764?u=db3d0cea2f5fab64d810113c5039a369699a2774&v=4 - url: https://github.com/timothy-jeong + avatarUrl: https://avatars.githubusercontent.com/u/21125286?v=4 + url: https://github.com/11kkw lpdswing: login: lpdswing count: 4 @@ -976,7 +1026,7 @@ SepehrRasouli: Zxilly: login: Zxilly count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/31370133?u=122e23d6e974614736be606e4ea816f45e7745f8&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/31370133?u=c5359b8d9d80a7cdc23d5295d179ed90174996c8&v=4 url: https://github.com/Zxilly eavv: login: eavv @@ -993,6 +1043,11 @@ FelipeSilva93: count: 4 avatarUrl: https://avatars.githubusercontent.com/u/66804965?u=e7cb4b580e46f2e04ecb4cd4d7a12acdddd3c6c1&v=4 url: https://github.com/FelipeSilva93 +peacekimjapan: + login: peacekimjapan + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/33534175?u=e4219bcebc3773a7068cc34c3eb268ef77cec31b&v=4 + url: https://github.com/peacekimjapan bas-baskara: login: bas-baskara count: 4 @@ -1016,18 +1071,23 @@ personage-hub: aminalaee: login: aminalaee count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/19784933?u=2f45a312b73e7fb29f3b6f8676e5be6f7220da25&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/19784933?v=4 url: https://github.com/aminalaee erfan-rfmhr: login: erfan-rfmhr count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/98986056?u=6c4f9218fe5bb04780dd92bfced360c55e2009f0&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/98986056?u=0acda1ff1df0989f3f3eb79977baa35da4cb6c8c&v=4 url: https://github.com/erfan-rfmhr Scorpionchiques: login: Scorpionchiques count: 4 avatarUrl: https://avatars.githubusercontent.com/u/15703294?v=4 url: https://github.com/Scorpionchiques +lordqyxz: + login: lordqyxz + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/31722468?u=974553c0ba53526d9be7e9876544283291be3b0d&v=4 + url: https://github.com/lordqyxz heysaeid: login: heysaeid count: 4 @@ -1058,11 +1118,11 @@ matiasbertani: count: 4 avatarUrl: https://avatars.githubusercontent.com/u/65260383?u=d5edd86a6e2ab4fb1aab7751931fe045a963afd7&v=4 url: https://github.com/matiasbertani -k94-ishi: - login: k94-ishi +thiennc254: + login: thiennc254 count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/32672580?u=bc7c5c07af0656be9fe4f1784a444af8d81ded89&v=4 - url: https://github.com/k94-ishi + avatarUrl: https://avatars.githubusercontent.com/u/97406628?u=1b2860679694b9a552764d0fa81dbd7a016322ec&v=4 + url: https://github.com/thiennc254 javillegasna: login: javillegasna count: 4 @@ -1078,11 +1138,16 @@ ilhamfadillah: count: 4 avatarUrl: https://avatars.githubusercontent.com/u/20577838?u=c56192cf99b55affcaad408b240259c62e633450&v=4 url: https://github.com/ilhamfadillah -Yarous: - login: Yarous +gerry-sabar: + login: gerry-sabar count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/61277193?u=5b462347458a373b2d599c6f416d2b75eddbffad&v=4 - url: https://github.com/Yarous + avatarUrl: https://avatars.githubusercontent.com/u/1120123?v=4 + url: https://github.com/gerry-sabar +cookie-byte217: + login: cookie-byte217 + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/57880178?v=4 + url: https://github.com/cookie-byte217 tyronedamasceno: login: tyronedamasceno count: 3 @@ -1161,7 +1226,7 @@ RuslanTer: FedorGN: login: FedorGN count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/66411909?u=1c6734e92f50c7d66f130ef7d394e72b53770fe6&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/66411909?u=22382380e7d66ee57ffbfc2ae6bd5efd0cdb672e&v=4 url: https://github.com/FedorGN rafsaf: login: rafsaf @@ -1283,6 +1348,11 @@ kohiry: count: 3 avatarUrl: https://avatars.githubusercontent.com/u/57669492?u=f6ab0a062740261e882879269a41a47788c84043&v=4 url: https://github.com/kohiry +ptt3199: + login: ptt3199 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/51350651?u=2c3d947a80283e32bf616d4c3af139a6be69680f&v=4 + url: https://github.com/ptt3199 arynoot: login: arynoot count: 3 @@ -1308,11 +1378,21 @@ RyaWcksn: count: 3 avatarUrl: https://avatars.githubusercontent.com/u/42831964?u=0cb4265faf3e3425a89e59b6fddd3eb2de180af0&v=4 url: https://github.com/RyaWcksn -gerry-sabar: - login: gerry-sabar +tienduong-21: + login: tienduong-21 count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/1120123?v=4 - url: https://github.com/gerry-sabar + avatarUrl: https://avatars.githubusercontent.com/u/80129618?v=4 + url: https://github.com/tienduong-21 +soroushgh1: + login: soroushgh1 + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/178516095?u=5e26f6a5f66cdb32d7b56e6ab362bf18ba7858b9&v=4 + url: https://github.com/soroushgh1 +zbellos: + login: zbellos + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/204500646?v=4 + url: https://github.com/zbellos blaisep: login: blaisep count: 2 @@ -1386,7 +1466,7 @@ TimorChow: ataberkciftlikli: login: ataberkciftlikli count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/64265169?v=4 + avatarUrl: https://avatars.githubusercontent.com/u/64265169?u=ca7c1348242559f70bc1dc027a4be277c464676f&v=4 url: https://github.com/ataberkciftlikli leandrodesouzadev: login: leandrodesouzadev @@ -1418,26 +1498,21 @@ lindsayzhou: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/26602940?u=3c52ce6393bb547c97e6380ccdee03e0c64152c6&v=4 url: https://github.com/0xflotus -peacekimjapan: - login: peacekimjapan - count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/33534175?u=e4219bcebc3773a7068cc34c3eb268ef77cec31b&v=4 - url: https://github.com/peacekimjapan jonatasoli: login: jonatasoli count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/26334101?u=071c062d2861d3dd127f6b4a5258cd8ef55d4c50&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/26334101?u=f601c3f111f2148bd9244c2cb3ebbd57b592e674&v=4 url: https://github.com/jonatasoli tyzh-dev: login: tyzh-dev count: 2 avatarUrl: https://avatars.githubusercontent.com/u/51972581?u=ba3882da7c009918a8e2d6b9ead31c89f09c922d&v=4 url: https://github.com/tyzh-dev -WaFeeAL: - login: WaFeeAL +yurkevich-dev: + login: yurkevich-dev count: 2 avatarUrl: https://avatars.githubusercontent.com/u/45145188?u=db2de8c186073d95693279dcf085fcebffab57d0&v=4 - url: https://github.com/WaFeeAL + url: https://github.com/yurkevich-dev emp7yhead: login: emp7yhead count: 2 @@ -1471,7 +1546,7 @@ felipebpl: iudeen: login: iudeen count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=f09cdd745e5bf16138f29b42732dd57c7f02bee1&v=4 url: https://github.com/iudeen dwisulfahnur: login: dwisulfahnur @@ -1491,7 +1566,7 @@ raphaelauv: Fahad-Md-Kamal: login: Fahad-Md-Kamal count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/34704464?u=84abea85e59c30b2e3bc700ae42424f3fe704332&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/34704464?u=f96c6cbd25b06274e3ff96bc961ca91b3f876481&v=4 url: https://github.com/Fahad-Md-Kamal zxcq544: login: zxcq544 @@ -1606,7 +1681,7 @@ zhiquanchi: Jamim: login: Jamim count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/5607572?u=0cf3027bec78ba4f0b89802430c136bc69847d7a&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/5607572?u=9ce0b6a6d1a5124e28b3c04d8d26827ca328713a&v=4 url: https://github.com/Jamim alvinkhalil: login: alvinkhalil @@ -1616,13 +1691,18 @@ alvinkhalil: leylaeminova: login: leylaeminova count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/100516839?u=35a9ce14bb86d7d7faa25d432f61dec2984cb818&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/100516839?u=0b0dab9e31742076b22812b14a39b4e6d8f6de4a&v=4 url: https://github.com/leylaeminova UN-9BOT: login: UN-9BOT count: 2 avatarUrl: https://avatars.githubusercontent.com/u/111110804?u=39e158937ed795972c2d0400fc521c50e9bfb9e7&v=4 url: https://github.com/UN-9BOT +flasonme: + login: flasonme + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/30571019?v=4 + url: https://github.com/flasonme gustavoprezoto: login: gustavoprezoto count: 2 @@ -1646,13 +1726,18 @@ ZhibangYue: saeye: login: saeye count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/62229734?v=4 + avatarUrl: https://avatars.githubusercontent.com/u/62229734?u=312d619db2588b60d5d5bde65260a2f44fdc6c76&v=4 url: https://github.com/saeye Heumhub: login: Heumhub count: 2 avatarUrl: https://avatars.githubusercontent.com/u/173761521?v=4 url: https://github.com/Heumhub +manumolina: + login: manumolina + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/2404208?u=fdc5502910f8dec814b2477f89587b9e45fac846&v=4 + url: https://github.com/manumolina logan2d5: login: logan2d5 count: 2 @@ -1668,3 +1753,33 @@ kiharito: count: 2 avatarUrl: https://avatars.githubusercontent.com/u/38311245?v=4 url: https://github.com/kiharito +J-Fuji: + login: J-Fuji + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/101452903?v=4 + url: https://github.com/J-Fuji +MrL8199: + login: MrL8199 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/39489075?u=3fc4f89c86973e40b5970d838c801bdbc13ac828&v=4 + url: https://github.com/MrL8199 +ivintoiu: + login: ivintoiu + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/1853336?u=5e3d0977f44661fb9712fa297cc8f7608ea6ce48&v=4 + url: https://github.com/ivintoiu +EgorOnishchuk: + login: EgorOnishchuk + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/120256301?v=4 + url: https://github.com/EgorOnishchuk +iamantonreznik: + login: iamantonreznik + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/112612414?u=bf6de9a1ab17326fe14de0709719fff3826526d0&v=4 + url: https://github.com/iamantonreznik +Azazul123: + login: Azazul123 + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/102759111?u=b48ce6e30a81a23467cc30e0c011bcc57f0326ab&v=4 + url: https://github.com/Azazul123 diff --git a/docs/en/data/translators.yml b/docs/en/data/translators.yml index 13859044d..51d05003b 100644 --- a/docs/en/data/translators.yml +++ b/docs/en/data/translators.yml @@ -10,9 +10,14 @@ jaystone776: url: https://github.com/jaystone776 ceb10n: login: ceb10n - count: 26 + count: 27 avatarUrl: https://avatars.githubusercontent.com/u/235213?u=edcce471814a1eba9f0cdaa4cd0de18921a940a6&v=4 url: https://github.com/ceb10n +valentinDruzhinin: + login: valentinDruzhinin + count: 24 + avatarUrl: https://avatars.githubusercontent.com/u/12831905?u=aae1ebc675c91e8fa582df4fcc4fc4128106344d&v=4 + url: https://github.com/valentinDruzhinin tokusumi: login: tokusumi count: 23 @@ -43,6 +48,11 @@ hard-coders: count: 15 avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=95db33927bbff1ed1c07efddeb97ac2ff33068ed&v=4 url: https://github.com/hard-coders +Joao-Pedro-P-Holanda: + login: Joao-Pedro-P-Holanda + count: 14 + avatarUrl: https://avatars.githubusercontent.com/u/110267046?u=331bd016326dac4cf3df4848f6db2dbbf8b5f978&v=4 + url: https://github.com/Joao-Pedro-P-Holanda codingjenny: login: codingjenny count: 14 @@ -53,11 +63,11 @@ Xewus: count: 13 avatarUrl: https://avatars.githubusercontent.com/u/85196001?u=f8e2dc7e5104f109cef944af79050ea8d1b8f914&v=4 url: https://github.com/Xewus -Joao-Pedro-P-Holanda: - login: Joao-Pedro-P-Holanda +Zhongheng-Cheng: + login: Zhongheng-Cheng count: 13 - avatarUrl: https://avatars.githubusercontent.com/u/110267046?u=331bd016326dac4cf3df4848f6db2dbbf8b5f978&v=4 - url: https://github.com/Joao-Pedro-P-Holanda + avatarUrl: https://avatars.githubusercontent.com/u/95612344?u=a0f7730a3cc7486827965e01a119ad610bda4b0a&v=4 + url: https://github.com/Zhongheng-Cheng Smlep: login: Smlep count: 11 @@ -78,11 +88,6 @@ Vincy1230: count: 9 avatarUrl: https://avatars.githubusercontent.com/u/81342412?u=ab5e256a4077a4a91f3f9cd2115ba80780454cbe&v=4 url: https://github.com/Vincy1230 -Zhongheng-Cheng: - login: Zhongheng-Cheng - count: 9 - avatarUrl: https://avatars.githubusercontent.com/u/95612344?u=a0f7730a3cc7486827965e01a119ad610bda4b0a&v=4 - url: https://github.com/Zhongheng-Cheng rjNemo: login: rjNemo count: 8 @@ -98,6 +103,11 @@ pablocm83: count: 8 avatarUrl: https://avatars.githubusercontent.com/u/28315068?u=3310fbb05bb8bfc50d2c48b6cb64ac9ee4a14549&v=4 url: https://github.com/pablocm83 +ptt3199: + login: ptt3199 + count: 7 + avatarUrl: https://avatars.githubusercontent.com/u/51350651?u=2c3d947a80283e32bf616d4c3af139a6be69680f&v=4 + url: https://github.com/ptt3199 batlopes: login: batlopes count: 6 @@ -106,7 +116,7 @@ batlopes: lucasbalieiro: login: lucasbalieiro count: 6 - avatarUrl: https://avatars.githubusercontent.com/u/37416577?u=5a395a69384e7fa0f9840ea32ef963d3f1cd9da4&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/37416577?u=eabaf4aebbaa88a94a4886273edba689012cee70&v=4 url: https://github.com/lucasbalieiro Alexandrhub: login: Alexandrhub @@ -143,6 +153,11 @@ rostik1410: count: 5 avatarUrl: https://avatars.githubusercontent.com/u/11443899?u=e26a635c2ba220467b308a326a579b8ccf4a8701&v=4 url: https://github.com/rostik1410 +alv2017: + login: alv2017 + count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 + url: https://github.com/alv2017 komtaki: login: komtaki count: 4 @@ -188,11 +203,11 @@ kwang1215: count: 4 avatarUrl: https://avatars.githubusercontent.com/u/74170199?u=2a63ff6692119dde3f5e5693365b9fcd6f977b08&v=4 url: https://github.com/kwang1215 -alv2017: - login: alv2017 +k94-ishi: + login: k94-ishi count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/31544722?v=4 - url: https://github.com/alv2017 + avatarUrl: https://avatars.githubusercontent.com/u/32672580?u=bc7c5c07af0656be9fe4f1784a444af8d81ded89&v=4 + url: https://github.com/k94-ishi jfunez: login: jfunez count: 3 @@ -201,7 +216,7 @@ jfunez: ycd: login: ycd count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=29682e4b6ac7d5293742ccf818188394b9a82972&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=f1e7bae394a315da950912c92dc861a8eaf95d4c&v=4 url: https://github.com/ycd mariacamilagl: login: mariacamilagl @@ -238,11 +253,6 @@ Zssaer: count: 3 avatarUrl: https://avatars.githubusercontent.com/u/45691504?u=4c0c195f25cb5ac6af32acfb0ab35427682938d2&v=4 url: https://github.com/Zssaer -wdh99: - login: wdh99 - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/108172295?u=8a8fb95d5afe3e0fa33257b2aecae88d436249eb&v=4 - url: https://github.com/wdh99 ChuyuChoyeon: login: ChuyuChoyeon count: 3 @@ -261,12 +271,12 @@ mojtabapaso: hsuanchi: login: hsuanchi count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/24913710?u=0b094ae292292fee093818e37ceb645c114d2bff&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/24913710?u=7d25a398e478b6e63503bf6f26c54efa9e0da07b&v=4 url: https://github.com/hsuanchi alejsdev: login: alejsdev count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=356f39ff3f0211c720b06d3dbb060e98884085e3&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/90076947?u=638c65283ac9e9e2c3a0f9d1e3370db4b8a2c58d&v=4 url: https://github.com/alejsdev riroan: login: riroan @@ -318,11 +328,21 @@ nahyunkeem: count: 3 avatarUrl: https://avatars.githubusercontent.com/u/174440096?u=e12401d492eee58570f8914d0872b52e421a776e&v=4 url: https://github.com/nahyunkeem +timothy-jeong: + login: timothy-jeong + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/53824764?u=db3d0cea2f5fab64d810113c5039a369699a2774&v=4 + url: https://github.com/timothy-jeong gerry-sabar: login: gerry-sabar count: 3 avatarUrl: https://avatars.githubusercontent.com/u/1120123?v=4 url: https://github.com/gerry-sabar +Rishat-F: + login: Rishat-F + count: 3 + avatarUrl: https://avatars.githubusercontent.com/u/66554797?v=4 + url: https://github.com/Rishat-F izaguerreiro: login: izaguerreiro count: 2 @@ -451,8 +471,13 @@ choi-haram: imtiaz101325: login: imtiaz101325 count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/54007087?u=7a210ee38a0a30b7536226419b3b799620ad57d9&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/54007087?u=194d972b501b9ea9d2ddeaed757c492936e0121a&v=4 url: https://github.com/imtiaz101325 +fabianfalon: + login: fabianfalon + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/3700760?u=95f69e31280b17ac22299cdcd345323b142fe0af&v=4 + url: https://github.com/fabianfalon waketzheng: login: waketzheng count: 2 @@ -481,15 +506,20 @@ andersonrocha0: saeye: login: saeye count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/62229734?v=4 + avatarUrl: https://avatars.githubusercontent.com/u/62229734?u=312d619db2588b60d5d5bde65260a2f44fdc6c76&v=4 url: https://github.com/saeye -timothy-jeong: - login: timothy-jeong +11kkw: + login: 11kkw count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/53824764?u=db3d0cea2f5fab64d810113c5039a369699a2774&v=4 - url: https://github.com/timothy-jeong -Rishat-F: - login: Rishat-F + avatarUrl: https://avatars.githubusercontent.com/u/21125286?v=4 + url: https://github.com/11kkw +yes0ng: + login: yes0ng count: 2 - avatarUrl: https://avatars.githubusercontent.com/u/66554797?v=4 - url: https://github.com/Rishat-F + avatarUrl: https://avatars.githubusercontent.com/u/25501794?u=3aed18b0d491e0220a167a1e9e58bea3638c6707&v=4 + url: https://github.com/yes0ng +EgorOnishchuk: + login: EgorOnishchuk + count: 2 + avatarUrl: https://avatars.githubusercontent.com/u/120256301?v=4 + url: https://github.com/EgorOnishchuk diff --git a/docs/en/docs/advanced/generate-clients.md b/docs/en/docs/advanced/generate-clients.md index 3b9dc83f0..b2aef5037 100644 --- a/docs/en/docs/advanced/generate-clients.md +++ b/docs/en/docs/advanced/generate-clients.md @@ -24,7 +24,7 @@ For example, you might want to try: * Speakeasy * Stainless -* liblab +* liblab There are also several other companies offering similar services that you can search and find online. 🤓 diff --git a/docs/en/docs/advanced/index.md b/docs/en/docs/advanced/index.md index 36f0720c0..47385e2c6 100644 --- a/docs/en/docs/advanced/index.md +++ b/docs/en/docs/advanced/index.md @@ -19,18 +19,3 @@ And it's possible that for your use case, the solution is in one of them. You could still use most of the features in **FastAPI** with the knowledge from the main [Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank}. And the next sections assume you already read it, and assume that you know those main ideas. - -## External Courses - -Although the [Tutorial - User Guide](../tutorial/index.md){.internal-link target=_blank} and this **Advanced User Guide** are written as a guided tutorial (like a book) and should be enough for you to **learn FastAPI**, you might want to complement it with additional courses. - -Or it might be the case that you just prefer to take other courses because they adapt better to your learning style. - -Some course providers ✨ [**sponsor FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨, this ensures the continued and healthy **development** of FastAPI and its **ecosystem**. - -And it shows their true commitment to FastAPI and its **community** (you), as they not only want to provide you a **good learning experience** but also want to make sure you have a **good and healthy framework**, FastAPI. 🙇 - -You might want to try their courses: - -* Talk Python Training -* Test-Driven Development diff --git a/docs/en/docs/deployment/cloud.md b/docs/en/docs/deployment/cloud.md index 471808851..d713379c3 100644 --- a/docs/en/docs/deployment/cloud.md +++ b/docs/en/docs/deployment/cloud.md @@ -14,5 +14,4 @@ You might want to try their services and follow their guides: * Platform.sh * Porter -* Coherence * Render diff --git a/docs/en/docs/deployment/concepts.md b/docs/en/docs/deployment/concepts.md index e71a7487a..ed635a920 100644 --- a/docs/en/docs/deployment/concepts.md +++ b/docs/en/docs/deployment/concepts.md @@ -65,7 +65,7 @@ The word **program** is commonly used to describe many things: * The **code** that you write, the **Python files**. * The **file** that can be **executed** by the operating system, for example: `python`, `python.exe` or `uvicorn`. -* A particular program while it is **running** on the operating system, using the CPU, and storing things on memory. This is also called a **process**. +* A particular program while it is **running** on the operating system, using the CPU, and storing things in memory. This is also called a **process**. ### What is a Process @@ -216,7 +216,7 @@ This Manager Process would probably be the one listening on the **port** in the Those worker processes would be the ones running your application, they would perform the main computations to receive a **request** and return a **response**, and they would load anything you put in variables in RAM. - + And of course, the same machine would probably have **other processes** running as well, apart from your application. diff --git a/docs/en/docs/deployment/https.md b/docs/en/docs/deployment/https.md index 46eda791e..8b4a08dbe 100644 --- a/docs/en/docs/deployment/https.md +++ b/docs/en/docs/deployment/https.md @@ -85,7 +85,7 @@ First, the browser would check with the **DNS servers** what is the **IP for the The DNS servers would tell the browser to use some specific **IP address**. That would be the public IP address used by your server, that you configured in the DNS servers. - + ### TLS Handshake Start @@ -93,7 +93,7 @@ The browser would then communicate with that IP address on **port 443** (the HTT The first part of the communication is just to establish the connection between the client and the server and to decide the cryptographic keys they will use, etc. - + This interaction between the client and the server to establish the TLS connection is called the **TLS handshake**. @@ -111,7 +111,7 @@ Using the **SNI extension** discussed above, the TLS Termination Proxy would che In this case, it would use the certificate for `someapp.example.com`. - + The client already **trusts** the entity that generated that TLS certificate (in this case Let's Encrypt, but we'll see about that later), so it can **verify** that the certificate is valid. @@ -133,19 +133,19 @@ Now that the client and server (specifically the browser and the TLS Termination So, the client sends an **HTTPS request**. This is just an HTTP request through an encrypted TLS connection. - + ### Decrypt the Request The TLS Termination Proxy would use the encryption agreed to **decrypt the request**, and would transmit the **plain (decrypted) HTTP request** to the process running the application (for example a process with Uvicorn running the FastAPI application). - + ### HTTP Response The application would process the request and send a **plain (unencrypted) HTTP response** to the TLS Termination Proxy. - + ### HTTPS Response @@ -153,7 +153,7 @@ The TLS Termination Proxy would then **encrypt the response** using the cryptogr Next, the browser would verify that the response is valid and encrypted with the right cryptographic key, etc. It would then **decrypt the response** and process it. - + The client (browser) will know that the response comes from the correct server because it is using the cryptography they agreed using the **HTTPS certificate** before. @@ -163,7 +163,7 @@ In the same server (or servers), there could be **multiple applications**, for e Only one process can be handling the specific IP and port (the TLS Termination Proxy in our example) but the other applications/processes can be running on the server(s) too, as long as they don't try to use the same **combination of public IP and port**. - + That way, the TLS Termination Proxy could handle HTTPS and certificates for **multiple domains**, for multiple applications, and then transmit the requests to the right application in each case. @@ -173,7 +173,7 @@ At some point in the future, each certificate would **expire** (about 3 months a And then, there would be another program (in some cases it's another program, in some cases it could be the same TLS Termination Proxy) that would talk to Let's Encrypt, and renew the certificate(s). - + The **TLS certificates** are **associated with a domain name**, not with an IP address. diff --git a/docs/en/docs/help-fastapi.md b/docs/en/docs/help-fastapi.md index 81151032f..35d2e7b84 100644 --- a/docs/en/docs/help-fastapi.md +++ b/docs/en/docs/help-fastapi.md @@ -249,20 +249,7 @@ On the other side, there are thousands of users in the chat systems, so there's ## Sponsor the author -You can also financially support the author (me) through GitHub sponsors. - -There you could buy me a coffee ☕️ to say thanks. 😄 - -And you can also become a Silver or Gold sponsor for FastAPI. 🏅🎉 - -## Sponsor the tools that power FastAPI - -As you have seen in the documentation, FastAPI stands on the shoulders of giants, Starlette and Pydantic. - -You can also sponsor: - -* Samuel Colvin (Pydantic) -* Encode (Starlette, Uvicorn) +If your **product/company** depends on or is related to **FastAPI** and you want to reach its users, you can sponsor the author (me) through GitHub sponsors. Depending on the tier, you could get some extra benefits, like a badge in the docs. 🎁 --- diff --git a/docs/en/docs/how-to/custom-docs-ui-assets.md b/docs/en/docs/how-to/custom-docs-ui-assets.md index f717c98fa..9d2238e4f 100644 --- a/docs/en/docs/how-to/custom-docs-ui-assets.md +++ b/docs/en/docs/how-to/custom-docs-ui-assets.md @@ -98,7 +98,7 @@ You can probably right-click each link and select an option similar to `Save lin And **ReDoc** uses the file: -* `redoc.standalone.js` +* `redoc.standalone.js` After that, your file structure could look like: @@ -129,14 +129,8 @@ You should see a very long JavaScript file for **ReDoc**. It could start with something like: ```JavaScript -/*! - * ReDoc - OpenAPI/Swagger-generated API Reference Documentation - * ------------------------------------------------------------- - * Version: "2.0.0-rc.18" - * Repo: https://github.com/Redocly/redoc - */ -!function(e,t){"object"==typeof exports&&"object"==typeof m - +/*! For license information please see redoc.standalone.js.LICENSE.txt */ +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("null")): ... ``` diff --git a/docs/en/docs/img/deployment/concepts/process-ram.drawio b/docs/en/docs/img/deployment/concepts/process-ram.drawio deleted file mode 100644 index b29c8a342..000000000 --- a/docs/en/docs/img/deployment/concepts/process-ram.drawio +++ /dev/null @@ -1,106 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/docs/en/docs/img/deployment/concepts/process-ram.drawio.svg b/docs/en/docs/img/deployment/concepts/process-ram.drawio.svg new file mode 100644 index 000000000..a6a5c81d0 --- /dev/null +++ b/docs/en/docs/img/deployment/concepts/process-ram.drawio.svg @@ -0,0 +1,297 @@ + + + + + + + + + + + + + +
+
+
+ + + Server + + +
+
+
+
+ + Server + +
+
+
+ + + + + + + + + + +
+
+
+ + + RAM + +
+
+
+
+
+
+ + RAM + +
+
+
+ + + + + + + + + + +
+
+
+ + + CPU + +
+
+
+
+
+
+ + CPU + +
+
+
+ + + + + + + + + + + + + + + + + + + + + +
+
+
+ + + + Process + + + + Manager + + +
+
+
+
+ + Process Manager + +
+
+
+ + + + + + + + + + +
+
+
+ + + Worker Process + + +
+
+
+
+ + Worker Process + +
+
+
+ + + + + + + + + + + + + +
+
+
+ + + Worker Process + + +
+
+
+
+ + Worker Process + +
+
+
+ + + + + + + + + + + + + +
+
+
+ + + Another Process + + +
+
+
+
+ + Another Process + +
+
+
+ + + + + + + + + + + + + + + + + + + +
+
+
+ + 1 GB + +
+
+
+
+ + 1 GB + +
+
+
+ + + + + + + +
+
+
+ + 1 GB + +
+
+
+
+ + 1 GB + +
+
+
+ + + + + + +
+ + + + + Text is not SVG - cannot display + + + +
diff --git a/docs/en/docs/img/deployment/concepts/process-ram.svg b/docs/en/docs/img/deployment/concepts/process-ram.svg deleted file mode 100644 index c1bf0d589..000000000 --- a/docs/en/docs/img/deployment/concepts/process-ram.svg +++ /dev/null @@ -1,59 +0,0 @@ -
Server
Server
RAM
RAM -
CPU
CPU -
Process Manager
Process Manager
Worker Process
Worker Process
Worker Process
Worker Process
Another Process
Another Process
1 GB
1 GB
1 GB
1 GB
Viewer does not support full SVG 1.1
diff --git a/docs/en/docs/img/deployment/https/https.drawio b/docs/en/docs/img/deployment/https/https.drawio deleted file mode 100644 index c4c8a3628..000000000 --- a/docs/en/docs/img/deployment/https/https.drawio +++ /dev/null @@ -1,277 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/docs/en/docs/img/deployment/https/https.drawio.svg b/docs/en/docs/img/deployment/https/https.drawio.svg new file mode 100644 index 000000000..c2a65b69f --- /dev/null +++ b/docs/en/docs/img/deployment/https/https.drawio.svg @@ -0,0 +1,907 @@ + + + + + + + + + + + + + + + + + + + +
+
+
+ + + Server(s) + + +
+
+
+
+ + Server(s) + +
+
+
+ + + + + + + + + + + +
+
+
+ + DNS Servers + +
+
+
+
+ + DNS Servers + +
+
+
+ + + + + + + + + + +
+
+
+ + + TLS Termination Proxy + +
+
+
+
+
+
+ + TLS Termination Proxy + +
+
+
+ + + + + + + + + + + + + + + +
+
+
+ + Cert Renovation Program + +
+
+
+
+ + Cert Renovation Program + +
+
+
+ + + + + + + + + + + +
+
+
+ + Let's Encrypt + +
+
+
+
+ + Let's Encrypt + +
+
+
+ + + + + + + + + + + + + + + +
+
+
+ + + FastAPI + + + app for: someapp.example.com + + +
+
+
+
+ + FastAPI app for: someapp.example.com + +
+
+
+ + + + + + + +
+
+
+ + + Another app + + + : another.example.com + + +
+
+
+
+ + Another app: another.example.com + +
+
+
+ + + + + + + +
+
+
+ + + One more app + + + : onemore.example.com + + +
+
+
+
+ + One more app: onemore.example.com + +
+
+
+ + + + + + + +
+
+
+ + + A Database + + +
+
+
+
+ + A Database + +
+
+
+ + + + + + + + + + + + + +
+
+
+ + + Plain response from: someapp.example.com + + +
+
+
+
+ + Plain response from: someapp.example.com + +
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+ + Port 443 (HTTPS) + +
+
+
+
+ + Port 443 (HTTPS) + +
+
+
+ + + + + + + + + + + + + + +
+
+
+ + + Encrypted request for: someapp.example.com + + +
+
+
+
+ + Encrypted request for: someapp.example.com + +
+
+
+ + + + + + + +
+
+
+ + + Who is: someapp.example.com + + +
+
+
+
+ + Who is: someapp.example.com + +
+
+
+ + + + + + + +
+
+
+ + + IP: + +
+ + 123.124.125.126 + +
+
+
+
+
+ + IP:... + +
+
+
+ + + + + + + +
+
+
+ + + Renew HTTPS cert for: someapp.example.com + + +
+
+
+
+ + Renew HTTPS cert for: someapp.example.com + +
+
+
+ + + + + + + +
+
+
+ + + New HTTPS cert for: someapp.example.com + + +
+
+
+
+ + New HTTPS cert for: someapp.example.com + +
+
+
+ + + + + + + + + + +
+
+
+ + + TLS Handshake + + +
+
+
+
+ + TLS Handshake + +
+
+
+ + + + + + + + + + +
+
+
+ + + Encrypted response from: someapp.example.com + + +
+
+
+
+ + Encrypted response from: someapp.example.com + +
+
+
+ + + + + + + + + + + + + +
+
+
+ + + HTTPS certificates + +
+
+
+
+
+
+ + HTTPS certificates + +
+
+
+ + + + + + + +
+
+
+ + + + someapp.example.com + + +
+
+
+
+
+
+ + someapp.example.com + +
+
+
+ + + + + + + +
+
+
+ + + + another.example.net + + +
+
+
+
+
+
+ + another.example.net + +
+
+
+ + + + + + + +
+
+
+ + + + onemore.example.org + + +
+
+
+
+
+
+ + onemore.example.org + +
+
+
+ + + + + + + +
+
+
+ + + + IP: + +
+ + 123.124.125.126 + +
+
+
+
+
+
+
+ + IP:... + +
+
+
+ + + + + + + +
+
+
+ + + Decrypted request for: someapp.example.com + + +
+
+
+
+ + Decrypted request for: someapp.example.com + +
+
+
+ + + + + + + + + + +
+
+
+ + https://someapp.example.com + +
+
+
+
+ + https://someapp.example.com + +
+
+
+
+ + + + + Text is not SVG - cannot display + + + +
diff --git a/docs/en/docs/img/deployment/https/https.svg b/docs/en/docs/img/deployment/https/https.svg deleted file mode 100644 index 69497518a..000000000 --- a/docs/en/docs/img/deployment/https/https.svg +++ /dev/null @@ -1,62 +0,0 @@ -
Server(s)
Server(s)
https://someapp.example.com
https://someapp.example.com
DNS Servers
DNS Servers
TLS Termination Proxy
TLS Termination Proxy -
Cert Renovation Program
Cert Renovation Program
Let's Encrypt
Let's Encrypt
FastAPI app for: someapp.example.com
FastAPI app for: someapp.example.com
Another app: another.example.com
Another app: another.example.com
One more app: onemore.example.com
One more app: onemore.example.com
A Database
A Database
Plain response from: someapp.example.com
Plain response from: someapp.example.com
Port 443 (HTTPS)
Port 443 (HTTPS)
Encrypted request for: someapp.example.com
Encrypted request for: someapp.example.com
Who is: someapp.example.com
Who is: someapp.example.com
IP:
123.124.125.126
IP:...
Renew HTTPS cert for: someapp.example.com
Renew HTTPS cert for: someapp.example.com
New HTTPS cert for: someapp.example.com
New HTTPS cert for: someapp.example.com
TLS Handshake
TLS Handshake
Encrypted response from: someapp.example.com
Encrypted response from: someapp.example.com
HTTPS certificates
HTTPS certificates -
someapp.example.com
someapp.example.com -
another.example.net
another.example.net -
onemore.example.org
onemore.example.org -
IP:
123.124.125.126
IP:...
Decrypted request for: someapp.example.com
Decrypted request for: someapp.example.com
Viewer does not support full SVG 1.1
diff --git a/docs/en/docs/img/deployment/https/https01.drawio b/docs/en/docs/img/deployment/https/https01.drawio deleted file mode 100644 index 181582f9b..000000000 --- a/docs/en/docs/img/deployment/https/https01.drawio +++ /dev/null @@ -1,78 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/docs/en/docs/img/deployment/https/https01.drawio.svg b/docs/en/docs/img/deployment/https/https01.drawio.svg new file mode 100644 index 000000000..ea128daf8 --- /dev/null +++ b/docs/en/docs/img/deployment/https/https01.drawio.svg @@ -0,0 +1,131 @@ + + + + + + + + + + + + + + + + + + +
+
+
+ + DNS Servers + +
+
+
+
+ + DNS Servers + +
+
+
+ + + + + + + + + + + + + + + + + +
+
+
+ + + Who is: someapp.example.com + + +
+
+
+
+ + Who is: someapp.example.com + +
+
+
+ + + + + + + +
+
+
+ + + IP: + +
+ + 123.124.125.126 + +
+
+
+
+
+ + IP:... + +
+
+
+ + + + + + + +
+
+
+ + https://someapp.example.com + +
+
+
+
+ + https://someapp.example.com + +
+
+
+
+ + + + + Text is not SVG - cannot display + + + +
diff --git a/docs/en/docs/img/deployment/https/https01.svg b/docs/en/docs/img/deployment/https/https01.svg deleted file mode 100644 index 2edbd0623..000000000 --- a/docs/en/docs/img/deployment/https/https01.svg +++ /dev/null @@ -1,57 +0,0 @@ -
https://someapp.example.com
https://someapp.example.com
DNS Servers
DNS Servers
Who is: someapp.example.com
Who is: someapp.example.com
IP:
123.124.125.126
IP:...
Viewer does not support full SVG 1.1
diff --git a/docs/en/docs/img/deployment/https/https02.drawio b/docs/en/docs/img/deployment/https/https02.drawio deleted file mode 100644 index 650c06d1e..000000000 --- a/docs/en/docs/img/deployment/https/https02.drawio +++ /dev/null @@ -1,110 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/docs/en/docs/img/deployment/https/https02.drawio.svg b/docs/en/docs/img/deployment/https/https02.drawio.svg new file mode 100644 index 000000000..c29d59356 --- /dev/null +++ b/docs/en/docs/img/deployment/https/https02.drawio.svg @@ -0,0 +1,245 @@ + + + + + + + + + + + + + + + + + +
+
+
+ + + Server(s) + + +
+
+
+
+ + Server(s) + +
+
+
+ + + + + + + + + + + +
+
+
+ + DNS Servers + +
+
+
+
+ + DNS Servers + +
+
+
+ + + + + + + + + + + + + + + + + +
+
+
+ + Port 443 (HTTPS) + +
+
+
+
+ + Port 443 (HTTPS) + +
+
+
+ + + + + + + +
+
+
+ + + + IP: + +
+ + 123.124.125.126 + +
+
+
+
+
+
+
+ + IP:... + +
+
+
+ + + + + + + +
+
+
+ + + Who is: someapp.example.com + + +
+
+
+
+ + Who is: someapp.example.com + +
+
+
+ + + + + + + +
+
+
+ + + IP: + +
+ + 123.124.125.126 + +
+
+
+
+
+ + IP:... + +
+
+
+ + + + + + + + + + +
+
+
+ + + TLS Handshake + + +
+
+
+
+ + TLS Handshake + +
+
+
+ + + + + + + + + + +
+
+
+ + https://someapp.example.com + +
+
+
+
+ + https://someapp.example.com + +
+
+
+
+ + + + + Text is not SVG - cannot display + + + +
diff --git a/docs/en/docs/img/deployment/https/https02.svg b/docs/en/docs/img/deployment/https/https02.svg deleted file mode 100644 index e16b7e94a..000000000 --- a/docs/en/docs/img/deployment/https/https02.svg +++ /dev/null @@ -1,57 +0,0 @@ -
Server(s)
Server(s)
https://someapp.example.com
https://someapp.example.com
DNS Servers
DNS Servers
Port 443 (HTTPS)
Port 443 (HTTPS)
IP:
123.124.125.126
IP:...
Who is: someapp.example.com
Who is: someapp.example.com
IP:
123.124.125.126
IP:...
TLS Handshake
TLS Handshake
Viewer does not support full SVG 1.1
diff --git a/docs/en/docs/img/deployment/https/https03.drawio b/docs/en/docs/img/deployment/https/https03.drawio deleted file mode 100644 index c178fd363..000000000 --- a/docs/en/docs/img/deployment/https/https03.drawio +++ /dev/null @@ -1,131 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/docs/en/docs/img/deployment/https/https03.drawio.svg b/docs/en/docs/img/deployment/https/https03.drawio.svg new file mode 100644 index 000000000..6971e4c9c --- /dev/null +++ b/docs/en/docs/img/deployment/https/https03.drawio.svg @@ -0,0 +1,715 @@ + + + + + + + + + + + + + + + + + + + +
+
+
+ + + Server(s) + + +
+
+
+
+ + Server(s) + +
+
+
+ + + + + + + + + + + +
+
+
+ + DNS Servers + +
+
+
+
+ + DNS Servers + +
+
+
+ + + + + + + + + + +
+
+
+ + + TLS Termination Proxy + +
+
+
+
+
+
+ + TLS Termination Proxy + +
+
+
+ + + + + + + + + + + + + + + + + +
+
+
+ + Port 443 (HTTPS) + +
+
+
+
+ + Port 443 (HTTPS) + +
+
+
+ + + + + + + +
+
+
+ + + Who is: someapp.example.com + + +
+
+
+
+ + Who is: someapp.example.com + +
+
+
+ + + + + + + +
+
+
+ + + IP: + +
+ + 123.124.125.126 + +
+
+
+
+
+ + IP:... + +
+
+
+ + + + + + + + + + +
+
+
+ + + TLS Handshake + + +
+
+
+
+ + TLS Handshake + +
+
+
+ + + + + + + + + + + + + +
+
+
+ + + HTTPS certificates + +
+
+
+
+
+
+ + HTTPS certificates + +
+
+
+ + + + + + + +
+
+
+ + + + someapp.example.com + + +
+
+
+
+
+
+ + someapp.example.com + +
+
+
+ + + + + + + +
+
+
+ + + + another.example.net + + +
+
+
+
+
+
+ + another.example.net + +
+
+
+ + + + + + + +
+
+
+ + + + onemore.example.org + + +
+
+
+
+
+
+ + onemore.example.org + +
+
+
+ + + + + + + +
+
+
+ + + + IP: + +
+ + 123.124.125.126 + +
+
+
+
+
+
+
+ + IP:... + +
+
+
+ + + + + + + +
+
+
+ + https://someapp.example.com + +
+
+
+
+ + https://someapp.example.com + +
+
+
+
+ + + + + Text is not SVG - cannot display + + + +
diff --git a/docs/en/docs/img/deployment/https/https03.svg b/docs/en/docs/img/deployment/https/https03.svg deleted file mode 100644 index 2badd1c7d..000000000 --- a/docs/en/docs/img/deployment/https/https03.svg +++ /dev/null @@ -1,62 +0,0 @@ -
Server(s)
Server(s)
https://someapp.example.com
https://someapp.example.com
DNS Servers
DNS Servers
TLS Termination Proxy
TLS Termination Proxy -
Port 443 (HTTPS)
Port 443 (HTTPS)
Who is: someapp.example.com
Who is: someapp.example.com
IP:
123.124.125.126
IP:...
TLS Handshake
TLS Handshake
HTTPS certificates
HTTPS certificates -
someapp.example.com
someapp.example.com -
another.example.net
another.example.net -
onemore.example.org
onemore.example.org -
IP:
123.124.125.126
IP:...
Viewer does not support full SVG 1.1
diff --git a/docs/en/docs/img/deployment/https/https04.drawio b/docs/en/docs/img/deployment/https/https04.drawio deleted file mode 100644 index 78a6e919a..000000000 --- a/docs/en/docs/img/deployment/https/https04.drawio +++ /dev/null @@ -1,152 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/docs/en/docs/img/deployment/https/https04.drawio.svg b/docs/en/docs/img/deployment/https/https04.drawio.svg new file mode 100644 index 000000000..7e32bcdfe --- /dev/null +++ b/docs/en/docs/img/deployment/https/https04.drawio.svg @@ -0,0 +1,419 @@ + + + + + + + + + + + + + + + + + +
+
+
+ + + Server(s) + + +
+
+
+
+ + Server(s) + +
+
+
+ + + + + + + + + + + +
+
+
+ + DNS Servers + +
+
+
+
+ + DNS Servers + +
+
+
+ + + + + + + + + + +
+
+
+ + + TLS Termination Proxy + +
+
+
+
+
+
+ + TLS Termination Proxy + +
+
+
+ + + + + + + + + + + + + + + + + +
+
+
+ + Port 443 (HTTPS) + +
+
+
+
+ + Port 443 (HTTPS) + +
+
+
+ + + + + + + + + + + + + + +
+
+
+ + + Encrypted request for: someapp.example.com + + +
+
+
+
+ + Encrypted request for: someapp.example.com + +
+
+
+ + + + + + + +
+
+
+ + + Who is: someapp.example.com + + +
+
+
+
+ + Who is: someapp.example.com + +
+
+
+ + + + + + + +
+
+
+ + + IP: + +
+ + 123.124.125.126 + +
+
+
+
+
+ + IP:... + +
+
+
+ + + + + + + + + + +
+
+
+ + + TLS Handshake + + +
+
+
+
+ + TLS Handshake + +
+
+
+ + + + + + + + + + + + + +
+
+
+ + + HTTPS certificates + +
+
+
+
+
+
+ + HTTPS certificates + +
+
+
+ + + + + + + +
+
+
+ + + + someapp.example.com + + +
+
+
+
+
+
+ + someapp.example.com + +
+
+
+ + + + + + + +
+
+
+ + + + another.example.net + + +
+
+
+
+
+
+ + another.example.net + +
+
+
+ + + + + + + +
+
+
+ + + + onemore.example.org + + +
+
+
+
+
+
+ + onemore.example.org + +
+
+
+ + + + + + + +
+
+
+ + + + IP: + +
+ + 123.124.125.126 + +
+
+
+
+
+
+
+ + IP:... + +
+
+
+ + + + + + + +
+
+
+ + https://someapp.example.com + +
+
+
+
+ + https://someapp.example.com + +
+
+
+
+ + + + + Text is not SVG - cannot display + + + +
diff --git a/docs/en/docs/img/deployment/https/https04.svg b/docs/en/docs/img/deployment/https/https04.svg deleted file mode 100644 index 4513ac76b..000000000 --- a/docs/en/docs/img/deployment/https/https04.svg +++ /dev/null @@ -1,62 +0,0 @@ -
Server(s)
Server(s)
https://someapp.example.com
https://someapp.example.com
DNS Servers
DNS Servers
TLS Termination Proxy
TLS Termination Proxy -
Port 443 (HTTPS)
Port 443 (HTTPS)
Encrypted request for: someapp.example.com
Encrypted request for: someapp.example.com
Who is: someapp.example.com
Who is: someapp.example.com
IP:
123.124.125.126
IP:...
TLS Handshake
TLS Handshake
HTTPS certificates
HTTPS certificates -
someapp.example.com
someapp.example.com -
another.example.net
another.example.net -
onemore.example.org
onemore.example.org -
IP:
123.124.125.126
IP:...
Viewer does not support full SVG 1.1
diff --git a/docs/en/docs/img/deployment/https/https05.drawio b/docs/en/docs/img/deployment/https/https05.drawio deleted file mode 100644 index 236ecd841..000000000 --- a/docs/en/docs/img/deployment/https/https05.drawio +++ /dev/null @@ -1,166 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/docs/en/docs/img/deployment/https/https05.drawio.svg b/docs/en/docs/img/deployment/https/https05.drawio.svg new file mode 100644 index 000000000..fed2fad16 --- /dev/null +++ b/docs/en/docs/img/deployment/https/https05.drawio.svg @@ -0,0 +1,641 @@ + + + + + + + + + + + + + + + + + + + +
+
+
+ + + Server(s) + + +
+
+
+
+ + Server(s) + +
+
+
+ + + + + + + + + + + +
+
+
+ + DNS Servers + +
+
+
+
+ + DNS Servers + +
+
+
+ + + + + + + + + + +
+
+
+ + + TLS Termination Proxy + +
+
+
+
+
+
+ + TLS Termination Proxy + +
+
+
+ + + + + + + +
+
+
+ + + FastAPI + + + app for: someapp.example.com + + +
+
+
+
+ + FastAPI app for: someapp.example.com + +
+
+
+ + + + + + + + + + + +
+
+
+ + + Decrypted request for: someapp.example.com + + +
+
+
+
+ + Decrypted request for: someapp.example.com + +
+
+
+ + + + + + + + + + + + + + + + + +
+
+
+ + Port 443 (HTTPS) + +
+
+
+
+ + Port 443 (HTTPS) + +
+
+
+ + + + + + + + + + + + + + +
+
+
+ + + Encrypted request for: someapp.example.com + + +
+
+
+
+ + Encrypted request for: someapp.example.com + +
+
+
+ + + + + + + +
+
+
+ + + Who is: someapp.example.com + + +
+
+
+
+ + Who is: someapp.example.com + +
+
+
+ + + + + + + +
+
+
+ + + IP: + +
+ + 123.124.125.126 + +
+
+
+
+
+ + IP:... + +
+
+
+ + + + + + + + + + +
+
+
+ + + TLS Handshake + + +
+
+
+
+ + TLS Handshake + +
+
+
+ + + + + + + + + + + + + +
+
+
+ + + HTTPS certificates + +
+
+
+
+
+
+ + HTTPS certificates + +
+
+
+ + + + + + + +
+
+
+ + + + someapp.example.com + + +
+
+
+
+
+
+ + someapp.example.com + +
+
+
+ + + + + + + +
+
+
+ + + + another.example.net + + +
+
+
+
+
+
+ + another.example.net + +
+
+
+ + + + + + + +
+
+
+ + + + onemore.example.org + + +
+
+
+
+
+
+ + onemore.example.org + +
+
+
+ + + + + + + +
+
+
+ + + + IP: + +
+ + 123.124.125.126 + +
+
+
+
+
+
+
+ + IP:... + +
+
+
+ + + + + + + +
+
+
+ + https://someapp.example.com + +
+
+
+
+ + https://someapp.example.com + +
+
+
+
+ + + + + Text is not SVG - cannot display + + + +
diff --git a/docs/en/docs/img/deployment/https/https05.svg b/docs/en/docs/img/deployment/https/https05.svg deleted file mode 100644 index ddcd2760a..000000000 --- a/docs/en/docs/img/deployment/https/https05.svg +++ /dev/null @@ -1,62 +0,0 @@ -
Server(s)
Server(s)
https://someapp.example.com
https://someapp.example.com
DNS Servers
DNS Servers
TLS Termination Proxy
TLS Termination Proxy -
FastAPI app for: someapp.example.com
FastAPI app for: someapp.example.com
Decrypted request for: someapp.example.com
Decrypted request for: someapp.example.com
Port 443 (HTTPS)
Port 443 (HTTPS)
Encrypted request for: someapp.example.com
Encrypted request for: someapp.example.com
Who is: someapp.example.com
Who is: someapp.example.com
IP:
123.124.125.126
IP:...
TLS Handshake
TLS Handshake
HTTPS certificates
HTTPS certificates -
someapp.example.com
someapp.example.com -
another.example.net
another.example.net -
onemore.example.org
onemore.example.org -
IP:
123.124.125.126
IP:...
Viewer does not support full SVG 1.1
diff --git a/docs/en/docs/img/deployment/https/https06.drawio b/docs/en/docs/img/deployment/https/https06.drawio deleted file mode 100644 index 9dec13184..000000000 --- a/docs/en/docs/img/deployment/https/https06.drawio +++ /dev/null @@ -1,183 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/docs/en/docs/img/deployment/https/https06.drawio.svg b/docs/en/docs/img/deployment/https/https06.drawio.svg new file mode 100644 index 000000000..e0bd9bc6e --- /dev/null +++ b/docs/en/docs/img/deployment/https/https06.drawio.svg @@ -0,0 +1,673 @@ + + + + + + + + + + + + + + + + + + + +
+
+
+ + + Server(s) + + +
+
+
+
+ + Server(s) + +
+
+
+ + + + + + + + + + + +
+
+
+ + DNS Servers + +
+
+
+
+ + DNS Servers + +
+
+
+ + + + + + + + + + +
+
+
+ + + TLS Termination Proxy + +
+
+
+
+
+
+ + TLS Termination Proxy + +
+
+
+ + + + + + + + + + + +
+
+
+ + + FastAPI + + + app for: someapp.example.com + + +
+
+
+
+ + FastAPI app for: someapp.example.com + +
+
+
+ + + + + + + +
+
+
+ + + Plain response from: someapp.example.com + + +
+
+
+
+ + Plain response from: someapp.example.com + +
+
+
+ + + + + + + + + + + + + + +
+
+
+ + + Decrypted request for: someapp.example.com + + +
+
+
+
+ + Decrypted request for: someapp.example.com + +
+
+
+ + + + + + + + + + + + + + + + + +
+
+
+ + Port 443 (HTTPS) + +
+
+
+
+ + Port 443 (HTTPS) + +
+
+
+ + + + + + + + + + + + + + +
+
+
+ + + Encrypted request for: someapp.example.com + + +
+
+
+
+ + Encrypted request for: someapp.example.com + +
+
+
+ + + + + + + +
+
+
+ + + Who is: someapp.example.com + + +
+
+
+
+ + Who is: someapp.example.com + +
+
+
+ + + + + + + +
+
+
+ + + IP: + +
+ + 123.124.125.126 + +
+
+
+
+
+ + IP:... + +
+
+
+ + + + + + + + + + +
+
+
+ + + TLS Handshake + + +
+
+
+
+ + TLS Handshake + +
+
+
+ + + + + + + + + + + + + +
+
+
+ + + HTTPS certificates + +
+
+
+
+
+
+ + HTTPS certificates + +
+
+
+ + + + + + + +
+
+
+ + + + someapp.example.com + + +
+
+
+
+
+
+ + someapp.example.com + +
+
+
+ + + + + + + +
+
+
+ + + + another.example.net + + +
+
+
+
+
+
+ + another.example.net + +
+
+
+ + + + + + + +
+
+
+ + + + onemore.example.org + + +
+
+
+
+
+
+ + onemore.example.org + +
+
+
+ + + + + + + +
+
+
+ + + + IP: + +
+ + 123.124.125.126 + +
+
+
+
+
+
+
+ + IP:... + +
+
+
+ + + + + + + +
+
+
+ + https://someapp.example.com + +
+
+
+
+ + https://someapp.example.com + +
+
+
+
+ + + + + Text is not SVG - cannot display + + + +
diff --git a/docs/en/docs/img/deployment/https/https06.svg b/docs/en/docs/img/deployment/https/https06.svg deleted file mode 100644 index 3695de40c..000000000 --- a/docs/en/docs/img/deployment/https/https06.svg +++ /dev/null @@ -1,62 +0,0 @@ -
Server(s)
Server(s)
https://someapp.example.com
https://someapp.example.com
DNS Servers
DNS Servers
TLS Termination Proxy
TLS Termination Proxy -
FastAPI app for: someapp.example.com
FastAPI app for: someapp.example.com
Plain response from: someapp.example.com
Plain response from: someapp.example.com
Decrypted request for: someapp.example.com
Decrypted request for: someapp.example.com
Port 443 (HTTPS)
Port 443 (HTTPS)
Encrypted request for: someapp.example.com
Encrypted request for: someapp.example.com
Who is: someapp.example.com
Who is: someapp.example.com
IP:
123.124.125.126
IP:...
TLS Handshake
TLS Handshake
HTTPS certificates
HTTPS certificates -
someapp.example.com
someapp.example.com -
another.example.net
another.example.net -
onemore.example.org
onemore.example.org -
IP:
123.124.125.126
IP:...
Viewer does not support full SVG 1.1
diff --git a/docs/en/docs/img/deployment/https/https07.drawio b/docs/en/docs/img/deployment/https/https07.drawio deleted file mode 100644 index aa8f4d6be..000000000 --- a/docs/en/docs/img/deployment/https/https07.drawio +++ /dev/null @@ -1,203 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/docs/en/docs/img/deployment/https/https07.drawio.svg b/docs/en/docs/img/deployment/https/https07.drawio.svg new file mode 100644 index 000000000..b74b33807 --- /dev/null +++ b/docs/en/docs/img/deployment/https/https07.drawio.svg @@ -0,0 +1,540 @@ + + + + + + + + + + + + + + + + + +
+
+
+ + + Server(s) + + +
+
+
+
+ + Server(s) + +
+
+
+ + + + + + + + + + + +
+
+
+ + DNS Servers + +
+
+
+
+ + DNS Servers + +
+
+
+ + + + + + + + + + +
+
+
+ + + TLS Termination Proxy + +
+
+
+
+
+
+ + TLS Termination Proxy + +
+
+
+ + + + + + + + + + + +
+
+
+ + + FastAPI + + + app for: someapp.example.com + + +
+
+
+
+ + FastAPI app for: someapp.example.com + +
+
+
+ + + + + + + +
+
+
+ + + Plain response from: someapp.example.com + + +
+
+
+
+ + Plain response from: someapp.example.com + +
+
+
+ + + + + + + + + + + + + + +
+
+
+ + + Decrypted request for: someapp.example.com + + +
+
+
+
+ + Decrypted request for: someapp.example.com + +
+
+
+ + + + + + + + + + + + + + + + + + + + + +
+
+
+ + Port 443 (HTTPS) + +
+
+
+
+ + Port 443 (HTTPS) + +
+
+
+ + + + + + + + + + + + + + +
+
+
+ + + Encrypted request for: someapp.example.com + + +
+
+
+
+ + Encrypted request for: someapp.example.com + +
+
+
+ + + + + + + +
+
+
+ + + Who is: someapp.example.com + + +
+
+
+
+ + Who is: someapp.example.com + +
+
+
+ + + + + + + +
+
+
+ + + IP: + +
+ + 123.124.125.126 + +
+
+
+
+
+ + IP:... + +
+
+
+ + + + + + + + + + +
+
+
+ + + TLS Handshake + + +
+
+
+
+ + TLS Handshake + +
+
+
+ + + + + + + + + + +
+
+
+ + + Encrypted response from: someapp.example.com + + +
+
+
+
+ + Encrypted response from: someapp.example.com + +
+
+
+ + + + + + + + + + + + + +
+
+
+ + + HTTPS certificates + +
+
+
+
+
+
+ + HTTPS certificates + +
+
+
+ + + + + + + +
+
+
+ + + + someapp.example.com + + +
+
+
+
+
+
+ + someapp.example.com + +
+
+
+ + + + + + + +
+
+
+ + + + another.example.net + + +
+
+
+
+
+
+ + another.example.net + +
+
+
+ + + + + + + +
+
+
+ + + + onemore.example.org + + +
+
+
+
+
+
+ + onemore.example.org + +
+
+
+ + + + + + + +
+
+
+ + + + IP: + +
+ + 123.124.125.126 + +
+
+
+
+
+
+
+ + IP:... + +
+
+
+ + + + + + + +
+
+
+ + https://someapp.example.com + +
+
+
+
+ + https://someapp.example.com + +
+
+
+
+ + + + + Text is not SVG - cannot display + + + +
diff --git a/docs/en/docs/img/deployment/https/https07.svg b/docs/en/docs/img/deployment/https/https07.svg deleted file mode 100644 index 551354cef..000000000 --- a/docs/en/docs/img/deployment/https/https07.svg +++ /dev/null @@ -1,62 +0,0 @@ -
Server(s)
Server(s)
https://someapp.example.com
https://someapp.example.com
DNS Servers
DNS Servers
TLS Termination Proxy
TLS Termination Proxy -
FastAPI app for: someapp.example.com
FastAPI app for: someapp.example.com
Plain response from: someapp.example.com
Plain response from: someapp.example.com
Decrypted request for: someapp.example.com
Decrypted request for: someapp.example.com
Port 443 (HTTPS)
Port 443 (HTTPS)
Encrypted request for: someapp.example.com
Encrypted request for: someapp.example.com
Who is: someapp.example.com
Who is: someapp.example.com
IP:
123.124.125.126
IP:...
TLS Handshake
TLS Handshake
Encrypted response from: someapp.example.com
Encrypted response from: someapp.example.com
HTTPS certificates
HTTPS certificates -
someapp.example.com
someapp.example.com -
another.example.net
another.example.net -
onemore.example.org
onemore.example.org -
IP:
123.124.125.126
IP:...
Viewer does not support full SVG 1.1
diff --git a/docs/en/docs/img/deployment/https/https08.drawio b/docs/en/docs/img/deployment/https/https08.drawio deleted file mode 100644 index 794b192df..000000000 --- a/docs/en/docs/img/deployment/https/https08.drawio +++ /dev/null @@ -1,217 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/docs/en/docs/img/deployment/https/https08.drawio.svg b/docs/en/docs/img/deployment/https/https08.drawio.svg new file mode 100644 index 000000000..8fc0b31ec --- /dev/null +++ b/docs/en/docs/img/deployment/https/https08.drawio.svg @@ -0,0 +1,625 @@ + + + + + + + + + + + + + + + + + +
+
+
+ + + Server(s) + + +
+
+
+
+ + Server(s) + +
+
+
+ + + + + + + + + + + +
+
+
+ + DNS Servers + +
+
+
+
+ + DNS Servers + +
+
+
+ + + + + + + + + + +
+
+
+ + + TLS Termination Proxy + +
+
+
+
+
+
+ + TLS Termination Proxy + +
+
+
+ + + + + + + + + + + + + + + +
+
+
+ + + FastAPI + + + app for: someapp.example.com + + +
+
+
+
+ + FastAPI app for: someapp.example.com + +
+
+
+ + + + + + + +
+
+
+ + + Another app + + + : another.example.com + + +
+
+
+
+ + Another app: another.example.com + +
+
+
+ + + + + + + +
+
+
+ + + One more app + + + : onemore.example.com + + +
+
+
+
+ + One more app: onemore.example.com + +
+
+
+ + + + + + + +
+
+
+ + + A Database + + +
+
+
+
+ + A Database + +
+
+
+ + + + + + + +
+
+
+ + + Plain response from: someapp.example.com + + +
+
+
+
+ + Plain response from: someapp.example.com + +
+
+
+ + + + + + + + + + + + + + +
+
+
+ + + Decrypted request for: someapp.example.com + + +
+
+
+
+ + Decrypted request for: someapp.example.com + +
+
+
+ + + + + + + + + + + + + + + + + + + + + +
+
+
+ + Port 443 (HTTPS) + +
+
+
+
+ + Port 443 (HTTPS) + +
+
+
+ + + + + + + + + + + + + + +
+
+
+ + + Encrypted request for: someapp.example.com + + +
+
+
+
+ + Encrypted request for: someapp.example.com + +
+
+
+ + + + + + + +
+
+
+ + + Who is: someapp.example.com + + +
+
+
+
+ + Who is: someapp.example.com + +
+
+
+ + + + + + + +
+
+
+ + + IP: + +
+ + 123.124.125.126 + +
+
+
+
+
+ + IP:... + +
+
+
+ + + + + + + + + + +
+
+
+ + + TLS Handshake + + +
+
+
+
+ + TLS Handshake + +
+
+
+ + + + + + + + + + +
+
+
+ + + Encrypted response from: someapp.example.com + + +
+
+
+
+ + Encrypted response from: someapp.example.com + +
+
+
+ + + + + + + + + + + + + +
+
+
+ + + HTTPS certificates + +
+
+
+
+
+
+ + HTTPS certificates + +
+
+
+ + + + + + + +
+
+
+ + + + someapp.example.com + + +
+
+
+
+
+
+ + someapp.example.com + +
+
+
+ + + + + + + +
+
+
+ + + + another.example.net + + +
+
+
+
+
+
+ + another.example.net + +
+
+
+ + + + + + + +
+
+
+ + + + onemore.example.org + + +
+
+
+
+
+
+ + onemore.example.org + +
+
+
+ + + + + + + +
+
+
+ + + + IP: + +
+ + 123.124.125.126 + +
+
+
+
+
+
+
+ + IP:... + +
+
+
+ + + + + + + +
+
+
+ + https://someapp.example.com + +
+
+
+
+ + https://someapp.example.com + +
+
+
+
+ + + + + Text is not SVG - cannot display + + + +
diff --git a/docs/en/docs/img/deployment/https/https08.svg b/docs/en/docs/img/deployment/https/https08.svg deleted file mode 100644 index 2d4680dcc..000000000 --- a/docs/en/docs/img/deployment/https/https08.svg +++ /dev/null @@ -1,62 +0,0 @@ -
Server(s)
Server(s)
https://someapp.example.com
https://someapp.example.com
DNS Servers
DNS Servers
TLS Termination Proxy
TLS Termination Proxy -
FastAPI app for: someapp.example.com
FastAPI app for: someapp.example.com
Another app: another.example.com
Another app: another.example.com
One more app: onemore.example.com
One more app: onemore.example.com
A Database
A Database
Plain response from: someapp.example.com
Plain response from: someapp.example.com
Decrypted request for: someapp.example.com
Decrypted request for: someapp.example.com
Port 443 (HTTPS)
Port 443 (HTTPS)
Encrypted request for: someapp.example.com
Encrypted request for: someapp.example.com
Who is: someapp.example.com
Who is: someapp.example.com
IP:
123.124.125.126
IP:...
TLS Handshake
TLS Handshake
Encrypted response from: someapp.example.com
Encrypted response from: someapp.example.com
HTTPS certificates
HTTPS certificates -
someapp.example.com
someapp.example.com -
another.example.net
another.example.net -
onemore.example.org
onemore.example.org -
IP:
123.124.125.126
IP:...
Viewer does not support full SVG 1.1
diff --git a/docs/en/docs/img/sponsors/coderabbit-banner.png b/docs/en/docs/img/sponsors/coderabbit-banner.png new file mode 100644 index 000000000..da3bb3482 Binary files /dev/null and b/docs/en/docs/img/sponsors/coderabbit-banner.png differ diff --git a/docs/en/docs/img/sponsors/coderabbit.png b/docs/en/docs/img/sponsors/coderabbit.png new file mode 100644 index 000000000..1fb74569b Binary files /dev/null and b/docs/en/docs/img/sponsors/coderabbit.png differ diff --git a/docs/en/docs/img/sponsors/interviewpal.png b/docs/en/docs/img/sponsors/interviewpal.png new file mode 100644 index 000000000..e40ed01fd Binary files /dev/null and b/docs/en/docs/img/sponsors/interviewpal.png differ diff --git a/docs/en/docs/img/sponsors/lambdatest.png b/docs/en/docs/img/sponsors/lambdatest.png new file mode 100644 index 000000000..674cbcb89 Binary files /dev/null and b/docs/en/docs/img/sponsors/lambdatest.png differ diff --git a/docs/en/docs/img/sponsors/subtotal-banner.svg b/docs/en/docs/img/sponsors/subtotal-banner.svg new file mode 100644 index 000000000..3d6c98dfc --- /dev/null +++ b/docs/en/docs/img/sponsors/subtotal-banner.svg @@ -0,0 +1,133 @@ + + + + + sponsorship-banner + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/en/docs/img/sponsors/subtotal.svg b/docs/en/docs/img/sponsors/subtotal.svg new file mode 100644 index 000000000..b944c1b2c --- /dev/null +++ b/docs/en/docs/img/sponsors/subtotal.svg @@ -0,0 +1,31 @@ + + + sponsorship-badge + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/en/docs/img/sponsors/zuplo.png b/docs/en/docs/img/sponsors/zuplo.png index 7a7c16862..6a4ed233e 100644 Binary files a/docs/en/docs/img/sponsors/zuplo.png and b/docs/en/docs/img/sponsors/zuplo.png differ diff --git a/docs/en/docs/img/tutorial/bigger-applications/package.drawio b/docs/en/docs/img/tutorial/bigger-applications/package.drawio deleted file mode 100644 index cab3de2ca..000000000 --- a/docs/en/docs/img/tutorial/bigger-applications/package.drawio +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/docs/en/docs/img/tutorial/bigger-applications/package.drawio.svg b/docs/en/docs/img/tutorial/bigger-applications/package.drawio.svg new file mode 100644 index 000000000..7e28f4a68 --- /dev/null +++ b/docs/en/docs/img/tutorial/bigger-applications/package.drawio.svg @@ -0,0 +1,420 @@ + + + + + + + + + + + + + + + + +
+
+
+ + Package app +
+ app/__init__.py +
+
+
+
+
+ + Package app... + +
+
+
+ + + + + + + +
+
+
+ + + Module app.main + +
+ + app/main.py + +
+
+
+
+
+ + Module app.main... + +
+
+
+ + + + + + + +
+
+
+ + + Module app.dependencies + +
+ + app/dependencies.py + +
+
+
+
+
+ + Module app.dependencies... + +
+
+
+ + + + + + + + + + +
+
+
+ + + Subpackage app.internal +
+
+ + app/internal/__init__.py + +
+ +
+
+
+
+
+
+ + Subpackage app.internal... + +
+
+
+ + + + + + + +
+
+
+ + + Module app.internal.admin + +
+ + app/internal/admin.py + +
+
+
+
+
+ + Module app.internal.admin... + +
+
+
+ + + + + + + + + + +
+
+
+ + + Subpackage app.routers +
+ app/routers/__init__.py +
+
+
+
+
+
+
+ + Subpackage app.routers... + +
+
+
+ + + + + + + +
+
+
+ + + Module app.routers.items + +
+ + app/routers/items.py + +
+
+
+
+
+ + Module app.routers.items... + +
+
+
+ + + + + + + +
+
+
+ + + Module app.routers.users + +
+ + app/routers/users.py + +
+
+
+
+
+ + Module app.routers.users... + +
+
+
+
+ + + + + Text is not SVG - cannot display + + + +
diff --git a/docs/en/docs/img/tutorial/bigger-applications/package.svg b/docs/en/docs/img/tutorial/bigger-applications/package.svg deleted file mode 100644 index 44da1dc30..000000000 --- a/docs/en/docs/img/tutorial/bigger-applications/package.svg +++ /dev/null @@ -1 +0,0 @@ -
Package app
app/__init__.py
Package app...
Module app.main
app/main.py
Module app.main...
Module app.dependencies
app/dependencies.py
Module app.dependencies...
Subpackage app.internal
app/internal/__init__.py
Subpackage app.internal...
Module app.internal.admin
app/internal/admin.py
Module app.internal.admin...
Subpackage app.routers
app/routers/__init__.py
Subpackage app.routers...
Module app.routers.items
app/routers/items.py
Module app.routers.items...
Module app.routers.users
app/routers/users.py
Module app.routers.users...
Viewer does not support full SVG 1.1
diff --git a/docs/en/docs/index.md b/docs/en/docs/index.md index cbe71c87d..0f3623ed5 100644 --- a/docs/en/docs/index.md +++ b/docs/en/docs/index.md @@ -12,7 +12,7 @@

- Test + Test Coverage @@ -146,7 +146,7 @@ $ pip install "fastapi[standard]" ### Create it -* Create a file `main.py` with: +Create a file `main.py` with: ```Python from typing import Union diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 449b880dc..1810527f7 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,8 +7,185 @@ hide: ## Latest Changes +### Upgrades + +* ⬆️ Update ReDoc to version 2.x. PR [#9700](https://github.com/fastapi/fastapi/pull/9700) by [@joakimnordling](https://github.com/joakimnordling). + +### Docs + +* 🍱 Update Drawio diagrams SVGs, single file per diagram, sans-serif font. PR [#13706](https://github.com/fastapi/fastapi/pull/13706) by [@tiangolo](https://github.com/tiangolo). +* 📝 Update docs for "Help FastAPI", simplify and reduce "sponsor" section. PR [#13670](https://github.com/fastapi/fastapi/pull/13670) by [@tiangolo](https://github.com/tiangolo). +* 📝 Remove unnecessary bullet from docs. PR [#13641](https://github.com/fastapi/fastapi/pull/13641) by [@Adamowoc](https://github.com/Adamowoc). +* ✏️ Fix syntax error in `docs/en/docs/tutorial/handling-errors.md`. PR [#13623](https://github.com/fastapi/fastapi/pull/13623) by [@gsheni](https://github.com/gsheni). +* 📝 Fix typo in documentation. PR [#13599](https://github.com/fastapi/fastapi/pull/13599) by [@Taoup](https://github.com/Taoup). +* 📝 Fix liblab client generation doc link. PR [#13571](https://github.com/fastapi/fastapi/pull/13571) by [@EFord36](https://github.com/EFord36). +* ✏️ Fix talk information typo. PR [#13544](https://github.com/fastapi/fastapi/pull/13544) by [@blueswen](https://github.com/blueswen). +* 📝 Add External Link: Taiwanese talk on FastAPI with observability . PR [#13527](https://github.com/fastapi/fastapi/pull/13527) by [@blueswen](https://github.com/blueswen). + +### Translations + +* 🌐 Add Bengali translation for `docs/bn/docs/environment-variables.md`. PR [#13629](https://github.com/fastapi/fastapi/pull/13629) by [@SakibSibly](https://github.com/SakibSibly). +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/query-params-str-validations.md` page. PR [#13546](https://github.com/fastapi/fastapi/pull/13546) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). +* 🌐 Add Russian translation for `docs/ru/docs/tutorial/cookie-param-models.md`. PR [#13616](https://github.com/fastapi/fastapi/pull/13616) by [@EgorOnishchuk](https://github.com/EgorOnishchuk). +* 🌐 Add Korean translation for `docs/ko/docs/tutorial/extra-models.md`. PR [#13063](https://github.com/fastapi/fastapi/pull/13063) by [@timothy-jeong](https://github.com/timothy-jeong). +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/path-params-numeric-validations.md` page. PR [#13548](https://github.com/fastapi/fastapi/pull/13548) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/middleware.md` page. PR [#13520](https://github.com/fastapi/fastapi/pull/13520) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/background-tasks.md` page. PR [#13502](https://github.com/fastapi/fastapi/pull/13502) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/cors.md` page. PR [#13519](https://github.com/fastapi/fastapi/pull/13519) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). +* 🌐 Update Korean translation for `docs/ko/docs/advanced/events.md`. PR [#13487](https://github.com/fastapi/fastapi/pull/13487) by [@bom1215](https://github.com/bom1215). +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/handling-errors.md` page. PR [#13420](https://github.com/fastapi/fastapi/pull/13420) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). +* 🌐 Add Russian translation for `docs/ru/docs/tutorial/request-form-models.md`. PR [#13552](https://github.com/fastapi/fastapi/pull/13552) by [@EgorOnishchuk](https://github.com/EgorOnishchuk). +* 📝 Fix internal anchor link in Spanish deployment docs. PR [#13737](https://github.com/fastapi/fastapi/pull/13737) by [@fabianfalon](https://github.com/fabianfalon). +* 🌐 Update Korean translation for `docs/ko/docs/virtual-environments.md`. PR [#13630](https://github.com/fastapi/fastapi/pull/13630) by [@sungchan1](https://github.com/sungchan1). +* 🌐 Add Russian translation for `docs/ru/docs/tutorial/header-param-models.md`. PR [#13526](https://github.com/fastapi/fastapi/pull/13526) by [@minaton-ru](https://github.com/minaton-ru). +* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/index.md`. PR [#13374](https://github.com/fastapi/fastapi/pull/13374) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). +* 🌐 Update Chinese translation for `docs/zh/docs/deployment/manually.md`. PR [#13324](https://github.com/fastapi/fastapi/pull/13324) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). +* 🌐 Update Chinese translation for `docs/zh/docs/deployment/server-workers.md`. PR [#13292](https://github.com/fastapi/fastapi/pull/13292) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). +* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/first-steps.md`. PR [#13348](https://github.com/fastapi/fastapi/pull/13348) by [@Zhongheng-Cheng](https://github.com/Zhongheng-Cheng). + +### Internal + +* ⬆ Bump typer from 0.15.3 to 0.16.0. PR [#13752](https://github.com/fastapi/fastapi/pull/13752) by [@dependabot[bot]](https://github.com/apps/dependabot). +* 👥 Update FastAPI GitHub topic repositories. PR [#13754](https://github.com/fastapi/fastapi/pull/13754) by [@tiangolo](https://github.com/tiangolo). +* 👥 Update FastAPI People - Sponsors. PR [#13750](https://github.com/fastapi/fastapi/pull/13750) by [@tiangolo](https://github.com/tiangolo). +* 👥 Update FastAPI People - Contributors and Translators. PR [#13749](https://github.com/fastapi/fastapi/pull/13749) by [@tiangolo](https://github.com/tiangolo). +* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#13736](https://github.com/fastapi/fastapi/pull/13736) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). +* 🔧 Update sponsors: Add InterviewPal. PR [#13728](https://github.com/fastapi/fastapi/pull/13728) by [@tiangolo](https://github.com/tiangolo). +* 🔧 Remove Google Analytics. PR [#13727](https://github.com/fastapi/fastapi/pull/13727) by [@tiangolo](https://github.com/tiangolo). +* 🔧 Update sponsors: remove MongoDB. PR [#13725](https://github.com/fastapi/fastapi/pull/13725) by [@tiangolo](https://github.com/tiangolo). +* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#13711](https://github.com/fastapi/fastapi/pull/13711) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). +* 🔧 Update sponsors: add Subtotal. PR [#13701](https://github.com/fastapi/fastapi/pull/13701) by [@tiangolo](https://github.com/tiangolo). +* 🔧 Update sponsors: remove deepset / Haystack. PR [#13700](https://github.com/fastapi/fastapi/pull/13700) by [@tiangolo](https://github.com/tiangolo). +* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#13688](https://github.com/fastapi/fastapi/pull/13688) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). +* 👥 Update FastAPI People - Experts. PR [#13671](https://github.com/fastapi/fastapi/pull/13671) by [@tiangolo](https://github.com/tiangolo). +* ⬆ Bump typer from 0.12.5 to 0.15.3. PR [#13666](https://github.com/fastapi/fastapi/pull/13666) by [@dependabot[bot]](https://github.com/apps/dependabot). +* ⬆ Bump sqlmodel from 0.0.23 to 0.0.24. PR [#13665](https://github.com/fastapi/fastapi/pull/13665) by [@dependabot[bot]](https://github.com/apps/dependabot). +* 🔧 Update Sponsors: Zuplo logo and alt text. PR [#13645](https://github.com/fastapi/fastapi/pull/13645) by [@martyndavies](https://github.com/martyndavies). +* 👥 Update FastAPI GitHub topic repositories. PR [#13667](https://github.com/fastapi/fastapi/pull/13667) by [@tiangolo](https://github.com/tiangolo). +* 🔧 Update links for LinkedIn and bottom. PR [#13669](https://github.com/fastapi/fastapi/pull/13669) by [@tiangolo](https://github.com/tiangolo). +* 🔧 Update sponsors: remove Bump.sh and Coherence. PR [#13668](https://github.com/fastapi/fastapi/pull/13668) by [@tiangolo](https://github.com/tiangolo). +* 👥 Update FastAPI People - Sponsors. PR [#13664](https://github.com/fastapi/fastapi/pull/13664) by [@tiangolo](https://github.com/tiangolo). +* 👥 Update FastAPI People - Contributors and Translators. PR [#13662](https://github.com/fastapi/fastapi/pull/13662) by [@tiangolo](https://github.com/tiangolo). +* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#13656](https://github.com/fastapi/fastapi/pull/13656) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). +* ✅ Use `inline-snapshot` to support different Pydantic versions in the test suite. PR [#12534](https://github.com/fastapi/fastapi/pull/12534) by [@15r10nk](https://github.com/15r10nk). +* ⬆ Bump astral-sh/setup-uv from 5 to 6. PR [#13648](https://github.com/fastapi/fastapi/pull/13648) by [@dependabot[bot]](https://github.com/apps/dependabot). +* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#13634](https://github.com/fastapi/fastapi/pull/13634) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). +* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#13619](https://github.com/fastapi/fastapi/pull/13619) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). +* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#13594](https://github.com/fastapi/fastapi/pull/13594) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). +* 👥 Update FastAPI People - Experts. PR [#13568](https://github.com/fastapi/fastapi/pull/13568) by [@tiangolo](https://github.com/tiangolo). +* 👥 Update FastAPI GitHub topic repositories. PR [#13565](https://github.com/fastapi/fastapi/pull/13565) by [@tiangolo](https://github.com/tiangolo). +* 👥 Update FastAPI People - Sponsors. PR [#13559](https://github.com/fastapi/fastapi/pull/13559) by [@tiangolo](https://github.com/tiangolo). +* 👥 Update FastAPI People - Contributors and Translators. PR [#13558](https://github.com/fastapi/fastapi/pull/13558) by [@tiangolo](https://github.com/tiangolo). +* ⬆ Bump dirty-equals from 0.8.0 to 0.9.0. PR [#13561](https://github.com/fastapi/fastapi/pull/13561) by [@dependabot[bot]](https://github.com/apps/dependabot). +* 🔧 Clean up `docs/en/mkdocs.yml` configuration file. PR [#13542](https://github.com/fastapi/fastapi/pull/13542) by [@svlandeg](https://github.com/svlandeg). +* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12986](https://github.com/fastapi/fastapi/pull/12986) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). + +## 0.115.12 + +### Fixes + +* 🐛 Fix `convert_underscores=False` for header Pydantic models. PR [#13515](https://github.com/fastapi/fastapi/pull/13515) by [@tiangolo](https://github.com/tiangolo). + +### Docs + +* 📝 Update `docs/en/docs/tutorial/middleware.md`. PR [#13444](https://github.com/fastapi/fastapi/pull/13444) by [@Rishat-F](https://github.com/Rishat-F). +* 👥 Update FastAPI People - Experts. PR [#13493](https://github.com/fastapi/fastapi/pull/13493) by [@tiangolo](https://github.com/tiangolo). + +### Translations + +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/metadata.md` page. PR [#13459](https://github.com/fastapi/fastapi/pull/13459) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/response-status-code.md` page. PR [#13462](https://github.com/fastapi/fastapi/pull/13462) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/cookie-param-models.md` page. PR [#13460](https://github.com/fastapi/fastapi/pull/13460) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/header-param-models.md` page. PR [#13461](https://github.com/fastapi/fastapi/pull/13461) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). +* 🌐 Add Japanese translation for `docs/ja/docs/virtual-environments.md`. PR [#13304](https://github.com/fastapi/fastapi/pull/13304) by [@k94-ishi](https://github.com/k94-ishi). +* 🌐 Add Korean translation for `docs/ko/docs/tutorial/security/oauth2-jwt.md`. PR [#13333](https://github.com/fastapi/fastapi/pull/13333) by [@yes0ng](https://github.com/yes0ng). +* 🌐 Add Vietnamese translation for `docs/vi/docs/deployment/cloud.md`. PR [#13407](https://github.com/fastapi/fastapi/pull/13407) by [@ptt3199](https://github.com/ptt3199). + +### Internal + +* ⬆ Bump pydantic-ai from 0.0.15 to 0.0.30. PR [#13438](https://github.com/fastapi/fastapi/pull/13438) by [@dependabot[bot]](https://github.com/apps/dependabot). +* ⬆ Bump sqlmodel from 0.0.22 to 0.0.23. PR [#13437](https://github.com/fastapi/fastapi/pull/13437) by [@dependabot[bot]](https://github.com/apps/dependabot). +* ⬆ Bump black from 24.10.0 to 25.1.0. PR [#13436](https://github.com/fastapi/fastapi/pull/13436) by [@dependabot[bot]](https://github.com/apps/dependabot). +* ⬆ Bump ruff to 0.9.4. PR [#13299](https://github.com/fastapi/fastapi/pull/13299) by [@dependabot[bot]](https://github.com/apps/dependabot). +* 🔧 Update sponsors: pause TestDriven. PR [#13446](https://github.com/fastapi/fastapi/pull/13446) by [@tiangolo](https://github.com/tiangolo). + +## 0.115.11 + +### Fixes + +* 🐛 Add docs examples and tests (support) for `Annotated` custom validations, like `AfterValidator`, revert [#13440](https://github.com/fastapi/fastapi/pull/13440). PR [#13442](https://github.com/fastapi/fastapi/pull/13442) by [@tiangolo](https://github.com/tiangolo). + * New docs: [Query Parameters and String Validations - Custom Validation](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#custom-validation). + +### Translations + +* 🌐 Add Russian translation for `docs/ru/docs/tutorial/middleware.md`. PR [#13412](https://github.com/fastapi/fastapi/pull/13412) by [@alv2017](https://github.com/alv2017). + +### Internal + +* 👥 Update FastAPI GitHub topic repositories. PR [#13439](https://github.com/fastapi/fastapi/pull/13439) by [@tiangolo](https://github.com/tiangolo). +* 👥 Update FastAPI People - Contributors and Translators. PR [#13432](https://github.com/fastapi/fastapi/pull/13432) by [@tiangolo](https://github.com/tiangolo). +* 👥 Update FastAPI People - Sponsors. PR [#13433](https://github.com/fastapi/fastapi/pull/13433) by [@tiangolo](https://github.com/tiangolo). + +## 0.115.10 + +### Fixes + +* ♻️ Update internal annotation usage for compatibility with Pydantic 2.11. PR [#13314](https://github.com/fastapi/fastapi/pull/13314) by [@Viicos](https://github.com/Viicos). + +### Upgrades + +* ⬆️ Bump Starlette to allow up to 0.46.0: `>=0.40.0,<0.47.0`. PR [#13426](https://github.com/fastapi/fastapi/pull/13426) by [@musicinmybrain](https://github.com/musicinmybrain). + +### Translations + +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/debugging.md`. PR [#13370](https://github.com/fastapi/fastapi/pull/13370) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/query-params.md`. PR [#13362](https://github.com/fastapi/fastapi/pull/13362) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/path-params.md`. PR [#13354](https://github.com/fastapi/fastapi/pull/13354) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/cookie-param-models.md`. PR [#13330](https://github.com/fastapi/fastapi/pull/13330) by [@k94-ishi](https://github.com/k94-ishi). +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/body-multiple-params.md`. PR [#13408](https://github.com/fastapi/fastapi/pull/13408) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). +* 🌐 Add Japanese translation for `docs/ja/docs/tutorial/query-param-models.md`. PR [#13323](https://github.com/fastapi/fastapi/pull/13323) by [@k94-ishi](https://github.com/k94-ishi). +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/body-nested-models.md`. PR [#13409](https://github.com/fastapi/fastapi/pull/13409) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). +* 🌐 Add Vietnamese translation for `docs/vi/docs/deployment/versions.md`. PR [#13406](https://github.com/fastapi/fastapi/pull/13406) by [@ptt3199](https://github.com/ptt3199). +* 🌐 Add Vietnamese translation for `docs/vi/docs/deployment/index.md`. PR [#13405](https://github.com/fastapi/fastapi/pull/13405) by [@ptt3199](https://github.com/ptt3199). +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/request-forms.md`. PR [#13383](https://github.com/fastapi/fastapi/pull/13383) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/testing.md`. PR [#13371](https://github.com/fastapi/fastapi/pull/13371) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). + +## 0.115.9 + +### Fixes + +* 🐛 Ensure that `HTTPDigest` only raises an exception when `auto_error is True`. PR [#2939](https://github.com/fastapi/fastapi/pull/2939) by [@arthurio](https://github.com/arthurio). + +### Refactors + +* ✅ Simplify tests for `query_params_str_validations`. PR [#13218](https://github.com/fastapi/fastapi/pull/13218) by [@alv2017](https://github.com/alv2017). +* ✅ Simplify tests for `app_testing`. PR [#13220](https://github.com/fastapi/fastapi/pull/13220) by [@alv2017](https://github.com/alv2017). +* ✅ Simplify tests for `dependency_testing`. PR [#13223](https://github.com/fastapi/fastapi/pull/13223) by [@alv2017](https://github.com/alv2017). + +### Docs + +* 🍱 Update sponsors: CodeRabbit logo. PR [#13424](https://github.com/fastapi/fastapi/pull/13424) by [@tiangolo](https://github.com/tiangolo). +* 🩺 Unify the badges across all tutorial translations. PR [#13329](https://github.com/fastapi/fastapi/pull/13329) by [@svlandeg](https://github.com/svlandeg). +* 📝 Fix typos in virtual environments documentation. PR [#13396](https://github.com/fastapi/fastapi/pull/13396) by [@bullet-ant](https://github.com/bullet-ant). +* 🐛 Fix issue with Swagger theme change example in the official tutorial. PR [#13289](https://github.com/fastapi/fastapi/pull/13289) by [@Zerohertz](https://github.com/Zerohertz). +* 📝 Add more precise description of HTTP status code range in docs. PR [#13347](https://github.com/fastapi/fastapi/pull/13347) by [@DanielYang59](https://github.com/DanielYang59). +* 🔥 Remove manual type annotations in JWT tutorial to avoid typing expectations (JWT doesn't provide more types). PR [#13378](https://github.com/fastapi/fastapi/pull/13378) by [@tiangolo](https://github.com/tiangolo). +* 📝 Update docs for Query Params and String Validations, remove obsolete Ellipsis docs (`...`). PR [#13377](https://github.com/fastapi/fastapi/pull/13377) by [@tiangolo](https://github.com/tiangolo). +* ✏️ Remove duplicate title in docs `body-multiple-params`. PR [#13345](https://github.com/fastapi/fastapi/pull/13345) by [@DanielYang59](https://github.com/DanielYang59). +* 📝 Fix test badge. PR [#13313](https://github.com/fastapi/fastapi/pull/13313) by [@esadek](https://github.com/esadek). + ### Translations +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/header-params.md`. PR [#13381](https://github.com/fastapi/fastapi/pull/13381) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/request-files.md`. PR [#13395](https://github.com/fastapi/fastapi/pull/13395) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/request-form-models.md`. PR [#13384](https://github.com/fastapi/fastapi/pull/13384) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). +* 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/request-forms-and-files.md`. PR [#13386](https://github.com/fastapi/fastapi/pull/13386) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). +* 🌐 Update Korean translation for `docs/ko/docs/help-fastapi.md`. PR [#13262](https://github.com/fastapi/fastapi/pull/13262) by [@Zerohertz](https://github.com/Zerohertz). +* 🌐 Add Korean translation for `docs/ko/docs/advanced/custom-response.md`. PR [#13265](https://github.com/fastapi/fastapi/pull/13265) by [@11kkw](https://github.com/11kkw). +* 🌐 Update Korean translation for `docs/ko/docs/tutorial/security/simple-oauth2.md`. PR [#13335](https://github.com/fastapi/fastapi/pull/13335) by [@yes0ng](https://github.com/yes0ng). +* 🌐 Add Russian translation for `docs/ru/docs/advanced/response-cookies.md`. PR [#13327](https://github.com/fastapi/fastapi/pull/13327) by [@Stepakinoyan](https://github.com/Stepakinoyan). +* 🌐 Add Vietnamese translation for `docs/vi/docs/tutorial/static-files.md`. PR [#11291](https://github.com/fastapi/fastapi/pull/11291) by [@ptt3199](https://github.com/ptt3199). +* 🌐 Add Korean translation for `docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#13257](https://github.com/fastapi/fastapi/pull/13257) by [@11kkw](https://github.com/11kkw). * 🌐 Add Vietnamese translation for `docs/vi/docs/virtual-environments.md`. PR [#13282](https://github.com/fastapi/fastapi/pull/13282) by [@ptt3199](https://github.com/ptt3199). * 🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/static-files.md`. PR [#13285](https://github.com/fastapi/fastapi/pull/13285) by [@valentinDruzhinin](https://github.com/valentinDruzhinin). * 🌐 Add Vietnamese translation for `docs/vi/docs/environment-variables.md`. PR [#13287](https://github.com/fastapi/fastapi/pull/13287) by [@ptt3199](https://github.com/ptt3199). @@ -21,6 +198,12 @@ hide: ### Internal +* ✅ Fix a minor bug in the test `tests/test_modules_same_name_body/test_main.py`. PR [#13411](https://github.com/fastapi/fastapi/pull/13411) by [@alv2017](https://github.com/alv2017). +* 👷 Use `wrangler-action` v3. PR [#13415](https://github.com/fastapi/fastapi/pull/13415) by [@joakimnordling](https://github.com/joakimnordling). +* 🔧 Update sponsors: add CodeRabbit. PR [#13402](https://github.com/fastapi/fastapi/pull/13402) by [@tiangolo](https://github.com/tiangolo). +* 🔧 Update team: Add Ludovico. PR [#13390](https://github.com/fastapi/fastapi/pull/13390) by [@tiangolo](https://github.com/tiangolo). +* 🔧 Update sponsors: Add LambdaTest. PR [#13389](https://github.com/fastapi/fastapi/pull/13389) by [@tiangolo](https://github.com/tiangolo). +* ⬆ Bump cloudflare/wrangler-action from 3.13 to 3.14. PR [#13350](https://github.com/fastapi/fastapi/pull/13350) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump mkdocs-material from 9.5.18 to 9.6.1. PR [#13301](https://github.com/fastapi/fastapi/pull/13301) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump pillow from 11.0.0 to 11.1.0. PR [#13300](https://github.com/fastapi/fastapi/pull/13300) by [@dependabot[bot]](https://github.com/apps/dependabot). * 👥 Update FastAPI People - Sponsors. PR [#13295](https://github.com/fastapi/fastapi/pull/13295) by [@tiangolo](https://github.com/tiangolo). diff --git a/docs/en/docs/tutorial/bigger-applications.md b/docs/en/docs/tutorial/bigger-applications.md index 605ced0d3..f5f29a173 100644 --- a/docs/en/docs/tutorial/bigger-applications.md +++ b/docs/en/docs/tutorial/bigger-applications.md @@ -52,7 +52,7 @@ from app.routers import items * There's also a subdirectory `app/internal/` with another file `__init__.py`, so it's another "Python subpackage": `app.internal`. * And the file `app/internal/admin.py` is another submodule: `app.internal.admin`. - + The same file structure with comments: @@ -270,7 +270,7 @@ But that file doesn't exist, our dependencies are in a file at `app/dependencies Remember how our app/file structure looks like: - + --- diff --git a/docs/en/docs/tutorial/body-multiple-params.md b/docs/en/docs/tutorial/body-multiple-params.md index 9fced9652..71b308bb4 100644 --- a/docs/en/docs/tutorial/body-multiple-params.md +++ b/docs/en/docs/tutorial/body-multiple-params.md @@ -10,8 +10,6 @@ And you can also declare body parameters as optional, by setting the default to {* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *} -## Multiple body parameters - /// note Notice that, in this case, the `item` that would be taken from the body is optional. As it has a `None` default value. diff --git a/docs/en/docs/tutorial/handling-errors.md b/docs/en/docs/tutorial/handling-errors.md index 4d969747f..5b8e677e4 100644 --- a/docs/en/docs/tutorial/handling-errors.md +++ b/docs/en/docs/tutorial/handling-errors.md @@ -35,7 +35,7 @@ Because it's a Python exception, you don't `return` it, you `raise` it. This also means that if you are inside a utility function that you are calling inside of your *path operation function*, and you raise the `HTTPException` from inside of that utility function, it won't run the rest of the code in the *path operation function*, it will terminate that request right away and send the HTTP error from the `HTTPException` to the client. -The benefit of raising an exception over `return`ing a value will be more evident in the section about Dependencies and Security. +The benefit of raising an exception over returning a value will be more evident in the section about Dependencies and Security. In this example, when the client requests an item by an ID that doesn't exist, raise an exception with a status code of `404`: @@ -252,4 +252,4 @@ If you want to use the exception along with the same default exception handlers {* ../../docs_src/handling_errors/tutorial006.py hl[2:5,15,21] *} -In this example you are just `print`ing the error with a very expressive message, but you get the idea. You can use the exception and then just reuse the default exception handlers. +In this example you are just printing the error with a very expressive message, but you get the idea. You can use the exception and then just reuse the default exception handlers. diff --git a/docs/en/docs/tutorial/header-param-models.md b/docs/en/docs/tutorial/header-param-models.md index 73950a668..4cdf09705 100644 --- a/docs/en/docs/tutorial/header-param-models.md +++ b/docs/en/docs/tutorial/header-param-models.md @@ -51,6 +51,22 @@ For example, if the client tries to send a `tool` header with a value of `plumbu } ``` +## Disable Convert Underscores + +The same way as with regular header parameters, when you have underscore characters in the parameter names, they are **automatically converted to hyphens**. + +For example, if you have a header parameter `save_data` in the code, the expected HTTP header will be `save-data`, and it will show up like that in the docs. + +If for some reason you need to disable this automatic conversion, you can do it as well for Pydantic models for header parameters. + +{* ../../docs_src/header_param_models/tutorial003_an_py310.py hl[19] *} + +/// warning + +Before setting `convert_underscores` to `False`, bear in mind that some HTTP proxies and servers disallow the usage of headers with underscores. + +/// + ## Summary You can use **Pydantic models** to declare **headers** in **FastAPI**. 😎 diff --git a/docs/en/docs/tutorial/middleware.md b/docs/en/docs/tutorial/middleware.md index 53c47a085..4f7980165 100644 --- a/docs/en/docs/tutorial/middleware.md +++ b/docs/en/docs/tutorial/middleware.md @@ -15,7 +15,7 @@ A "middleware" is a function that works with every **request** before it is proc If you have dependencies with `yield`, the exit code will run *after* the middleware. -If there were any background tasks (documented later), they will run *after* all the middleware. +If there were any background tasks (covered in the [Background Tasks](background-tasks.md){.internal-link target=_blank} section, you will see it later), they will run *after* all the middleware. /// diff --git a/docs/en/docs/tutorial/query-params-str-validations.md b/docs/en/docs/tutorial/query-params-str-validations.md index 1bf16334d..e50fc347c 100644 --- a/docs/en/docs/tutorial/query-params-str-validations.md +++ b/docs/en/docs/tutorial/query-params-str-validations.md @@ -6,13 +6,13 @@ Let's take this application as example: {* ../../docs_src/query_params_str_validations/tutorial001_py310.py hl[7] *} -The query parameter `q` is of type `Union[str, None]` (or `str | None` in Python 3.10), that means that it's of type `str` but could also be `None`, and indeed, the default value is `None`, so FastAPI will know it's not required. +The query parameter `q` is of type `str | None`, that means that it's of type `str` but could also be `None`, and indeed, the default value is `None`, so FastAPI will know it's not required. /// note FastAPI will know that the value of `q` is not required because of the default value `= None`. -The `Union` in `Union[str, None]` will allow your editor to give you better support and detect errors. +Having `str | None` will allow your editor to give you better support and detect errors. /// @@ -25,29 +25,9 @@ We are going to enforce that even though `q` is optional, whenever it is provide To achieve that, first import: * `Query` from `fastapi` -* `Annotated` from `typing` (or from `typing_extensions` in Python below 3.9) +* `Annotated` from `typing` -//// tab | Python 3.10+ - -In Python 3.9 or above, `Annotated` is part of the standard library, so you can import it from `typing`. - -```Python hl_lines="1 3" -{!> ../../docs_src/query_params_str_validations/tutorial002_an_py310.py!} -``` - -//// - -//// tab | Python 3.8+ - -In versions of Python below Python 3.9 you import `Annotated` from `typing_extensions`. - -It will already be installed with FastAPI. - -```Python hl_lines="3-4" -{!> ../../docs_src/query_params_str_validations/tutorial002_an.py!} -``` - -//// +{* ../../docs_src/query_params_str_validations/tutorial002_an_py310.py hl[1,3] *} /// info @@ -145,54 +125,23 @@ As in this case (without using `Annotated`) we have to replace the default value So: -```Python -q: Union[str, None] = Query(default=None) -``` - -...makes the parameter optional, with a default value of `None`, the same as: - -```Python -q: Union[str, None] = None -``` - -And in Python 3.10 and above: - ```Python q: str | None = Query(default=None) ``` ...makes the parameter optional, with a default value of `None`, the same as: -```Python -q: str | None = None -``` - -But the `Query` versions declare it explicitly as being a query parameter. - -/// info - -Keep in mind that the most important part to make a parameter optional is the part: ```Python -= None -``` - -or the: - -```Python -= Query(default=None) +q: str | None = None ``` -as it will use that `None` as the default value, and that way make the parameter **not required**. - -The `Union[str, None]` part allows your editor to provide better support, but it is not what tells FastAPI that this parameter is not required. - -/// +But the `Query` version declares it explicitly as being a query parameter. Then, we can pass more parameters to `Query`. In this case, the `max_length` parameter that applies to strings: ```Python -q: Union[str, None] = Query(default=None, max_length=50) +q: str | None = Query(default=None, max_length=50) ``` This will validate the data, show a clear error when the data is not valid, and document the parameter in the OpenAPI schema *path operation*. @@ -201,7 +150,7 @@ This will validate the data, show a clear error when the data is not valid, and 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. +Instead, use the actual default value of the function parameter. Otherwise, it would be inconsistent. For example, this is not allowed: @@ -255,7 +204,7 @@ This specific regular expression pattern checks that the received parameter valu If you feel lost with all these **"regular expression"** ideas, don't worry. They are a hard topic for many people. You can still do a lot of stuff without needing regular expressions yet. -But whenever you need them and go and learn them, know that you can already use them directly in **FastAPI**. +Now you know that whenever you need them you can use them in **FastAPI**. ### Pydantic v1 `regex` instead of `pattern` @@ -296,7 +245,7 @@ q: str instead of: ```Python -q: Union[str, None] = None +q: str | None = None ``` But we are now declaring it with `Query`, for example like: @@ -304,15 +253,7 @@ But we are now declaring it with `Query`, for example like: //// tab | Annotated ```Python -q: Annotated[Union[str, None], Query(min_length=3)] = None -``` - -//// - -//// tab | non-Annotated - -```Python -q: Union[str, None] = Query(default=None, min_length=3) +q: Annotated[str | None, Query(min_length=3)] = None ``` //// @@ -321,42 +262,14 @@ So, when you need to declare a value as required while using `Query`, you can si {* ../../docs_src/query_params_str_validations/tutorial006_an_py39.py hl[9] *} -### Required with Ellipsis (`...`) - -There's an alternative way to explicitly declare that a value is required. You can set the default to the literal value `...`: - -{* ../../docs_src/query_params_str_validations/tutorial006b_an_py39.py hl[9] *} - -/// info - -If you hadn't seen that `...` before: it is a special single value, it is part of Python and is called "Ellipsis". - -It is used by Pydantic and FastAPI to explicitly declare that a value is required. - -/// - -This will let **FastAPI** know that this parameter is required. - ### Required, can be `None` You can declare that a parameter can accept `None`, but that it's still required. This would force clients to send a value, even if the value is `None`. -To do that, you can declare that `None` is a valid type but still use `...` as the default: +To do that, you can declare that `None` is a valid type but simply do not declare a default value: {* ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py hl[9] *} -/// tip - -Pydantic, which is what powers all the data validation and serialization in FastAPI, has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about Required fields. - -/// - -/// tip - -Remember that in most of the cases, when something is required, you can simply omit the default, so you normally don't have to use `...`. - -/// - ## Query parameter list / multiple values When you define a query parameter explicitly with `Query` you can also declare it to receive a list of values, or said in another way, to receive multiple values. @@ -396,7 +309,7 @@ The interactive API docs will update accordingly, to allow multiple values: ### Query parameter list / multiple values with defaults -And you can also define a default `list` of values if none are provided: +You can also define a default `list` of values if none are provided: {* ../../docs_src/query_params_str_validations/tutorial012_an_py39.py hl[9] *} @@ -419,7 +332,7 @@ the default of `q` will be: `["foo", "bar"]` and your response will be: #### Using just `list` -You can also use `list` directly instead of `List[str]` (or `list[str]` in Python 3.9+): +You can also use `list` directly instead of `list[str]`: {* ../../docs_src/query_params_str_validations/tutorial013_an_py39.py hl[9] *} @@ -427,7 +340,7 @@ You can also use `list` directly instead of `List[str]` (or `list[str]` in Pytho 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. +For example, `list[int]` would check (and document) that the contents of the list are integers. But `list` alone wouldn't. /// @@ -493,6 +406,68 @@ To exclude a query parameter from the generated OpenAPI schema (and thus, from t {* ../../docs_src/query_params_str_validations/tutorial014_an_py310.py hl[10] *} +## Custom Validation + +There could be cases where you need to do some **custom validation** that can't be done with the parameters shown above. + +In those cases, you can use a **custom validator function** that is applied after the normal validation (e.g. after validating that the value is a `str`). + +You can achieve that using Pydantic's `AfterValidator` inside of `Annotated`. + +/// tip + +Pydantic also has `BeforeValidator` and others. 🤓 + +/// + +For example, this custom validator checks that the item ID starts with `isbn-` for an ISBN book number or with `imdb-` for an IMDB movie URL ID: + +{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py hl[5,16:19,24] *} + +/// info + +This is available with Pydantic version 2 or above. 😎 + +/// + +/// tip + +If you need to do any type of validation that requires communicating with any **external component**, like a database or another API, you should instead use **FastAPI Dependencies**, you will learn about them later. + +These custom validators are for things that can be checked with **only** the **same data** provided in the request. + +/// + +### Understand that Code + +The important point is just using **`AfterValidator` with a function inside `Annotated`**. Feel free to skip this part. 🤸 + +--- + +But if you're curious about this specific code example and you're still entertained, here are some extra details. + +#### String with `value.startswith()` + +Did you notice? a string using `value.startswith()` can take a tuple, and it will check each value in the tuple: + +{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[16:19] hl[17] *} + +#### A Random Item + +With `data.items()` we get an iterable object with tuples containing the key and value for each dictionary item. + +We convert this iterable object into a proper `list` with `list(data.items())`. + +Then with `random.choice()` we can get a **random value** from the list, so, we get a tuple with `(id, name)`. It will be something like `("imdb-tt0371724", "The Hitchhiker's Guide to the Galaxy")`. + +Then we **assign those two values** of the tuple to the variables `id` and `name`. + +So, if the user didn't provide an item ID, they will still receive a random suggestion. + +...we do all this in a **single simple line**. 🤯 Don't you love Python? 🐍 + +{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[22:30] hl[29] *} + ## Recap You can declare additional validations and metadata for your parameters. @@ -510,6 +485,8 @@ Validations specific for strings: * `max_length` * `pattern` +Custom validations using `AfterValidator`. + In these examples you saw how to declare validations for `str` values. See the next chapters to learn how to declare validations for other types, like numbers. diff --git a/docs/en/docs/tutorial/response-status-code.md b/docs/en/docs/tutorial/response-status-code.md index 711042a46..41bf02a8f 100644 --- a/docs/en/docs/tutorial/response-status-code.md +++ b/docs/en/docs/tutorial/response-status-code.md @@ -53,16 +53,16 @@ These status codes have a name associated to recognize them, but the important p In short: -* `100` and above are for "Information". You rarely use them directly. Responses with these status codes cannot have a body. -* **`200`** and above are for "Successful" responses. These are the ones you would use the most. +* `100 - 199` are for "Information". You rarely use them directly. Responses with these status codes cannot have a body. +* **`200 - 299`** are for "Successful" responses. These are the ones you would use the most. * `200` is the default status code, which means everything was "OK". * Another example would be `201`, "Created". It is commonly used after creating a new record in the database. * A special case is `204`, "No Content". This response is used when there is no content to return to the client, and so the response must not have a body. -* **`300`** and above are for "Redirection". Responses with these status codes may or may not have a body, except for `304`, "Not Modified", which must not have one. -* **`400`** and above are for "Client error" responses. These are the second type you would probably use the most. +* **`300 - 399`** are for "Redirection". Responses with these status codes may or may not have a body, except for `304`, "Not Modified", which must not have one. +* **`400 - 499`** are for "Client error" responses. These are the second type you would probably use the most. * An example is `404`, for a "Not Found" response. * For generic errors from the client, you can just use `400`. -* `500` and above are for server errors. You almost never use them directly. When something goes wrong at some part in your application code, or server, it will automatically return one of these status codes. +* `500 - 599` are for server errors. You almost never use them directly. When something goes wrong at some part in your application code, or server, it will automatically return one of these status codes. /// tip diff --git a/docs/en/docs/virtual-environments.md b/docs/en/docs/virtual-environments.md index b75be18c3..4f65b3b80 100644 --- a/docs/en/docs/virtual-environments.md +++ b/docs/en/docs/virtual-environments.md @@ -668,7 +668,7 @@ After activating the virtual environment, the `PATH` variable would look somethi /home/user/code/awesome-project/.venv/bin:/usr/bin:/bin:/usr/sbin:/sbin ``` -That means that the system will now start looking first look for programs in: +That means that the system will now start looking first for programs in: ```plaintext /home/user/code/awesome-project/.venv/bin @@ -692,7 +692,7 @@ and use that one. C:\Users\user\code\awesome-project\.venv\Scripts;C:\Windows\System32 ``` -That means that the system will now start looking first look for programs in: +That means that the system will now start looking first for programs in: ```plaintext C:\Users\user\code\awesome-project\.venv\Scripts diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index e9a639d0b..8a5ea13e0 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -6,7 +6,7 @@ theme: name: material custom_dir: ../en/overrides palette: - - media: "(prefers-color-scheme)" + - media: (prefers-color-scheme) toggle: icon: material/lightbulb-auto name: Switch to light mode @@ -27,7 +27,6 @@ theme: features: - content.code.annotate - content.code.copy - # - content.code.select - content.footnote.tooltips - content.tabs.link - content.tooltips @@ -35,7 +34,6 @@ theme: - navigation.indexes - navigation.instant - navigation.instant.prefetch - # - navigation.instant.preview - navigation.instant.progress - navigation.path - navigation.tabs @@ -46,7 +44,6 @@ theme: - search.share - search.suggest - toc.follow - icon: repo: fontawesome/brands/github-alt logo: img/icon-white.svg @@ -55,11 +52,7 @@ theme: repo_name: fastapi/fastapi repo_url: https://github.com/fastapi/fastapi plugins: - # Material for MkDocs - search: - # Configured in mkdocs.insiders.yml - # social: - # Other plugins + search: null macros: include_yaml: - external_links: ../en/data/external_links.yml @@ -103,7 +96,6 @@ plugins: signature_crossrefs: true show_symbol_type_heading: true show_symbol_type_toc: true - nav: - FastAPI: index.md - features.md @@ -258,33 +250,27 @@ nav: - benchmarks.md - management.md - release-notes.md - markdown_extensions: - # Python Markdown - abbr: - attr_list: - footnotes: - md_in_html: - tables: + abbr: null + attr_list: null + footnotes: null + md_in_html: null + tables: null toc: permalink: true - - # Python Markdown Extensions - pymdownx.betterem: - pymdownx.caret: + pymdownx.betterem: null + pymdownx.caret: null pymdownx.highlight: line_spans: __span - pymdownx.inlinehilite: - pymdownx.keys: - pymdownx.mark: + pymdownx.inlinehilite: null + pymdownx.keys: null + pymdownx.mark: null pymdownx.superfences: custom_fences: - name: mermaid class: mermaid - format: !!python/name:pymdownx.superfences.fence_code_format - pymdownx.tilde: - - # pymdownx blocks + format: !!python/name:pymdownx.superfences.fence_code_format '' + pymdownx.tilde: null pymdownx.blocks.admonition: types: - note @@ -295,34 +281,14 @@ markdown_extensions: - tip - hint - warning - # Custom types - info - check - pymdownx.blocks.details: + pymdownx.blocks.details: null pymdownx.blocks.tab: - alternate_style: True - - # Other extensions - mdx_include: - markdown_include_variants: - + alternate_style: true + mdx_include: null + markdown_include_variants: null extra: - analytics: - provider: google - property: G-YNEVN69SC3 - feedback: - title: Was this page helpful? - ratings: - - icon: material/emoticon-happy-outline - name: This page was helpful - data: 1 - note: >- - Thanks for your feedback! - - icon: material/emoticon-sad-outline - name: This page could be improved - data: 0 - note: >- - Thanks for your feedback! social: - icon: fontawesome/brands/github-alt link: https://github.com/fastapi/fastapi @@ -331,14 +297,9 @@ extra: - icon: fontawesome/brands/twitter link: https://twitter.com/fastapi - icon: fontawesome/brands/linkedin - link: https://www.linkedin.com/in/tiangolo - - icon: fontawesome/brands/dev - link: https://dev.to/tiangolo - - icon: fontawesome/brands/medium - link: https://medium.com/@tiangolo + link: https://www.linkedin.com/company/fastapi - icon: fontawesome/solid/globe link: https://tiangolo.com - alternate: - link: / name: en - English @@ -390,14 +351,11 @@ extra: name: zh-hant - 繁體中文 - link: /em/ name: 😉 - extra_css: - css/termynal.css - css/custom.css - extra_javascript: - js/termynal.js - js/custom.js - hooks: - ../../scripts/mkdocs_hooks.py diff --git a/docs/en/overrides/main.html b/docs/en/overrides/main.html index b58ed8818..89c8171d0 100644 --- a/docs/en/overrides/main.html +++ b/docs/en/overrides/main.html @@ -10,6 +10,13 @@ Follow @fastapi on Twitter to stay updated +

+ + + {% include ".icons/fontawesome/brands/linkedin.svg" %} + Follow FastAPI on LinkedIn to stay updated + +
@@ -17,9 +24,6 @@ Subscribe to the FastAPI and friends newsletter 🎉
-
- You can now sponsor FastAPI 🍰 -
@@ -40,12 +44,6 @@
-
- - - - -
@@ -59,33 +57,33 @@
- + - +
- + - +
- + - +
- + - +
- + - +
diff --git a/docs/es/docs/deployment/concepts.md b/docs/es/docs/deployment/concepts.md index f5725c5dc..bcc7948bc 100644 --- a/docs/es/docs/deployment/concepts.md +++ b/docs/es/docs/deployment/concepts.md @@ -216,7 +216,7 @@ Este Proceso Administrador probablemente sería el que escuche en el **puerto** Esos worker processes serían los que ejecutan tu aplicación, realizarían los cálculos principales para recibir un **request** y devolver un **response**, y cargarían cualquier cosa que pongas en variables en RAM. - + Y por supuesto, la misma máquina probablemente tendría **otros procesos** ejecutándose también, aparte de tu aplicación. diff --git a/docs/es/docs/deployment/docker.md b/docs/es/docs/deployment/docker.md index ff204f078..3a39d3661 100644 --- a/docs/es/docs/deployment/docker.md +++ b/docs/es/docs/deployment/docker.md @@ -6,7 +6,7 @@ Usar contenedores de Linux tiene varias ventajas, incluyendo **seguridad**, **re /// tip | Consejo -¿Tienes prisa y ya conoces esto? Salta al [`Dockerfile` más abajo 👇](#build-a-docker-image-for-fastapi). +¿Tienes prisa y ya conoces esto? Salta al [`Dockerfile` más abajo 👇](#construir-una-imagen-de-docker-para-fastapi). /// diff --git a/docs/es/docs/deployment/https.md b/docs/es/docs/deployment/https.md index f2871ac03..3ccb5dc47 100644 --- a/docs/es/docs/deployment/https.md +++ b/docs/es/docs/deployment/https.md @@ -85,7 +85,7 @@ Primero, el navegador consultaría con los **servidores DNS** cuál es la **IP d Los servidores DNS le dirían al navegador que use una **dirección IP** específica. Esa sería la dirección IP pública utilizada por tu servidor, que configuraste en los servidores DNS. - + ### Inicio del Handshake TLS @@ -93,7 +93,7 @@ El navegador luego se comunicaría con esa dirección IP en el **puerto 443** (e La primera parte de la comunicación es solo para establecer la conexión entre el cliente y el servidor y decidir las claves criptográficas que usarán, etc. - + Esta interacción entre el cliente y el servidor para establecer la conexión TLS se llama **handshake TLS**. @@ -111,7 +111,7 @@ Usando la **extensión SNI** discutida anteriormente, el TLS Termination Proxy v En este caso, usaría el certificado para `someapp.example.com`. - + El cliente ya **confía** en la entidad que generó ese certificado TLS (en este caso Let's Encrypt, pero lo veremos más adelante), por lo que puede **verificar** que el certificado sea válido. @@ -133,19 +133,19 @@ Ahora que el cliente y el servidor (específicamente el navegador y el TLS Termi Así que, el cliente envía un **request HTTPS**. Esto es simplemente un request HTTP a través de una conexión TLS encriptada. - + ### Desencriptar el Request El TLS Termination Proxy usaría la encriptación acordada para **desencriptar el request**, y transmitiría el **request HTTP simple (desencriptado)** al proceso que ejecuta la aplicación (por ejemplo, un proceso con Uvicorn ejecutando la aplicación FastAPI). - + ### Response HTTP La aplicación procesaría el request y enviaría un **response HTTP simple (sin encriptar)** al TLS Termination Proxy. - + ### Response HTTPS @@ -153,7 +153,7 @@ El TLS Termination Proxy entonces **encriptaría el response** usando la criptog Luego, el navegador verificaría que el response sea válido y encriptado con la clave criptográfica correcta, etc. Entonces **desencriptaría el response** y lo procesaría. - + El cliente (navegador) sabrá que el response proviene del servidor correcto porque está utilizando la criptografía que acordaron usando el **certificado HTTPS** anteriormente. @@ -163,7 +163,7 @@ En el mismo servidor (o servidores), podrían haber **múltiples aplicaciones**, Solo un proceso puede estar gestionando la IP y puerto específica (el TLS Termination Proxy en nuestro ejemplo) pero las otras aplicaciones/procesos pueden estar ejecutándose en el/los servidor(es) también, siempre y cuando no intenten usar la misma **combinación de IP pública y puerto**. - + De esa manera, el TLS Termination Proxy podría gestionar HTTPS y certificados para **múltiples dominios**, para múltiples aplicaciones, y luego transmitir los requests a la aplicación correcta en cada caso. @@ -173,7 +173,7 @@ En algún momento en el futuro, cada certificado **expiraría** (alrededor de 3 Y entonces, habría otro programa (en algunos casos es otro programa, en algunos casos podría ser el mismo TLS Termination Proxy) que hablaría con Let's Encrypt y renovaría el/los certificado(s). - + Los **certificados TLS** están **asociados con un nombre de dominio**, no con una dirección IP. diff --git a/docs/es/docs/how-to/custom-docs-ui-assets.md b/docs/es/docs/how-to/custom-docs-ui-assets.md index 444cf167e..0a03ff330 100644 --- a/docs/es/docs/how-to/custom-docs-ui-assets.md +++ b/docs/es/docs/how-to/custom-docs-ui-assets.md @@ -98,7 +98,7 @@ Probablemente puedas hacer clic derecho en cada enlace y seleccionar una opción Y **ReDoc** utiliza el archivo: -* `redoc.standalone.js` +* `redoc.standalone.js` Después de eso, tu estructura de archivos podría verse así: @@ -129,14 +129,8 @@ Deberías ver un archivo JavaScript muy largo de **ReDoc**. Podría comenzar con algo como: ```JavaScript -/*! - * ReDoc - OpenAPI/Swagger-generated API Reference Documentation - * ------------------------------------------------------------- - * Version: "2.0.0-rc.18" - * Repo: https://github.com/Redocly/redoc - */ -!function(e,t){"object"==typeof exports&&"object"==typeof m - +/*! For license information please see redoc.standalone.js.LICENSE.txt */ +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("null")): ... ``` diff --git a/docs/es/docs/index.md b/docs/es/docs/index.md index db8da6933..c1da5d633 100644 --- a/docs/es/docs/index.md +++ b/docs/es/docs/index.md @@ -12,7 +12,7 @@

- Test + Test Coverage diff --git a/docs/es/docs/tutorial/bigger-applications.md b/docs/es/docs/tutorial/bigger-applications.md index 78165ef05..c3d8f0686 100644 --- a/docs/es/docs/tutorial/bigger-applications.md +++ b/docs/es/docs/tutorial/bigger-applications.md @@ -52,7 +52,7 @@ from app.routers import items * También hay un subdirectorio `app/internal/` con otro archivo `__init__.py`, por lo que es otro "subpaquete de Python": `app.internal`. * Y el archivo `app/internal/admin.py` es otro submódulo: `app.internal.admin`. - + La misma estructura de archivos con comentarios: @@ -270,7 +270,7 @@ Pero ese archivo no existe, nuestras dependencias están en un archivo en `app/d Recuerda cómo se ve nuestra estructura de aplicación/archivo: - + --- diff --git a/docs/es/docs/tutorial/query-params-str-validations.md b/docs/es/docs/tutorial/query-params-str-validations.md index f378b9dce..9cb76156f 100644 --- a/docs/es/docs/tutorial/query-params-str-validations.md +++ b/docs/es/docs/tutorial/query-params-str-validations.md @@ -321,22 +321,6 @@ Así que, cuando necesites declarar un valor como requerido mientras usas `Query {* ../../docs_src/query_params_str_validations/tutorial006_an_py39.py hl[9] *} -### Requerido con Puntos suspensivos (`...`) - -Hay una manera alternativa de declarar explícitamente que un valor es requerido. Puedes establecer el valor por defecto al valor literal `...`: - -{* ../../docs_src/query_params_str_validations/tutorial006b_an_py39.py hl[9] *} - -/// info | Información - -Si no habías visto eso `...` antes: es un valor especial único, es parte de Python y se llama "Ellipsis". - -Se usa por Pydantic y FastAPI para declarar explícitamente que un valor es requerido. - -/// - -Esto le permitirá a **FastAPI** saber que este parámetro es requerido. - ### Requerido, puede ser `None` Puedes declarar que un parámetro puede aceptar `None`, pero que aún así es requerido. Esto obligaría a los clientes a enviar un valor, incluso si el valor es `None`. diff --git a/docs/fa/docs/index.md b/docs/fa/docs/index.md index 6addce763..0aa0bec36 100644 --- a/docs/fa/docs/index.md +++ b/docs/fa/docs/index.md @@ -11,11 +11,11 @@ فریم‌ورک FastAPI، کارایی بالا، یادگیری آسان، کدنویسی سریع، آماده برای استفاده در محیط پروداکشن

- - Test + + Test - - Coverage + + Coverage Package version diff --git a/docs/fr/docs/index.md b/docs/fr/docs/index.md index 695429008..d25f7a939 100644 --- a/docs/fr/docs/index.md +++ b/docs/fr/docs/index.md @@ -12,7 +12,7 @@

- Test + Test Coverage diff --git a/docs/he/docs/index.md b/docs/he/docs/index.md index 6498d15e1..bd166f205 100644 --- a/docs/he/docs/index.md +++ b/docs/he/docs/index.md @@ -12,10 +12,10 @@

- Test + Test - - Coverage + + Coverage Package version diff --git a/docs/hu/docs/index.md b/docs/hu/docs/index.md index c6f596650..45ff49c3b 100644 --- a/docs/hu/docs/index.md +++ b/docs/hu/docs/index.md @@ -6,7 +6,7 @@

- Test + Test Coverage diff --git a/docs/id/docs/index.md b/docs/id/docs/index.md index 7fdd1cc7a..5fb0c4c9c 100644 --- a/docs/id/docs/index.md +++ b/docs/id/docs/index.md @@ -12,7 +12,7 @@

- Test + Test Coverage diff --git a/docs/it/docs/index.md b/docs/it/docs/index.md index 8a1039bc5..dc8f5b846 100644 --- a/docs/it/docs/index.md +++ b/docs/it/docs/index.md @@ -4,15 +4,19 @@

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

+

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

diff --git a/docs/ja/docs/deployment/concepts.md b/docs/ja/docs/deployment/concepts.md index c6b21fd1b..a0d4fb35b 100644 --- a/docs/ja/docs/deployment/concepts.md +++ b/docs/ja/docs/deployment/concepts.md @@ -219,7 +219,7 @@ FastAPI アプリケーションでは、Uvicorn のようなサーバープロ これらのワーカー・プロセスは、アプリケーションを実行するものであり、**リクエスト**を受けて**レスポンス**を返すための主要な計算を行い、あなたが変数に入れたものは何でもRAMにロードします。 - + そしてもちろん、同じマシンでは、あなたのアプリケーションとは別に、**他のプロセス**も実行されているでしょう。 diff --git a/docs/ja/docs/deployment/https.md b/docs/ja/docs/deployment/https.md index ac40b0982..7b0f567aa 100644 --- a/docs/ja/docs/deployment/https.md +++ b/docs/ja/docs/deployment/https.md @@ -92,7 +92,7 @@ DNSサーバーでは、**取得したドメイン**をあなたのサーバー DNSサーバーは、ブラウザに特定の**IPアドレス**を使用するように指示します。このIPアドレスは、DNSサーバーで設定した、あなたのサーバーが使用するパブリックIPアドレスになります。 - + ### TLS Handshake の開始 @@ -100,7 +100,7 @@ DNSサーバーは、ブラウザに特定の**IPアドレス**を使用する 通信の最初の部分は、クライアントとサーバー間の接続を確立し、使用する暗号鍵などを決めるだけです。 - + TLS接続を確立するためのクライアントとサーバー間のこのやりとりは、**TLSハンドシェイク**と呼ばれます。 @@ -120,7 +120,7 @@ TLS Termination Proxyは、1つ以上の**TLS証明書**(HTTPS証明書)に 今回は、`someapp.example.com`の証明書を使うことになります。 - + クライアントは、そのTLS証明書を生成したエンティティ(この場合はLet's Encryptですが、これについては後述します)をすでに**信頼**しているため、その証明書が有効であることを**検証**することができます。 @@ -142,19 +142,19 @@ TLS Termination Proxyは、1つ以上の**TLS証明書**(HTTPS証明書)に そこで、クライアントは**HTTPSリクエスト**を送信します。これは、暗号化されたTLSコネクションを介した単なるHTTPリクエストです。 - + ### リクエストの復号化 TLS Termination Proxy は、合意が取れている暗号化を使用して、**リクエストを復号化**し、**プレーン (復号化された) HTTP リクエスト** をアプリケーションを実行しているプロセス (例えば、FastAPI アプリケーションを実行している Uvicorn を持つプロセス) に送信します。 - + ### HTTP レスポンス アプリケーションはリクエストを処理し、**プレーン(暗号化されていない)HTTPレスポンス** をTLS Termination Proxyに送信します。 - + ### HTTPS レスポンス @@ -162,7 +162,7 @@ TLS Termination Proxyは次に、事前に合意が取れている暗号(`someap その後ブラウザでは、レスポンスが有効で正しい暗号キーで暗号化されていることなどを検証します。そして、ブラウザはレスポンスを**復号化**して処理します。 - + クライアント(ブラウザ)は、レスポンスが正しいサーバーから来たことを知ることができます。 なぜなら、そのサーバーは、以前に**HTTPS証明書**を使って合意した暗号を使っているからです。 @@ -172,7 +172,7 @@ TLS Termination Proxyは次に、事前に合意が取れている暗号(`someap 特定のIPとポート(この例ではTLS Termination Proxy)を扱うことができるのは1つのプロセスだけですが、他のアプリケーション/プロセスも、同じ**パブリックIPとポート**の組み合わせを使用しようとしない限り、サーバー上で実行することができます。 - + そうすれば、TLS Termination Proxy は、**複数のドメイン**や複数のアプリケーションのHTTPSと証明書を処理し、それぞれのケースで適切なアプリケーションにリクエストを送信することができます。 @@ -182,7 +182,7 @@ TLS Termination Proxyは次に、事前に合意が取れている暗号(`someap その後、Let's Encryptと通信する別のプログラム(別のプログラムである場合もあれば、同じTLS Termination Proxyである場合もある)によって、証明書を更新します。 - + **TLS証明書**は、IPアドレスではなく、**ドメイン名に関連付けられて**います。 diff --git a/docs/ja/docs/index.md b/docs/ja/docs/index.md index 682c94e83..1ba85f8e0 100644 --- a/docs/ja/docs/index.md +++ b/docs/ja/docs/index.md @@ -11,14 +11,17 @@ FastAPI framework, high performance, easy to learn, fast to code, ready for production

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

diff --git a/docs/ja/docs/tutorial/cookie-param-models.md b/docs/ja/docs/tutorial/cookie-param-models.md new file mode 100644 index 000000000..8285f44ef --- /dev/null +++ b/docs/ja/docs/tutorial/cookie-param-models.md @@ -0,0 +1,77 @@ +# クッキーパラメータモデル + +もし関連する**複数のクッキー**から成るグループがあるなら、それらを宣言するために、**Pydanticモデル**を作成できます。🍪 + +こうすることで、**複数の場所**で**そのPydanticモデルを再利用**でき、バリデーションやメタデータを、すべてのクッキーパラメータに対して一度に宣言できます。😎 + +/// note | 備考 + +この機能は、FastAPIのバージョン `0.115.0` からサポートされています。🤓 + +/// + +/// tip | 豆知識 + +これと同じテクニックは `Query` 、 `Cookie` 、 `Header` にも適用できます。 😎 + +/// + +## クッキーにPydanticモデルを使用する + +必要な複数の**クッキー**パラメータを**Pydanticモデル**で宣言し、さらに、それを `Cookie` として宣言しましょう: + +{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *} + +**FastAPI**は、リクエストの**クッキー**から**それぞれのフィールド**のデータを**抽出**し、定義された**Pydanticモデル**を提供します。 + +## ドキュメントの確認 + +対話的APIドキュメントUI `/docs` で、定義されているクッキーを確認できます: + +
+ +
+ +/// info | 備考 + + +**ブラウザがクッキーを処理し**ていますが、特別な方法で内部的に処理を行っているために、**JavaScript**からは簡単に操作**できない**ことに留意してください。 + +**対話的APIドキュメントUI** `/docs` にアクセスすれば、*パスオペレーション*に関するクッキーの**ドキュメンテーション**を確認できます。 + +しかし、たとえ**クッキーデータを入力して**「Execute」をクリックしても、対話的APIドキュメントUIは**JavaScript**で動作しているためクッキーは送信されず、まるで値を入力しなかったかのような**エラー**メッセージが表示されます。 + +/// + +## 余分なクッキーを禁止する + +特定の(あまり一般的ではないかもしれない)ケースで、受け付けるクッキーを**制限**する必要があるかもしれません。 + +あなたのAPIは独自の クッキー同意 を管理する能力を持っています。 🤪🍪 + +Pydanticのモデルの Configuration を利用して、 `extra` フィールドを `forbid` とすることができます。 + +{* ../../docs_src/cookie_param_models/tutorial002_an_py39.py hl[10] *} + +もしクライアントが**余分なクッキー**を送ろうとすると、**エラー**レスポンスが返されます。 + +どうせAPIに拒否されるのにあなたの同意を得ようと精一杯努力する可哀想なクッキーバナーたち... 🍪 + +例えば、クライアントがクッキー `santa_tracker` を `good-list-please` という値で送ろうとすると、`santa_tracker` という クッキーが許可されていない ことを通知する**エラー**レスポンスが返されます: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["cookie", "santa_tracker"], + "msg": "Extra inputs are not permitted", + "input": "good-list-please", + } + ] +} +``` + +## まとめ + +**FastAPI**では、**クッキー**を宣言するために、**Pydanticモデル**を使用できます。😎 diff --git a/docs/ja/docs/tutorial/query-param-models.md b/docs/ja/docs/tutorial/query-param-models.md new file mode 100644 index 000000000..053d0740b --- /dev/null +++ b/docs/ja/docs/tutorial/query-param-models.md @@ -0,0 +1,68 @@ +# クエリパラメータモデル + +もし関連する**複数のクエリパラメータ**から成るグループがあるなら、それらを宣言するために、**Pydanticモデル**を作成できます。 + +こうすることで、**複数の場所**で**そのPydanticモデルを再利用**でき、バリデーションやメタデータを、すべてのクエリパラメータに対して一度に宣言できます。😎 + +/// note | 備考 + +この機能は、FastAPIのバージョン `0.115.0` からサポートされています。🤓 + +/// + +## クエリパラメータにPydanticモデルを使用する + +必要な**複数のクエリパラメータ**を**Pydanticモデル**で宣言し、さらに、それを `Query` として宣言しましょう: + +{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *} + +**FastAPI**は、リクエストの**クエリパラメータ**からそれぞれの**フィールド**のデータを**抽出**し、定義された**Pydanticモデル**を提供します。 + +## ドキュメントの確認 + +対話的APIドキュメント `/docs` でクエリパラメータを確認できます: + +
+ +
+ +## 余分なクエリパラメータを禁止する + +特定の(あまり一般的ではないかもしれない)ケースで、受け付けるクエリパラメータを**制限**する必要があるかもしれません。 + +Pydanticのモデルの Configuration を利用して、 `extra` フィールドを `forbid` とすることができます。 + +{* ../../docs_src/query_param_models/tutorial002_an_py310.py hl[10] *} + +もしクライアントが**クエリパラメータ**として**余分な**データを送ろうとすると、**エラー**レスポンスが返されます。 + +例えば、クライアントがクエリパラメータ `tool` に、値 `plumbus` を設定して送ろうとすると: + +```http +https://example.com/items/?limit=10&tool=plumbus +``` + +クエリパラメータ `tool` が許可されていないことを通知する**エラー**レスポンスが返されます。 + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["query", "tool"], + "msg": "Extra inputs are not permitted", + "input": "plumbus" + } + ] +} +``` + +## まとめ + +**FastAPI**では、**クエリパラメータ**を宣言するために、**Pydanticモデル**を使用できます。😎 + +/// tip | 豆知識 + +ネタバレ注意: Pydanticモデルはクッキーやヘッダーの宣言にも使用できますが、その内容については後のチュートリアルで学びます。🤫 + +/// diff --git a/docs/ja/docs/virtual-environments.md b/docs/ja/docs/virtual-environments.md new file mode 100644 index 000000000..791cf64a8 --- /dev/null +++ b/docs/ja/docs/virtual-environments.md @@ -0,0 +1,831 @@ +# 仮想環境 + +Pythonプロジェクトの作業では、**仮想環境**(または類似の仕組み)を使用し、プロジェクトごとにインストールするパッケージを分離するべきでしょう。 + +/// info | 情報 + +もし、仮想環境の概要や作成方法、使用方法について既にご存知なら、このセクションをスキップすることができます。🤓 + +/// + +/// tip | 豆知識 + +**仮想環境**は、**環境変数**とは異なります。 + +**環境変数**は、プログラムが使用できるシステム内の変数です。 + +**仮想環境**は、ファイルをまとめたディレクトリのことです。 + +/// + +/// info | 情報 +このページでは、**仮想環境**の使用方法と、そのはたらきについて説明します。 + +もし**すべてを管理するツール**(Pythonのインストールも含む)を導入する準備ができているなら、uv をお試しください。 + +/// + +## プロジェクトの作成 + +まず、プロジェクト用のディレクトリを作成します。 + +私は通常 home/user ディレクトリの中に `code` というディレクトリを用意していて、プロジェクトごとに1つのディレクトリをその中に作成しています。 + +
+ +```console +// Go to the home directory +$ cd +// Create a directory for all your code projects +$ mkdir code +// Enter into that code directory +$ cd code +// Create a directory for this project +$ mkdir awesome-project +// Enter into that project directory +$ cd awesome-project +``` + +
+ +## 仮想環境の作成 + +Pythonプロジェクトでの**初めての**作業を開始する際には、**プロジェクト内**に仮想環境を作成してください。 + +/// tip | 豆知識 + +これを行うのは、**プロジェクトごとに1回だけ**です。作業のたびに行う必要はありません。 + +/// + +//// tab | `venv` + +仮想環境を作成するには、Pythonに付属している `venv` モジュールを使用できます。 + +
+ +```console +$ python -m venv .venv +``` + +
+ +/// details | このコマンドの意味 + +- `python` : `python` というプログラムを呼び出します +- `-m` : モジュールをスクリプトとして呼び出します。どのモジュールを呼び出すのか、この次に指定します +- `venv` : 通常Pythonに付随してインストールされる `venv`モジュールを使用します +- `.venv` : 仮想環境を`.venv`という新しいディレクトリに作成します + +/// + +//// + +//// tab | `uv` + +もし `uv` をインストール済みなら、仮想環境を作成するために `uv` を使うこともできます。 + +
+ +```console +$ uv venv +``` + +
+ +/// tip | 豆知識 + +デフォルトでは、 `uv` は `.venv` というディレクトリに仮想環境を作成します。 + +ただし、追加の引数にディレクトリ名を与えてカスタマイズすることもできます。 + +/// + +//// + +このコマンドは `.venv` というディレクトリに新しい仮想環境を作成します。 + +/// details | `.venv` またはその他の名前 + +仮想環境を別のディレクトリに作成することも可能ですが、 `.venv` と名付けるのが一般的な慣習です。 + +/// + +## 仮想環境の有効化 + +実行されるPythonコマンドやインストールされるパッケージが新しく作成した仮想環境を使用するよう、その仮想環境を有効化しましょう。 + +/// tip | 豆知識 + +そのプロジェクトの作業で**新しいターミナルセッション**を開始する際には、**毎回**有効化が必要です。 + +/// + +//// tab | Linux, macOS + +
+ +```console +$ source .venv/bin/activate +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ .venv\Scripts\Activate.ps1 +``` + +
+ +//// + +//// tab | Windows Bash + +もしWindowsでBashを使用している場合 (Git Bashなど): + +
+ +```console +$ source .venv/Scripts/activate +``` + +
+ +//// + +/// tip | 豆知識 + +**新しいパッケージ**を仮想環境にインストールするときには、再度**有効化**してください。 + +こうすることで、そのパッケージがインストールした**ターミナル(CLI)プログラム**を使用する場合に、仮想環境内のものが確実に使われ、グローバル環境にインストールされている別のもの(おそらく必要なものとは異なるバージョン)を誤って使用することを防ぎます。 + +/// + +## 仮想環境が有効であることを確認する + +仮想環境が有効である(前のコマンドが正常に機能した)ことを確認します。 + +/// tip | 豆知識 + +これは**任意**ですが、すべてが期待通りに機能し、意図した仮想環境を使用していることを**確認する**良い方法です。 + +/// + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +
+ +`.venv/bin/python` にある `python` バイナリが、プロジェクト(この場合は `awesome-project` )内に表示されていれば、正常に動作しています 🎉。 + +//// + +//// tab | Windows PowerShell + +
+ +``` console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +
+ +`.venv\Scripts\python` にある `python` バイナリが、プロジェクト(この場合は `awesome-project` )内に表示されていれば、正常に動作しています 🎉。 + +//// + +## `pip` をアップグレードする + +/// tip | 豆知識 + +もし `uv` を使用している場合は、 `pip` の代わりに `uv` を使ってインストールを行うため、 `pip` をアップグレードする必要はありません 😎。 + +/// + +もしパッケージのインストールに `pip`(Pythonに標準で付属しています)を使用しているなら、 `pip` を最新バージョンに**アップグレード**しましょう。 + +パッケージのインストール中に発生する想定外のエラーの多くは、最初に `pip` をアップグレードしておくだけで解決されます。 + +/// tip | 豆知識 + +通常、これは仮想環境を作成した直後に**一度だけ**実行します。 + +/// + +仮想環境が有効であることを(上で説明したコマンドで)確認し、アップグレードを実行しましょう: + +
+ +```console +$ python -m pip install --upgrade pip + +---> 100% +``` + +
+ +## `.gitignore` を追加する + +**Git**を使用している場合(使用するべきでしょう)、 `.gitignore` ファイルを追加して、 `.venv` 内のあらゆるファイルをGitの管理対象から除外します。 + +/// tip | 豆知識 + +もし `uv` を使用して仮想環境を作成した場合、すでにこの作業は済んでいるので、この手順をスキップできます 😎。 + +/// + +/// tip | 豆知識 + +これも、仮想環境を作成した直後に**一度だけ**実行します。 + +/// + +
+ +```console +$ echo "*" > .venv/.gitignore +``` + +
+ +/// details | このコマンドの意味 + +- `echo "*"` : ターミナルに `*` というテキストを「表示」しようとします。(次の部分によってその動作が少し変わります) +- `>` : `>` の左側のコマンドがターミナルに表示しようとする内容を、ターミナルには表示せず、 `>` の右側のファイルに書き込みます。 +- `.gitignore` : `*` を書き込むファイル名。 + +ここで、Gitにおける `*` は「すべて」を意味するので、このコマンドによって `.venv` ディレクトリ内のすべてがGitに無視されるようになります。 + +このコマンドは以下のテキストを持つ `.gitignore` ファイルを作成します: + +```gitignore +* +``` + +/// + +## パッケージのインストール + +仮想環境を有効化した後、その中でパッケージをインストールできます。 + +/// tip | 豆知識 + +プロジェクトに必要なパッケージをインストールまたはアップグレードする場合、これを**一度**実行します。 + +もし新しいパッケージを追加したり、バージョンをアップグレードする必要がある場合は、もう**一度この手順を繰り返し**ます。 + +/// + +### パッケージを直接インストールする + +急いでいて、プロジェクトのパッケージ要件を宣言するファイルを使いたくない場合、パッケージを直接インストールできます。 + +/// tip | 豆知識 + +プログラムが必要とするパッケージとバージョンをファイル(例えば `requirements.txt` や `pyproject.toml` )に記載しておくのは、(とても)良い考えです。 + +/// + +//// tab | `pip` + +
+ +```console +$ pip install "fastapi[standard]" + +---> 100% +``` + +
+ +//// + +//// tab | `uv` + +もし `uv` を使用できるなら: + +
+ +```console +$ uv pip install "fastapi[standard]" +---> 100% +``` + +
+ +//// + +### `requirements.txt` からインストールする + +もし `requirements.txt` があるなら、パッケージのインストールに使用できます。 + +//// tab | `pip` + +
+ +```console +$ pip install -r requirements.txt +---> 100% +``` + +
+ +//// + +//// tab | `uv` + +もし `uv` を使用できるなら: + +
+ +```console +$ uv pip install -r requirements.txt +---> 100% +``` + +
+ +//// + +/// details | `requirements.txt` + +パッケージが記載された `requirements.txt` は以下のようになっています: + +```requirements.txt +fastapi[standard]==0.113.0 +pydantic==2.8.0 +``` + +/// + +## プログラムを実行する + +仮想環境を有効化した後、プログラムを実行できます。この際、仮想環境内のPythonと、そこにインストールしたパッケージが使用されます。 + +
+ +```console +$ python main.py + +Hello World +``` + +
+ +## エディタの設定 + +プロジェクトではおそらくエディタを使用するでしょう。コード補完やインラインエラーの表示ができるように、作成した仮想環境をエディタでも使えるよう設定してください。(多くの場合、自動検出されます) + +設定例: + +* VS Code +* PyCharm + +/// tip | 豆知識 + +この設定は通常、仮想環境を作成した際に**一度だけ**行います。 + +/// + +## 仮想環境の無効化 + +プロジェクトの作業が終了したら、その仮想環境を**無効化**できます。 + +
+ +```console +$ deactivate +``` + +
+ +これにより、 `python` コマンドを実行しても、そのプロジェクト用(のパッケージがインストールされた)仮想環境から `python` プログラムを呼び出そうとはしなくなります。 + +## 作業準備完了 + +ここまでで、プロジェクトの作業を始める準備が整いました。 + +/// tip | 豆知識 + +上記の内容を理解したいですか? + +もしそうなら、以下を読み進めてください。👇🤓 + +/// + +## なぜ仮想環境? + +FastAPIを使った作業をするには、 [Python](https://www.python.org/) のインストールが必要です。 + +それから、FastAPIや、使用したいその他の**パッケージ**を**インストール**する必要があります。 + +パッケージをインストールするには、通常、Python に付属する `pip` コマンド (または同様の代替コマンド) を使用します。 + +ただし、`pip` を直接使用すると、パッケージは**グローバルなPython環境**(OS全体にインストールされたPython環境)にインストールされます。 + +### 問題点 + +では、グローバルPython環境にパッケージをインストールすることの問題点は何でしょうか? + +ある時点で、あなたは**異なるパッケージ**に依存する多くのプログラムを書くことになるでしょう。そして、これらの中には同じパッケージの**異なるバージョン**に依存するものも出てくるでしょう。😱 + +例えば、 `philosophers-stone` (賢者の石)というプロジェクトを作成するとします。このプログラムは **`harry` (ハリー)というパッケージのバージョン `1`**に依存しています。そのため、 `harry` (ハリー)をインストールする必要があります。 + +```mermaid +flowchart LR + stone(philosophers-stone) -->|requires| harry-1[harry v1] +``` + +それから、 `prisoner-of-azkaban` (アズカバンの囚人)という別のプロジェクトを作成したとします。このプロジェクトも `harry` (ハリー)に依存していますが、**`harry` (ハリー)のバージョン `3`**が必要です。 + +```mermaid +flowchart LR + azkaban(prisoner-of-azkaban) --> |requires| harry-3[harry v3] +``` + +しかし、ここで問題になるのは、もしローカルの**仮想環境**ではなくグローバル(環境)にパッケージをインストールするなら、 `harry` (ハリー)のどのバージョンをインストールするか選ばないといけないことです。 + +例えば、 `philosophers-stone` (賢者の石)を実行するには、まず `harry` (ハリー)のバージョン `1` をインストールする必要があります: + +
+ +```console +$ pip install "harry==1" +``` + +
+ +これにより、`harry` (ハリー)バージョン1がグローバルなPython環境にインストールされます。 + +```mermaid +flowchart LR + subgraph global[global env] + harry-1[harry v1] + end + subgraph stone-project[philosophers-stone project] + stone(philosophers-stone) -->|requires| harry-1 + end +``` + +しかし、 `prisoner-of-azkaban` (アズカバンの囚人)を実行したい場合は、`harry` (ハリー)のバージョン `1` をアンインストールし、`harry` (ハリー)のバージョン `3` をインストールし直す必要があります。(あるいは、単に`harry` (ハリー)のバージョン `3` をインストールすることで、自動的にバージョン `1` がアンインストールされます) + +
+ +```console +$ pip install "harry==3" +``` + +
+ +このようにして、グローバル環境への `harry` (ハリー)のバージョン `3` のインストールが完了します。 + +それから、 `philosophers-stone` (賢者の石)を再び実行しようとすると、このプログラムは `harry` (ハリー)のバージョン `1` が必要なため、**動作しなくなる**可能性があります。 + +```mermaid +flowchart LR + subgraph global[global env] + harry-1[harry v1] + style harry-1 fill:#ccc,stroke-dasharray: 5 5 + harry-3[harry v3] + end + subgraph stone-project[philosophers-stone project] + stone(philosophers-stone) -.-x|⛔️| harry-1 + end + subgraph azkaban-project[prisoner-of-azkaban project] + azkaban(prisoner-of-azkaban) --> |requires| harry-3 + end +``` + +/// tip | 豆知識 + +Pythonのパッケージでは、**新しいバージョン**で**互換性を損なう変更を避ける**よう努めるのが一般的ですが、それでも注意が必要です。すべてが正常に動作することをテストで確認してから、意図的に指定して新しいバージョンをインストールするのが良いでしょう。 + +/// + +あなたのすべての**プロジェクトが依存している**、**多数の**他の**パッケージ**が上記の問題を抱えていると想像してください。これは管理が非常に困難です。そして、**互換性のないバージョン**のパッケージを使ってプロジェクトを実行し、なぜ動作しないのか分からなくなるでしょう。 + +また、使用しているOS(Linux、Windows、macOS など)によっては、Pythonがすでにインストールされていることがあります。この場合、特定のバージョンのパッケージが**OSの動作に必要である**ことがあります。グローバル環境にパッケージをインストールすると、OSに付属するプログラムを**壊してしまう**可能性があります。 + +## パッケージのインストール先 + +Pythonをインストールしたとき、ファイルを含んだいくつかのディレクトリが作成されます。 + +これらの中には、インストールされたパッケージを保存するためのものもあります。 + +以下のコマンドを実行したとき: + +
+ +```console +// Don't run this now, it's just an example 🤓 +$ pip install "fastapi[standard]" +---> 100% +``` + +
+ +FastAPIのコードを含む圧縮ファイルが、通常は [PyPI](https://pypi.org/project/fastapi/) からダウンロードされます。 + +また、FastAPIが依存する他のパッケージも**ダウンロード**されます。 + +それから、これらのファイルは**解凍**され、コンピュータのあるディレクトリに配置されます。 + +デフォルトでは、これらのファイルはPythonのインストール時に作成されるディレクトリ、つまり**グローバル環境**に配置されます。 + +## 仮想環境とは + +すべてのパッケージをグローバル環境に配置することによって生じる問題の解決策は、作業する**プロジェクトごとの仮想環境**を使用することです。 + +仮想環境は**ディレクトリ**であり、グローバル環境と非常に似ていて、一つのプロジェクトで使う特定のパッケージ群をインストールできる場所です。 + +このようにして、それぞれのプロジェクトが独自の仮想環境(`.venv` ディレクトリ)に独自のパッケージ群を持つことができます。 + +```mermaid +flowchart TB + subgraph stone-project[philosophers-stone project] + stone(philosophers-stone) --->|requires| harry-1 + subgraph venv1[.venv] + harry-1[harry v1] + end + end + subgraph azkaban-project[prisoner-of-azkaban project] + azkaban(prisoner-of-azkaban) --->|requires| harry-3 + subgraph venv2[.venv] + harry-3[harry v3] + end + end + stone-project ~~~ azkaban-project +``` + +## 仮想環境の有効化とは + +仮想環境を有効にしたとき、例えば次のコマンドを実行した場合を考えます: + +//// tab | Linux, macOS + +
+ +```console +$ source .venv/bin/activate +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ .venv\Scripts\Activate.ps1 +``` + +
+ +//// + +//// tab | Windows Bash + +あるいは、WindowsでBashを使用している場合 (Git Bashなど): + +
+ +```console +$ source .venv/Scripts/activate +``` + +
+ +//// + +これによって、いくつかの [環境変数](environment-variables.md){.internal-link target=_blank} が作成・修正され、次に実行されるコマンドで使用できるようになります。 + +これらの環境変数のひとつに、 `PATH` 変数があります。 + +/// tip | 豆知識 + +`PATH` 変数についての詳細は [環境変数](environment-variables.md#path環境変数){.internal-link target=_blank} を参照してください。 + +/// + +仮想環境を有効にすると、その仮想環境のパス `.venv/bin` (LinuxとmacOS)、あるいは `.venv\Scripts` (Windows)が `PATH` 変数に追加されます。 + +その環境を有効にする前の `PATH` 変数が次のようになっているとします。 + +//// tab | Linux, macOS + +```plaintext +/usr/bin:/bin:/usr/sbin:/sbin +``` + +これは、OSが以下のディレクトリ中でプログラムを探すことを意味します: + +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Windows\System32 +``` + +これは、OSが以下のディレクトリ中でプログラムを探すことを意味します: + +* `C:\Windows\System32` + +//// + +仮想環境を有効にすると、 `PATH` 変数は次のようになります。 + +//// tab | Linux, macOS + +```plaintext +/home/user/code/awesome-project/.venv/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +これは、OSが他のディレクトリを探すより前に、最初に以下のディレクトリ中でプログラムを探し始めることを意味します: + +```plaintext +/home/user/code/awesome-project/.venv/bin +``` + +そのため、ターミナルで `python` と入力した際に、OSはPythonプログラムを以下のパスで発見し、使用します。 + +```plaintext +/home/user/code/awesome-project/.venv/bin/python +``` + +//// + +//// tab | Windows + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts;C:\Windows\System32 +``` + +これは、OSが他のディレクトリを探すより前に、最初に以下のディレクトリ中でプログラムを探し始めることを意味します: + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts +``` + +そのため、ターミナルで `python` と入力した際に、OSはPythonプログラムを以下のパスで発見し、使用します。 + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +//// + +重要な点は、仮想環境のパスを `PATH` 変数の**先頭**に配置することです。OSは利用可能な他のPythonを見つけるより**前に**、この仮想環境のPythonを見つけるようになります。このようにして、 `python` を実行したときに、他の `python` (例えばグローバル環境の `python` )ではなく、**その仮想環境の**Pythonを使用するようになります。 + +仮想環境を有効にして変更されることは他にもありますが、これが最も重要な変更のひとつです。 + +## 仮想環境の確認 + +仮想環境が有効かどうか、例えば次のように確認できます。: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +
+ +//// + +これは、使用される `python` プログラムが**その仮想環境の**ものであることを意味します。 + +LinuxやmacOSでは `which` を、Windows PowerShellでは `Get-Command` を使用します。 + +このコマンドの動作は、 `PATH`変数に設定された**それぞれのパスを順に**確認していき、呼ばれている `python` プログラムを探します。そして、見つかり次第そのプログラムへの**パスを表示します**。 + +最も重要なことは、 `python` が呼ばれたときに、まさにこのコマンドで確認した "`python`" が実行されることです。 + +こうして、自分が想定通りの仮想環境にいるかを確認できます。 + +/// tip | 豆知識 + +ある仮想環境を有効にし、そのPythonを使用したまま**他のプロジェクトに移動して**しまうことは簡単に起こり得ます。 + +そして、その第二のプロジェクトは動作しないでしょう。なぜなら別のプロジェクトの仮想環境の**誤ったPython**を使用しているからです。 + +そのため、どの `python` が使用されているのか確認できることは役立ちます。🤓 + +/// + +## なぜ仮想環境を無効化するのか + +例えば、`philosophers-stone` (賢者の石)というプロジェクトで作業をしていて、**その仮想環境を有効にし**、必要なパッケージをインストールしてその環境内で作業を進めているとします。 + +それから、**別のプロジェクト**、 `prisoner-of-azkaban` (アズカバンの囚人)に取り掛かろうとします。 + +そのプロジェクトディレクトリへ移動します: + +
+ +```console +$ cd ~/code/prisoner-of-azkaban +``` + +
+ +もし `philosophers-stone` (賢者の石)の仮想環境を無効化していないと、`python` を実行したとき、 ターミナルは `philosophers-stone` (賢者の石)のPythonを使用しようとします。 + +
+ +```console +$ cd ~/code/prisoner-of-azkaban + +$ python main.py + +// Error importing sirius, it's not installed 😱 +Traceback (most recent call last): + File "main.py", line 1, in + import sirius +``` + +
+ +しかし、その仮想環境を無効化し、 `prisoner-of-azkaban` (アズカバンの囚人)のための新しい仮想環境を有効にすれば、 `python` を実行したときに `prisoner-of-azkaban` (アズカバンの囚人)の仮想環境の Python が使用されるようになります。 + +
+ +```console +$ cd ~/code/prisoner-of-azkaban + +// You don't need to be in the old directory to deactivate, you can do it wherever you are, even after going to the other project 😎 +$ deactivate + +// Activate the virtual environment in prisoner-of-azkaban/.venv 🚀 +$ source .venv/bin/activate + +// Now when you run python, it will find the package sirius installed in this virtual environment ✨ +$ python main.py + +I solemnly swear 🐺 +``` + +
+ +## 代替手段 + +これは、あらゆる仕組みを**根本から**学ぶためのシンプルな入門ガイドです。 + +仮想環境、パッケージの依存関係(requirements)、プロジェクトの管理には、多くの**代替手段**があります。 + +準備が整い、パッケージの依存関係、仮想環境など**プロジェクト全体の管理**ツールを使いたいと考えたら、uv を試してみることをおすすめします。 + +`uv` では以下のような多くのことができます: + +* 異なるバージョンも含めた**Python のインストール** +* プロジェクトごとの**仮想環境**の管理 +* **パッケージ**のインストール +* プロジェクトのパッケージの**依存関係やバージョン**の管理 +* パッケージとそのバージョンの、依存関係を含めた**厳密な**組み合わせを保持し、これによって、本番環境で、開発環境と全く同じようにプロジェクトを実行できる(これは**locking**と呼ばれます) +* その他のさまざまな機能 + +## まとめ + +ここまで読みすべて理解したなら、世間の多くの開発者と比べて、仮想環境について**あなたはより多くのことを知っています**。🤓 + +これらの詳細を知ることは、将来、複雑に見える何かのデバッグにきっと役立つでしょう。しかし、その頃には、あなたは**そのすべての動作を根本から**理解しているでしょう。😎 diff --git a/docs/ko/docs/advanced/custom-response.md b/docs/ko/docs/advanced/custom-response.md new file mode 100644 index 000000000..2001956fa --- /dev/null +++ b/docs/ko/docs/advanced/custom-response.md @@ -0,0 +1,313 @@ +# 사용자 정의 응답 - HTML, Stream, 파일, 기타 + +기본적으로, **FastAPI** 응답을 `JSONResponse`를 사용하여 반환합니다. + +이를 재정의 하려면 [응답을 직접 반환하기](response-directly.md){.internal-link target=_blank}에서 본 것처럼 `Response`를 직접 반환하면 됩니다. + +그러나 `Response` (또는 `JSONResponse`와 같은 하위 클래스)를 직접 반환하면, 데이터가 자동으로 변환되지 않으며 (심지어 `response_model`을 선언했더라도), 문서화가 자동으로 생성되지 않습니다(예를 들어, 생성된 OpenAPI의 일부로 HTTP 헤더 `Content-Type`에 특정 "미디어 타입"을 포함하는 경우). + +하지만 *경로 작업 데코레이터*에서 `response_class` 매개변수를 사용하여 원하는 `Response`(예: 모든 `Response` 하위 클래스)를 선언할 수도 있습니다. + +*경로 작업 함수*에서 반환하는 내용은 해당 `Response`안에 포함됩니다. + +그리고 만약 그 `Response`가 `JSONResponse`와 `UJSONResponse`의 경우 처럼 JSON 미디어 타입(`application/json`)을 가지고 있다면, *경로 작업 데코레이터*에서 선언한 Pydantic의 `response_model`을 사용해 자동으로 변환(및 필터링) 됩니다. + +/// note | 참고 + +미디어 타입이 없는 응답 클래스를 사용하는 경우, FastAPI는 응답에 내용이 없을 것으로 예상하므로 생성된 OpenAPI 문서에서 응답 형식을 문서화하지 않습니다. + +/// + +## `ORJSONResponse` 사용하기 + +예를 들어, 성능을 극대화하려는 경우, orjson을 설치하여 사용하고 응답을 `ORJSONResponse`로 설정할 수 있습니다. + +사용하고자 하는 `Response` 클래스(하위 클래스)를 임포트한 후, **경로 작업 데코레이터*에서 선언하세요. + +대규모 응답의 경우, 딕셔너리를 반환하는 것보다 `Response`를 반환하는 것이 훨씬 빠릅니다. + +이유는 기본적으로, FastAPI가 내부의 모든 항목을 검사하고 JSON으로 직렬화할 수 있는지 확인하기 때문입니다. 이는 사용자 안내서에서 설명된 [JSON 호환 가능 인코더](../tutorial/encoder.md){.internal-link target=_blank}를 사용하는 방식과 동일합니다. 이를 통해 데이터베이스 모델과 같은 **임의의 객체**를 반환할 수 있습니다. + +하지만 반환하는 내용이 **JSON으로 직렬화 가능**하다고 확신하는 경우, 해당 내용을 응답 클래스에 직접 전달할 수 있으며, FastAPI가 반환 내용을 `jsonable_encoder`를 통해 처리한 뒤 응답 클래스에 전달하는 오버헤드를 피할 수 있습니다. + +{* ../../docs_src/custom_response/tutorial001b.py hl[2,7] *} + +/// info | 정보 + +`response_class` 매개변수는 응답의 "미디어 타입"을 정의하는 데에도 사용됩니다. + +이 경우, HTTP 헤더 `Content-Type`은 `application/json`으로 설정됩니다. + +그리고 이는 OpenAPI에 그대로 문서화됩니다. + +/// + +/// tip | 팁 + +`ORJSONResponse`는 FastAPI에서만 사용할 수 있고 Starlette에서는 사용할 수 없습니다. + +/// + +## HTML 응답 + +**FastAPI**에서 HTML 응답을 직접 반환하려면 `HTMLResponse`를 사용하세요. + +* `HTMLResponse`를 임포트 합니다. +* *경로 작업 데코레이터*의 `response_class` 매개변수로 `HTMLResponse`를 전달합니다. + +{* ../../docs_src/custom_response/tutorial002.py hl[2,7] *} + +/// info | 정보 + +`response_class` 매개변수는 응답의 "미디어 타입"을 정의하는 데에도 사용됩니다. + +이 경우, HTTP 헤더 `Content-Type`은 `text/html`로 설정됩니다. + +그리고 이는 OpenAPI에 그대로 문서화 됩니다. + +/// + +### `Response` 반환하기 + +[응답을 직접 반환하기](response-directly.md){.internal-link target=_blank}에서 본 것 처럼, *경로 작업*에서 응답을 직접 반환하여 재정의할 수도 있습니다. + +위의 예제와 동일하게 `HTMLResponse`를 반환하는 코드는 다음과 같을 수 있습니다: + +{* ../../docs_src/custom_response/tutorial003.py hl[2,7,19] *} + +/// warning | 경고 + +*경로 작업 함수*에서 직접 반환된 `Response`는 OpenAPI에 문서화되지 않습니다(예를들어, `Content-Type`이 문서화되지 않음) 자동 대화형 문서에서도 표시되지 않습니다. + +/// + +/// info | 정보 + +물론 실제 `Content-Type` 헤더, 상태 코드 등은 반환된 `Response` 객체에서 가져옵니다. + +/// + +### OpenAPI에 문서화하고 `Response` 재정의 하기 + +함수 내부에서 응답을 재정의하면서 동시에 OpenAPI에서 "미디어 타입"을 문서화하고 싶다면, `response_class` 매게변수를 사용하면서 `Response` 객체를 반환할 수 있습니다. + +이 경우 `response_class`는 OpenAPI *경로 작업*을 문서화하는 데만 사용되고, 실제로는 여러분이 반환한 `Response`가 그대로 사용됩니다. + +### `HTMLResponse`직접 반환하기 + +예를 들어, 다음과 같이 작성할 수 있습니다: + +{* ../../docs_src/custom_response/tutorial004.py hl[7,21,23] *} + +이 예제에서, `generate_html_response()` 함수는 HTML을 `str`로 반환하는 대신 이미 `Response`를 생성하고 반환합니다. + +`generate_html_response()`를 호출한 결과를 반환함으로써, 기본적인 **FastAPI** 기본 동작을 재정의 하는 `Response`를 이미 반환하고 있습니다. + +하지만 `response_class`에 `HTMLResponse`를 함께 전달했기 때문에, FastAPI는 이를 OpenAPI 및 대화형 문서에서 `text/html`로 HTML을 문서화 하는 방법을 알 수 있습니다. + + + +## 사용 가능한 응답들 + +다음은 사용할 수 있는 몇가지 응답들 입니다. + +`Response`를 사용하여 다른 어떤 것도 반환 할수 있으며, 직접 하위 클래스를 만들 수도 있습니다. + +/// note | 기술 세부사항 + +`from starlette.responses import HTMLResponse`를 사용할 수도 있습니다. + +**FastAPI**는 개발자인 여러분의 편의를 위해 `starlette.responses`를 `fastapi.responses`로 제공 하지만, 대부분의 사용 가능한 응답은 Starlette에서 직접 가져옵니다. + +/// + +### `Response` + +기본 `Response` 클래스는 다른 모든 응답 클래스의 부모 클래스 입니다. + +이 클래스를 직접 반환할 수 있습니다. + +다음 매개변수를 받을 수 있습니다: + +* `content` - `str` 또는 `bytes`. +* `status_code` - HTTP 상태코드를 나타내는 `int`. +* `headers` - 문자열로 이루어진 `dict`. +* `media_type` - 미디어 타입을 나타내는 `str` 예: `"text/html"`. + +FastAPI (실제로는 Starlette)가 자동으로 `Content-Length` 헤더를 포함시킵니다. 또한 `media_type`에 기반하여 `Content-Type` 헤더를 포함하며, 텍스트 타입의 경우 문자 집합을 추가 합니다. + +{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *} + +### `HTMLResponse` + +텍스트 또는 바이트를 받아 HTML 응답을 반환합니다. 위에서 설명한 내용과 같습니다. + +### `PlainTextResponse` + +텍스트 또는 바이트를 받아 일반 텍스트 응답을 반환합니다. + +{* ../../docs_src/custom_response/tutorial005.py hl[2,7,9] *} + +### `JSONResponse` + +데이터를 받아 `application/json`으로 인코딩된 응답을 반환합니다. + +이는 위에서 설명했듯이 **FastAPI**에서 기본적으로 사용되는 응답 형식입니다. + +### `ORJSONResponse` + + `orjson`을 사용하여 빠른 JSON 응답을 제공하는 대안입니다. 위에서 설명한 내용과 같습니다. + +/// info | 정보 + +이를 사용하려면 `orjson`을 설치해야합니다. 예: `pip install orjson`. + +/// + +### `UJSONResponse` + +`ujson`을 사용한 또 다른 JSON 응답 형식입니다. + +/// info | 정보 + +이 응답을 사용하려면 `ujson`을 설치해야합니다. 예: 'pip install ujson`. + +/// + +/// warning | 경고 + +`ujson` 은 일부 예외 경우를 처리하는 데 있어 Python 내장 구현보다 덜 엄격합니다. + +/// + +{* ../../docs_src/custom_response/tutorial001.py hl[2,7] *} + +/// tip | 팁 + +`ORJSONResponse`가 더 빠른 대안일 가능성이 있습니다. + +/// + +### `RedirectResponse` + +HTTP 리디렉션 응답을 반환합니다. 기본적으로 상태 코드는 307(임시 리디렉션)으로 설정됩니다. + +`RedirectResponse`를 직접 반환할 수 있습니다. + +{* ../../docs_src/custom_response/tutorial006.py hl[2,9] *} + +--- + +또는 `response_class` 매개변수에서 사용할 수도 있습니다: + + +{* ../../docs_src/custom_response/tutorial006b.py hl[2,7,9] *} + +이 경우, *경로 작업* 함수에서 URL을 직접 반환할 수 있습니다. + +이 경우, 사용되는 `status_code`는 `RedirectResponse`의 기본값인 `307` 입니다. + +--- + +`status_code` 매개변수를 `response_class` 매개변수와 함께 사용할 수도 있습니다: + +{* ../../docs_src/custom_response/tutorial006c.py hl[2,7,9] *} + +### `StreamingResponse` + +비동기 제너레이터 또는 일반 제너레이터/이터레이터를 받아 응답 본문을 스트리밍 합니다. + +{* ../../docs_src/custom_response/tutorial007.py hl[2,14] *} + +#### 파일과 같은 객체를 사용한 `StreamingResponse` + +파일과 같은 객체(예: `open()`으로 반환된 객체)가 있는 경우, 해당 파일과 같은 객체를 반복(iterate)하는 제너레이터 함수를 만들 수 있습니다. + +이 방식으로, 파일 전체를 메모리에 먼저 읽어들일 필요 없이, 제너레이터 함수를 `StreamingResponse`에 전달하여 반환할 수 있습니다. + +이 방식은 클라우드 스토리지, 비디오 처리 등의 다양한 라이브러리와 함께 사용할 수 있습니다. + +{* ../../docs_src/custom_response/tutorial008.py hl[2,10:12,14] *} + +1. 이것이 제너레이터 함수입니다. `yield` 문을 포함하고 있으므로 "제너레이터 함수"입니다. +2. `with` 블록을 사용함으로써, 제너레이터 함수가 완료된 후 파일과 같은 객체가 닫히도록 합니다. 즉, 응답 전송이 끝난 후 닫힙니다. +3. 이 `yield from`은 함수가 `file_like`라는 객체를 반복(iterate)하도록 합니다. 반복된 각 부분은 이 제너레이터 함수(`iterfile`)에서 생성된 것처럼 `yield` 됩니다. + + 이렇게 하면 "생성(generating)" 작업을 내부적으로 다른 무언가에 위임하는 제너레이터 함수가 됩니다. + + 이 방식을 사용하면 `with` 블록 안에서 파일을 열 수 있어, 작업이 완료된 후 파일과 같은 객체가 닫히는 것을 보장할 수 있습니다. + +/// tip | 팁 + +여기서 표준 `open()`을 사용하고 있기 때문에 `async`와 `await`를 지원하지 않습니다. 따라서 경로 작업은 일반 `def`로 선언합니다. + +/// + +### `FileResponse` + +파일을 비동기로 스트리밍하여 응답합니다. + +다른 응답 유형과는 다른 인수를 사용하여 객체를 생성합니다: + +* `path` - 스트리밍할 파일의 경로. +* `headers` - 딕셔너리 형식의 사용자 정의 헤더. +* `media_type` - 미디어 타입을 나타내는 문자열. 설정되지 않은 경우 파일 이름이나 경로를 사용하여 추론합니다. +* `filename` - 설정된 경우 응답의 `Content-Disposition`에 포함됩니다. + +파일 응답에는 적절한 `Content-Length`, `Last-Modified`, 및 `ETag` 헤더가 포함됩니다. + +{* ../../docs_src/custom_response/tutorial009.py hl[2,10] *} + +또한 `response_class` 매개변수를 사용할 수도 있습니다: + +{* ../../docs_src/custom_response/tutorial009b.py hl[2,8,10] *} + +이 경우, 경로 작업 함수에서 파일 경로를 직접 반환할 수 있습니다. + +## 사용자 정의 응답 클래스 + +`Response`를 상속받아 사용자 정의 응답 클래스를 생성하고 사용할 수 있습니다. + +예를 들어, 포함된 `ORJSONResponse` 클래스에서 사용되지 않는 설정으로 orjson을 사용하고 싶다고 가정해봅시다. + +만약 들여쓰기 및 포맷된 JSON을 반환하고 싶다면, `orjson.OPT_INDENT_2` 옵션을 사용할 수 있습니다. + +`CustomORJSONResponse`를 생성할 수 있습니다. 여기서 핵심은 `Response.render(content)` 메서드를 생성하여 내용을 `bytes`로 반환하는 것입니다: + +{* ../../docs_src/custom_response/tutorial009c.py hl[9:14,17] *} + +이제 다음 대신: + +```json +{"message": "Hello World"} +``` + +이 응답은 이렇게 반환됩니다: + +```json +{ + "message": "Hello World" +} +``` + +물론 JSON 포맷팅보다 더 유용하게 활용할 방법을 찾을 수 있을 것입니다. 😉 + +## 기본 응답 클래스 + +**FastAPI** 클래스 객체 또는 `APIRouter`를 생성할 때 기본적으로 사용할 응답 클래스를 지정할 수 있습니다. + +이를 정의하는 매개변수는 `default_response_class`입니다. + +아래 예제에서 **FastAPI**는 모든 경로 작업에서 기본적으로 `JSONResponse` 대신 `ORJSONResponse`를 사용합니다. + +{* ../../docs_src/custom_response/tutorial010.py hl[2,4] *} + +/// tip | 팁 + +여전히 이전처럼 *경로 작업*에서 `response_class`를 재정의할 수 있습니다. + +/// + +## 추가 문서화 + +OpenAPI에서 `responses`를 사용하여 미디어 타입 및 기타 세부 정보를 선언할 수도 있습니다: [OpenAPI에서 추가 응답](additional-responses.md){.internal-link target=_blank}. diff --git a/docs/ko/docs/advanced/events.md b/docs/ko/docs/advanced/events.md index ae349e7be..5f8fe0f1e 100644 --- a/docs/ko/docs/advanced/events.md +++ b/docs/ko/docs/advanced/events.md @@ -1,53 +1,165 @@ -# 이벤트: startup과 shutdown +# Lifespan 이벤트 -필요에 따라 응용 프로그램이 시작되기 전이나 종료될 때 실행되는 이벤트 핸들러(함수)를 정의할 수 있습니다. +애플리케이션 **시작 전**에 실행되어야 하는 로직(코드)을 정의할 수 있습니다. 이는 이 코드가 **한 번**만 실행되며, **애플리케이션이 요청을 받기 시작하기 전**에 실행된다는 의미입니다. -이 함수들은 `async def` 또는 평범하게 `def`으로 선언할 수 있습니다. +마찬가지로, 애플리케이션이 **종료될 때** 실행되어야 하는 로직(코드)을 정의할 수 있습니다. 이 경우, 이 코드는 **한 번**만 실행되며, **여러 요청을 처리한 후**에 실행됩니다. + +이 코드가 애플리케이션이 **요청을 받기 시작하기 전에** 실행되고, 요청 처리가 끝난 후 **종료 직전에** 실행되기 때문에 전체 애플리케이션의 **수명(Lifespan)**을 다룹니다. (잠시 후 "수명"이라는 단어가 중요해집니다 😉) + +이 방법은 전체 애플리케이션에서 사용해야 하는 **자원**을 설정하거나 요청 간에 **공유되는** 자원을 설정하고, 또는 그 후에 **정리**하는 데 매우 유용할 수 있습니다. 예를 들어, 데이터베이스 연결 풀 또는 공유되는 머신러닝 모델을 로드하는 경우입니다. + + +## 사용 사례 + +먼저 **사용 사례**를 예로 들어보고, 이를 어떻게 해결할 수 있는지 살펴보겠습니다. + +우리가 요청을 처리하기 위해 사용하고 싶은 **머신러닝 모델**이 있다고 상상해 봅시다. 🤖 + +이 모델들은 요청 간에 공유되므로, 요청마다 모델이 하나씩 있는 것이 아니라, 여러 요청에서 동일한 모델을 사용합니다. + +모델을 로드하는 데 **상당한 시간이 걸린다고 상상해 봅시다**, 왜냐하면 모델이 **디스크에서 많은 데이터를 읽어야** 하기 때문입니다. 따라서 모든 요청에 대해 모델을 매번 로드하고 싶지 않습니다. + +모듈/파일의 최상위에서 모델을 로드할 수도 있지만, 그러면 **모델을 로드하는데** 시간이 걸리기 때문에, 단순한 자동화된 테스트를 실행할 때도 모델이 로드될 때까지 기다려야 해서 **테스트 속도가 느려집니다**. + +이 문제를 해결하려고 하는 것입니다. 요청을 처리하기 전에 모델을 로드하되, 애플리케이션이 요청을 받기 시작하기 직전에만 로드하고, 코드가 로드되는 동안은 로드하지 않도록 하겠습니다. + +## Lifespan + +`FastAPI` 애플리케이션의 `lifespan` 매개변수와 "컨텍스트 매니저"를 사용하여 *시작*과 *종료* 로직을 정의할 수 있습니다. (컨텍스트 매니저가 무엇인지 잠시 후에 설명드리겠습니다.) + +예제를 통해 시작하고, 그 후에 자세히 살펴보겠습니다. + +우리는 `yield`를 사용하여 비동기 함수 `lifespan()`을 다음과 같이 생성합니다: + +{* ../../docs_src/events/tutorial003.py hl[16,19] *} + +여기서 우리는 모델을 로드하는 비싼 *시작* 작업을 시뮬레이션하고 있습니다. `yield` 앞에서 (가짜) 모델 함수를 머신러닝 모델이 담긴 딕셔너리에 넣습니다. 이 코드는 **애플리케이션이 요청을 받기 시작하기 전**, *시작* 동안에 실행됩니다. + +그리고 `yield` 직후에는 모델을 언로드합니다. 이 코드는 **애플리케이션이 요청 처리 완료 후**, *종료* 직전에 실행됩니다. 예를 들어, 메모리나 GPU와 같은 자원을 해제하는 작업을 할 수 있습니다. + +/// tip | 팁 + +`shutdown`은 애플리케이션을 **종료**할 때 발생합니다. + +새로운 버전을 시작해야 하거나, 그냥 실행을 멈추고 싶을 수도 있습니다. 🤷 + +/// + +### Lifespan 함수 + +먼저 주목할 점은, `yield`를 사용하여 비동기 함수(async function)를 정의하고 있다는 것입니다. 이는 `yield`를 사용한 의존성과 매우 유사합니다. + +{* ../../docs_src/events/tutorial003.py hl[14:19] *} + +함수의 첫 번째 부분, 즉 `yield` 이전의 코드는 애플리케이션이 시작되기 **전에** 실행됩니다. + +그리고 `yield` 이후의 부분은 애플리케이션이 완료된 후 **나중에** 실행됩니다. + +### 비동기 컨텍스트 매니저 + +함수를 확인해보면, `@asynccontextmanager`로 장식되어 있습니다. + +이것은 함수를 "**비동기 컨텍스트 매니저**"라고 불리는 것으로 변환시킵니다. + +{* ../../docs_src/events/tutorial003.py hl[1,13] *} + +파이썬에서 **컨텍스트 매니저**는 `with` 문에서 사용할 수 있는 것입니다. 예를 들어, `open()`은 컨텍스트 매니저로 사용할 수 있습니다: + +```Python +with open("file.txt") as file: + file.read() +``` +최근 버전의 파이썬에서는 **비동기 컨텍스트 매니저**도 있습니다. 이를 `async with`와 함께 사용합니다: + +```Python +async with lifespan(app): + await do_stuff() +``` + +컨텍스트 매니저나 위와 같은 비동기 컨텍스트 매니저를 만들면, `with` 블록에 들어가기 전에 `yield` 이전의 코드가 실행되고, `with` 블록을 벗어난 후에는 `yield` 이후의 코드가 실행됩니다. + +위의 코드 예제에서는 직접 사용하지 않고, FastAPI에 전달하여 사용하도록 합니다. + +`FastAPI` 애플리케이션의 `lifespan` 매개변수는 **비동기 컨텍스트 매니저**를 받기 때문에, 새로운 `lifespan` 비동기 컨텍스트 매니저를 FastAPI에 전달할 수 있습니다. + +{* ../../docs_src/events/tutorial003.py hl[22] *} + +## 대체 이벤트 (사용 중단) /// warning | 경고 -이벤트 핸들러는 주 응용 프로그램에서만 작동합니다. [하위 응용 프로그램 - 마운트](./sub-applications.md){.internal-link target=_blank}에서는 작동하지 않습니다. +*시작*과 *종료*를 처리하는 권장 방법은 위에서 설명한 대로 `FastAPI` 애플리케이션의 `lifespan` 매개변수를 사용하는 것입니다. `lifespan` 매개변수를 제공하면 `startup`과 `shutdown` 이벤트 핸들러는 더 이상 호출되지 않습니다. `lifespan`을 사용할지, 모든 이벤트를 사용할지 선택해야 하며 둘 다 사용할 수는 없습니다. + +이 부분은 건너뛰셔도 좋습니다. /// -## `startup` 이벤트 +*시작*과 *종료* 동안 실행될 이 로직을 정의하는 대체 방법이 있습니다. + +애플리케이션이 시작되기 전에 또는 종료될 때 실행해야 하는 이벤트 핸들러(함수)를 정의할 수 있습니다. -응용 프로그램을 시작하기 전에 실행하려는 함수를 "startup" 이벤트로 선언합니다: +이 함수들은 `async def` 또는 일반 `def`로 선언할 수 있습니다. + +### `startup` 이벤트 + +애플리케이션이 시작되기 전에 실행되어야 하는 함수를 추가하려면, `"startup"` 이벤트로 선언합니다: {* ../../docs_src/events/tutorial001.py hl[8] *} -이 경우 `startup` 이벤트 핸들러 함수는 단순히 몇 가지 값으로 구성된 `dict` 형식의 "데이터베이스"를 초기화합니다. +이 경우, `startup` 이벤트 핸들러 함수는 "database"라는 항목(단지 `dict`)을 일부 값으로 초기화합니다. -하나 이상의 이벤트 핸들러 함수를 추가할 수도 있습니다. +여러 개의 이벤트 핸들러 함수를 추가할 수 있습니다. -그리고 응용 프로그램은 모든 `startup` 이벤트 핸들러가 완료될 때까지 요청을 받지 않습니다. +애플리케이션은 모든 `startup` 이벤트 핸들러가 완료될 때까지 요청을 받기 시작하지 않습니다. -## `shutdown` 이벤트 +### `shutdown` 이벤트 -응용 프로그램이 종료될 때 실행하려는 함수를 추가하려면 `"shutdown"` 이벤트로 선언합니다: +애플리케이션이 종료될 때 실행되어야 하는 함수를 추가하려면, `"shutdown"` 이벤트로 선언합니다: {* ../../docs_src/events/tutorial002.py hl[6] *} -이 예제에서 `shutdown` 이벤트 핸들러 함수는 `"Application shutdown"`이라는 텍스트가 적힌 `log.txt` 파일을 추가할 것입니다. +여기서, `shutdown` 이벤트 핸들러 함수는 `"Application shutdown"`이라는 텍스트를 `log.txt` 파일에 기록합니다. /// info | 정보 -`open()` 함수에서 `mode="a"`는 "추가"를 의미합니다. 따라서 이미 존재하는 파일의 내용을 덮어쓰지 않고 새로운 줄을 추가합니다. +`open()` 함수에서 `mode="a"`는 "추가"를 의미하므로, 파일에 있는 기존 내용은 덮어쓰지 않고 새로운 줄이 추가됩니다. /// /// tip | 팁 -이 예제에서는 파일과 상호작용 하기 위해 파이썬 표준 함수인 `open()`을 사용하고 있습니다. +이 경우, 우리는 표준 파이썬 `open()` 함수를 사용하여 파일과 상호작용하고 있습니다. -따라서 디스크에 데이터를 쓰기 위해 "대기"가 필요한 I/O (입력/출력) 작업을 수행합니다. +따라서 I/O(입출력) 작업이 포함되어 있어 디스크에 기록되는 것을 "기다리는" 과정이 필요합니다. -그러나 `open()`은 `async`와 `await`을 사용하지 않기 때문에 이벤트 핸들러 함수는 `async def`가 아닌 표준 `def`로 선언하고 있습니다. +하지만 `open()`은 `async`와 `await`를 사용하지 않습니다. + +그래서 우리는 이벤트 핸들러 함수를 `async def` 대신 일반 `def`로 선언합니다. /// +### `startup`과 `shutdown`을 함께 사용 + +*시작*과 *종료* 로직이 연결될 가능성이 높습니다. 예를 들어, 무언가를 시작한 후 끝내거나, 자원을 획득한 후 해제하는 등의 작업을 할 수 있습니다. + +이러한 작업을 별도의 함수로 처리하면 서로 로직이나 변수를 공유하지 않기 때문에 더 어려워집니다. 값들을 전역 변수에 저장하거나 비슷한 트릭을 사용해야 할 수 있습니다. + +그렇기 때문에 위에서 설명한 대로 `lifespan`을 사용하는 것이 권장됩니다. + +## 기술적 세부사항 + +호기심 많은 분들을 위한 기술적인 세부사항입니다. 🤓 + +ASGI 기술 사양에 따르면, 이는 Lifespan Protocol의 일부이며, `startup`과 `shutdown`이라는 이벤트를 정의합니다. + /// info | 정보 -이벤트 핸들러에 관한 내용은 Starlette 이벤트 문서에서 추가로 확인할 수 있습니다. +Starlette의 `lifespan` 핸들러에 대해 더 읽고 싶다면 Starlette의 Lifespan 문서에서 확인할 수 있습니다. + +이 문서에는 코드의 다른 영역에서 사용할 수 있는 lifespan 상태를 처리하는 방법도 포함되어 있습니다. /// + +## 서브 애플리케이션 + +🚨 이 lifespan 이벤트(`startup`과 `shutdown`)는 메인 애플리케이션에 대해서만 실행되며, [서브 애플리케이션 - Mounts](sub-applications.md){.internal-link target=_blank}에는 실행되지 않음을 유의하세요. diff --git a/docs/ko/docs/help-fastapi.md b/docs/ko/docs/help-fastapi.md index 932952b4a..06435d4bb 100644 --- a/docs/ko/docs/help-fastapi.md +++ b/docs/ko/docs/help-fastapi.md @@ -1,162 +1,269 @@ -* # FastAPI 지원 - 도움말 받기 +# FastAPI 지원 - 도움 받기 - **FastAPI** 가 마음에 드시나요? +**FastAPI** 가 마음에 드시나요? - FastAPI, 다른 사용자, 개발자를 응원하고 싶으신가요? +FastAPI, 다른 사용자, 개발자를 응원하고 싶으신가요? - 혹은 **FastAPI** 에 대해 도움이 필요하신가요? +혹은 **FastAPI** 에 대해 도움이 필요하신가요? - 아주 간단하게 응원할 수 있습니다 (몇 번의 클릭만으로). +아주 간단하게 응원할 수 있습니다 (몇 번의 클릭만으로). - 또한 도움을 받을 수 있는 방법도 몇 가지 있습니다. +또한 도움을 받을 수 있는 방법도 몇 가지 있습니다. - ## 뉴스레터 구독 +## 뉴스레터 구독 - [**FastAPI와 친구** 뉴스레터](https://github.com/fastapi/fastapi/blob/master/newsletter)를 구독하여 최신 정보를 유지할 수 있습니다{.internal-link target=_blank}: +[**FastAPI and friends** 뉴스레터](newsletter.md){.internal-link target=\_blank}를 구독하여 최신 정보를 유지할 수 있습니다: - - FastAPI 와 그 친구들에 대한 뉴스 🚀 - - 가이드 📝 - - 특징 ✨ - - 획기적인 변화 🚨 - - 팁과 요령 ✅ +* FastAPI and friends에 대한 뉴스 🚀 +* 가이드 📝 +* 기능 ✨ +* 획기적인 변화 🚨 +* 팁과 요령 ✅ - ## 트위터에서 FastAPI 팔로우하기 +## 트위터에서 FastAPI 팔로우하기 - [Follow @fastapi on **Twitter**](https://twitter.com/fastapi) 를 팔로우하여 **FastAPI** 에 대한 최신 뉴스를 얻을 수 있습니다. 🐦 +**Twitter**의 @fastapi를 팔로우하여 **FastAPI** 에 대한 최신 뉴스를 얻을 수 있습니다. 🐦 - ## Star **FastAPI** in GitHub +## Star **FastAPI** in GitHub - GitHub에서 FastAPI에 "star"를 붙일 수 있습니다(오른쪽 상단의 star 버튼을 클릭): https://github.com/fastapi/fastapi. ⭐️ +GitHub에서 FastAPI에 "star"를 붙일 수 있습니다 (오른쪽 상단의 star 버튼을 클릭): https://github.com/fastapi/fastapi. ⭐️ - 스타를 늘림으로써, 다른 사용자들이 좀 더 쉽게 찾을 수 있고, 많은 사람들에게 유용한 것임을 나타낼 수 있습니다. +스타를 늘림으로써, 다른 사용자들이 좀 더 쉽게 찾을 수 있고, 많은 사람들에게 유용한 것임을 나타낼 수 있습니다. - ## GitHub 저장소에서 릴리즈 확인 +## GitHub 저장소에서 릴리즈 확인 - GitHub에서 FastAPI를 "watch"할 수 있습니다 (오른쪽 상단 watch 버튼을 클릭): https://github.com/fastapi/fastapi. 👀 +GitHub에서 FastAPI를 "watch"할 수 있습니다 (오른쪽 상단 watch 버튼을 클릭): https://github.com/fastapi/fastapi. 👀 - 여기서 "Releases only"을 선택할 수 있습니다. +여기서 "Releases only"을 선택할 수 있습니다. - 이렇게하면, **FastAPI** 의 버그 수정 및 새로운 기능의 구현 등의 새로운 자료 (최신 버전)이 있을 때마다 (이메일) 통지를 받을 수 있습니다. +이렇게하면, **FastAPI** 의 버그 수정 및 새로운 기능의 구현 등의 새로운 자료 (최신 버전)이 있을 때마다 (이메일) 통지를 받을 수 있습니다. - ## 개발자와의 연결 +## 개발자와의 연결 - 개발자인 [me (Sebastián Ramírez / `tiangolo`)](https://tiangolo.com/) 와 연락을 취할 수 있습니다. +개발자(Sebastián Ramírez / `tiangolo`)와 연락을 취할 수 있습니다. - 여러분은 할 수 있습니다: +여러분은 할 수 있습니다: - - [**GitHub**에서 팔로우하기](https://github.com/tiangolo). - - 당신에게 도움이 될 저의 다른 오픈소스 프로젝트를 확인하십시오. - - 새로운 오픈소스 프로젝트를 만들었을 때 확인하려면 팔로우 하십시오. +* **GitHub**에서 팔로우하기.. + * 당신에게 도움이 될 저의 다른 오픈소스 프로젝트를 확인하십시오. + * 새로운 오픈소스 프로젝트를 만들었을 때 확인하려면 팔로우 하십시오. +* **Twitter** 또는 Mastodon에서 팔로우하기. + * FastAPI의 사용 용도를 알려주세요 (그것을 듣는 것을 좋아합니다). + * 발표나 새로운 툴 출시 소식을 받아보십시오. + * **Twitter**의 @fastapi를 팔로우 (별도 계정에서) 할 수 있습니다. +* **LinkedIn**에서 팔로우하기.. + * 새로운 툴의 발표나 출시 소식을 받아보십시오. (단, Twitter를 더 자주 사용합니다 🤷‍♂). +* **Dev.to** 또는 **Medium**에서 제가 작성한 내용을 읽어 보십시오 (또는 팔로우). + * 다른 기사나 아이디어들을 읽고, 제가 만들어왔던 툴에 대해서도 읽으십시오. + * 새로운 기사를 읽기 위해 팔로우 하십시오. - - [**Twitter**에서 팔로우하기](https://twitter.com/tiangolo). - - FastAPI의 사용 용도를 알려주세요 (그것을 듣는 것을 좋아합니다). - - 발표 또는 새로운 툴 출시할 때 들으십시오. - - [follow @fastapi on Twitter](https://twitter.com/fastapi) (별도 계정에서) 할 수 있습니다. +## **FastAPI**에 대한 트윗 - - [**Linkedin**에서의 연결](https://www.linkedin.com/in/tiangolo/). - - 새로운 툴의 발표나 릴리스를 들을 수 있습니다 (단, Twitter를 더 자주 사용합니다 🤷‍♂). +**FastAPI**에 대해 트윗 하고 FastAPI가 마음에 드는 이유를 알려주세요. 🎉 - - [**Dev.to**](https://dev.to/tiangolo) 또는 [**Medium**](https://medium.com/@tiangolo)에서 제가 작성한 내용을 읽어 보십시오(또는 팔로우). - - 다른 기사나 아이디어들을 읽고, 제가 만들어왔던 툴에 대해서도 읽으십시오. - - 새로운 기사를 읽기 위해 팔로우 하십시오. +**FastAPI**가 어떻게 사용되고 있는지, 어떤 점이 마음에 들었는지, 어떤 프로젝트/회사에서 사용하고 있는지 등에 대해 듣고 싶습니다. - ## **FastAPI**에 대한 트윗 +## FastAPI에 투표하기 - [**FastAPI**에 대해 트윗](https://twitter.com/compose/tweet?text=I'm loving @fastapi because... https://github.com/fastapi/fastapi) 하고 FastAPI가 마음에 드는 이유를 알려주세요. 🎉 +* Slant에서 **FastAPI** 에 대해 투표하십시오. +* AlternativeTo에서 **FastAPI** 에 대해 투표하십시오. +* StackShare에서 **FastAPI** 에 대해 투표하십시오. - **FastAPI**가 어떻게 사용되고 있는지, 어떤 점이 마음에 들었는지, 어떤 프로젝트/회사에서 사용하고 있는지 등에 대해 듣고 싶습니다. +## GitHub의 이슈로 다른사람 돕기 - ## FastAPI에 투표하기 +다른 사람들의 질문에 도움을 줄 수 있습니다: - - [Slant에서 **FastAPI** 에 대해 투표하십시오](https://www.slant.co/options/34241/~fastapi-review). - - [AlternativeTo**FastAPI** 에 대해 투표하십시오](https://alternativeto.net/software/fastapi/). +* GitHub 디스커션 +* GitHub 이슈 - ## GitHub의 이슈로 다른사람 돕기 +많은 경우, 여러분은 이미 그 질문에 대한 답을 알고 있을 수도 있습니다. 🤓 - [존재하는 이슈](https://github.com/fastapi/fastapi/issues)를 확인하고 그것을 시도하고 도와줄 수 있습니다. 대부분의 경우 이미 답을 알고 있는 질문입니다. 🤓 +만약 많은 사람들의 문제를 도와준다면, 공식적인 [FastAPI 전문가](fastapi-people.md#fastapi-experts){.internal-link target=\_blank} 가 될 것입니다. 🎉 - 많은 사람들의 문제를 도와준다면, 공식적인 [FastAPI 전문가](https://github.com/fastapi/fastapi/blob/master/docs/en/docs/fastapi-people.md#experts) 가 될 수 있습니다{.internal-link target=_blank}. 🎉 +가장 중요한 점은: 친절하려고 노력하는 것입니다. 사람들은 좌절감을 안고 오며, 많은 경우 최선의 방식으로 질문하지 않을 수도 있습니다. 하지만 최대한 친절하게 대하려고 노력하세요. 🤗 - ## GitHub 저장소 보기 +**FastAPI** 커뮤니티의 목표는 친절하고 환영하는 것입니다. 동시에, 괴롭힘이나 무례한 행동을 받아들이지 마세요. 우리는 서로를 돌봐야 합니다. - GitHub에서 FastAPI를 "watch"할 수 있습니다 (오른쪽 상단 watch 버튼을 클릭): https://github.com/fastapi/fastapi. 👀 +--- - "Releases only" 대신 "Watching"을 선택하면 다른 사용자가 새로운 issue를 생성할 때 알림이 수신됩니다. +다른 사람들의 질문 (디스커션 또는 이슈에서) 해결을 도울 수 있는 방법은 다음과 같습니다. - 그런 다음 이런 issues를 해결 할 수 있도록 도움을 줄 수 있습니다. +### 질문 이해하기 - ## 이슈 생성하기 +* 질문하는 사람이 가진 **목적**과 사용 사례를 이해할 수 있는지 확인하세요. - GitHub 저장소에 [새로운 이슈 생성](https://github.com/fastapi/fastapi/issues/new/choose) 을 할 수 있습니다, 예를들면 다음과 같습니다: +* 질문 (대부분은 질문입니다)이 **명확**한지 확인하세요. - - **질문**을 하거나 **문제**에 대해 질문합니다. - - 새로운 **기능**을 제안 합니다. +* 많은 경우, 사용자가 가정한 해결책에 대한 질문을 하지만, 더 **좋은** 해결책이 있을 수 있습니다. 문제와 사용 사례를 더 잘 이해하면 더 나은 **대안적인 해결책**을 제안할 수 있습니다. - **참고**: 만약 이슈를 생성한다면, 저는 여러분에게 다른 사람들을 도와달라고 부탁할 것입니다. 😉 +* 질문을 이해할 수 없다면, 더 **자세한 정보**를 요청하세요. - ## Pull Request를 만드십시오 +### 문제 재현하기 - Pull Requests를 이용하여 소스코드에 [컨트리뷰트](https://github.com/fastapi/fastapi/blob/master/docs/en/docs/contributing.md){.internal-link target=_blank} 할 수 있습니다. 예를 들면 다음과 같습니다: +대부분의 경우, 질문은 질문자의 **원본 코드**와 관련이 있습니다. - - 문서에서 찾은 오타를 수정할 때. +많은 경우, 코드의 일부만 복사해서 올리지만, 그것만으로는 **문제를 재현**하기에 충분하지 않습니다. - - FastAPI를 [편집하여](https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml) 작성했거나 찾은 문서, 비디오 또는 팟캐스트를 공유할 때. +* 질문자에게 최소한의 재현 가능한 예제를 제공해달라고 요청하세요. 이렇게 하면 코드를 **복사-붙여넣기**하여 직접 실행하고, 동일한 오류나 동작을 확인하거나 사용 사례를 더 잘 이해할 수 있습니다. - - 해당 섹션의 시작 부분에 링크를 추가했는지 확인하십시오. +* 너그러운 마음이 든다면, 문제 설명만을 기반으로 직접 **예제를 만들어**볼 수도 있습니다. 하지만, 이는 시간이 많이 걸릴 수 있으므로, 먼저 질문을 명확히 해달라고 요청하는 것이 좋습니다. - - 당신의 언어로 [문서 번역하는데](https://github.com/fastapi/fastapi/blob/master/docs/en/docs/contributing.md#translations){.internal-link target=_blank} 기여할 때. +### 해결책 제안하기 - - 또한 다른 사용자가 만든 번역을 검토하는데 도움을 줄 수도 있습니다. +* 질문을 충분히 이해한 후에는 가능한 **답변**을 제공할 수 있습니다. - - 새로운 문서의 섹션을 제안할 때. +* 많은 경우, 질문자의 **근본적인 문제나 사용 사례**를 이해하는 것이 중요합니다. 그들이 시도하는 방법보다 더 나은 해결책이 있을 수 있기 때문입니다. - - 기존 문제/버그를 수정할 때. +### 해결 요청하기 - - 새로운 feature를 추가할 때. +질문자가 답변을 확인하고 나면, 당신이 문제를 해결했을 가능성이 높습니다. 축하합니다, **당신은 영웅입니다**! 🦸 - ## 채팅에 참여하십시오 +* 이제 문제를 해결했다면, 질문자에게 다음을 요청할 수 있습니다. - 👥 [디스코드 채팅 서버](https://discord.gg/VQjSZaeJmf) 👥 에 가입하고 FastAPI 커뮤니티에서 다른 사람들과 어울리세요. + * GitHub 디스커션에서: 댓글을 **답변**으로 표시하도록 요청하세요. + * GitHub 이슈에서: 이슈를 **닫아달라고** 요청하세요. - /// tip +## GitHub 저장소 보기 - 질문이 있는 경우, [GitHub 이슈 ](https://github.com/fastapi/fastapi/issues/new/choose) 에서 질문하십시오, [FastAPI 전문가](https://github.com/fastapi/fastapi/blob/master/docs/en/docs/fastapi-people.md#experts) 의 도움을 받을 가능성이 높습니다{.internal-link target=_blank} . +GitHub에서 FastAPI를 "watch"할 수 있습니다 (오른쪽 상단 watch 버튼을 클릭): https://github.com/fastapi/fastapi. 👀 - /// +"Releases only" 대신 "Watching"을 선택하면, 새로운 이슈나 질문이 생성될 때 알림을 받을 수 있습니다. 또한, 특정하게 새로운 이슈, 디스커션, PR 등만 알림 받도록 설정할 수도 있습니다. - ``` - 다른 일반적인 대화에서만 채팅을 사용하십시오. - ``` +그런 다음 이런 이슈들을 해결 할 수 있도록 도움을 줄 수 있습니다. - 기존 [지터 채팅](https://gitter.im/fastapi/fastapi) 이 있지만 채널과 고급기능이 없어서 대화를 하기가 조금 어렵기 때문에 지금은 디스코드가 권장되는 시스템입니다. +## 이슈 생성하기 - ### 질문을 위해 채팅을 사용하지 마십시오 +GitHub 저장소에 새로운 이슈 생성을 할 수 있습니다, 예를들면 다음과 같습니다: - 채팅은 더 많은 "자유로운 대화"를 허용하기 때문에, 너무 일반적인 질문이나 대답하기 어려운 질문을 쉽게 질문을 할 수 있으므로, 답변을 받지 못할 수 있습니다. +* **질문**을 하거나 **문제**에 대해 질문합니다. +* 새로운 **기능**을 제안 합니다. - GitHub 이슈에서의 템플릿은 올바른 질문을 작성하도록 안내하여 더 쉽게 좋은 답변을 얻거나 질문하기 전에 스스로 문제를 해결할 수도 있습니다. 그리고 GitHub에서는 시간이 조금 걸리더라도 항상 모든 것에 답할 수 있습니다. 채팅 시스템에서는 개인적으로 그렇게 할 수 없습니다. 😅 +**참고**: 만약 이슈를 생성한다면, 저는 여러분에게 다른 사람들을 도와달라고 부탁할 것입니다. 😉 - 채팅 시스템에서의 대화 또한 GitHub에서 처럼 쉽게 검색할 수 없기 때문에 대화 중에 질문과 답변이 손실될 수 있습니다. 그리고 GitHub 이슈에 있는 것만 [FastAPI 전문가](https://github.com/fastapi/fastapi/blob/master/docs/en/docs/fastapi-people.md#experts)가 되는 것으로 간주되므로{.internal-link target=_blank} , GitHub 이슈에서 더 많은 관심을 받을 것입니다. +## Pull Requests 리뷰하기 - 반면, 채팅 시스템에는 수천 명의 사용자가 있기 때문에, 거의 항상 대화 상대를 찾을 가능성이 높습니다. 😄 +다른 사람들의 pull request를 리뷰하는 데 도움을 줄 수 있습니다. - ## 개발자 스폰서가 되십시오 +다시 한번 말하지만, 최대한 친절하게 리뷰해 주세요. 🤗 - [GitHub 스폰서](https://github.com/sponsors/tiangolo) 를 통해 개발자를 경제적으로 지원할 수 있습니다. +--- - 감사하다는 말로 커피를 ☕️ 한잔 사줄 수 있습니다. 😄 +Pull Rrquest를 리뷰할 때 고려해야 할 사항과 방법은 다음과 같습니다: - 또한 FastAPI의 실버 또는 골드 스폰서가 될 수 있습니다. 🏅🎉 +### 문제 이해하기 - ## FastAPI를 강화하는 도구의 스폰서가 되십시오 +* 먼저, 해당 pull request가 해결하려는 **문제를 이해하는지** 확인하세요. GitHub 디스커션 또는 이슈에서 더 긴 논의가 있었을 수도 있습니다. - 문서에서 보았듯이, FastAPI는 Starlette과 Pydantic 라는 거인의 어깨에 타고 있습니다. +* Pull request가 필요하지 않을 가능성도 있습니다. **다른 방식**으로 문제를 해결할 수 있다면, 그 방법을 제안하거나 질문할 수 있습니다. - 다음의 스폰서가 될 수 있습니다 +### 스타일에 너무 신경 쓰지 않기 - - [Samuel Colvin (Pydantic)](https://github.com/sponsors/samuelcolvin) - - [Encode (Starlette, Uvicorn)](https://github.com/sponsors/encode) +* 커밋 메시지 스타일 같은 것에 너무 신경 쓰지 않아도 됩니다. 저는 직접 커밋을 수정하여 squash and merge를 수행할 것입니다. - ------ +* 코드 스타일 규칙도 걱정할 필요 없습니다. 이미 자동화된 도구들이 이를 검사하고 있습니다. - 감사합니다! 🚀 +스타일이나 일관성 관련 요청이 필요한 경우, 제가 직접 요청하거나 필요한 변경 사항을 추가 커밋으로 수정할 것입니다. + +### 코드 확인하기 + +* 코드를 읽고, **논리적으로 타당**한지 확인한 후 로컬에서 실행하여 문제가 해결되는지 확인하세요. + +* 그런 다음, 확인했다고 **댓글**을 남겨 주세요. 그래야 제가 검토했음을 알 수 있습니다. + +/// info + +불행히도, 제가 단순히 여러 개의 승인만으로 PR을 신뢰할 수는 없습니다. + +3개, 5개 이상의 승인이 달린 PR이 실제로는 깨져 있거나, 버그가 있거나, 주장하는 문제를 해결하지 못하는 경우가 여러 번 있었습니다. 😅 + +따라서, 정말로 코드를 읽고 실행한 뒤, 댓글로 확인 내용을 남겨 주는 것이 매우 중요합니다. 🤓 + +/// + +* PR을 더 단순하게 만들 수 있다면 그렇게 요청할 수 있지만, 너무 까다로울 필요는 없습니다. 주관적인 견해가 많이 있을 수 있기 때문입니다 (그리고 저도 제 견해가 있을 거예요 🙈). 따라서 핵심적인 부분에 집중하는 것이 좋습니다. + +### 테스트 + +* PR에 **테스트**가 포함되어 있는지 확인하는 데 도움을 주세요. + +* PR을 적용하기 전에 테스트가 **실패**하는지 확인하세요. 🚨 + +* PR을 적용한 후 테스트가 **통과**하는지 확인하세요. ✅ + +* 많은 PR에는 테스트가 없습니다. 테스트를 추가하도록 **상기**시켜줄 수도 있고, 직접 테스트를 **제안**할 수도 있습니다. 이는 시간이 많이 소요되는 부분 중 하나이며, 그 부분을 많이 도와줄 수 있습니다. + +* 그리고 시도한 내용을 댓글로 남겨주세요. 그러면 제가 확인했다는 걸 알 수 있습니다. 🤓 + +## Pull Request를 만드십시오 + +Pull Requests를 이용하여 소스코드에 [컨트리뷰트](contributing.md){.internal-link target=\_blank} 할 수 있습니다. 예를 들면 다음과 같습니다: + +* 문서에서 발견한 오타를 수정할 때. +* FastAPI 관련 문서, 비디오 또는 팟캐스트를 작성했거나 발견하여 이 파일을 편집하여 공유할 때. + * 해당 섹션의 시작 부분에 링크를 추가해야 합니다. +* 당신의 언어로 [문서 번역하는데](contributing.md#translations){.internal-link target=\_blank} 기여할 때. + * 다른 사람이 작성한 번역을 검토하는 것도 도울 수 있습니다. +* 새로운 문서의 섹션을 제안할 때. +* 기존 문제/버그를 수정할 때. + * 테스트를 반드시 추가해야 합니다. +* 새로운 feature를 추가할 때. + * 테스트를 반드시 추가해야 합니다. + * 관련 문서가 필요하다면 반드시 추가해야 합니다. + +## FastAPI 유지 관리에 도움 주기 + +**FastAPI**의 유지 관리를 도와주세요! 🤓 + +할 일이 많고, 그 중 대부분은 **여러분**이 할 수 있습니다. + +지금 할 수 있는 주요 작업은: + +* [GitHub에서 다른 사람들의 질문에 도움 주기](#github_1){.internal-link target=_blank} (위의 섹션을 참조하세요). +* [Pull Request 리뷰하기](#pull-requests){.internal-link target=_blank} (위의 섹션을 참조하세요). + +이 두 작업이 **가장 많은 시간을 소모**하는 일입니다. 그것이 FastAPI 유지 관리의 주요 작업입니다. + +이 작업을 도와주신다면, **FastAPI 유지 관리에 도움을 주는 것**이며 그것이 **더 빠르고 더 잘 발전하는 것**을 보장하는 것입니다. 🚀 + +## 채팅에 참여하십시오 + +👥 디스코드 채팅 서버 👥 에 가입하고 FastAPI 커뮤니티에서 다른 사람들과 어울리세요. + +/// tip + +질문이 있는 경우, GitHub 디스커션 에서 질문하십시오, [FastAPI Experts](fastapi-people.md#fastapi-experts){.internal-link target=_blank} 의 도움을 받을 가능성이 높습니다. + +다른 일반적인 대화에서만 채팅을 사용하십시오. + +/// + +### 질문을 위해 채팅을 사용하지 마십시오 + +채팅은 더 많은 "자유로운 대화"를 허용하기 때문에, 너무 일반적인 질문이나 대답하기 어려운 질문을 쉽게 질문을 할 수 있으므로, 답변을 받지 못할 수 있습니다. + +GitHub 이슈에서의 템플릿은 올바른 질문을 작성하도록 안내하여 더 쉽게 좋은 답변을 얻거나 질문하기 전에 스스로 문제를 해결할 수도 있습니다. 그리고 GitHub에서는 시간이 조금 걸리더라도 항상 모든 것에 답할 수 있습니다. 채팅 시스템에서는 개인적으로 그렇게 할 수 없습니다. 😅 + +채팅 시스템에서의 대화 또한 GitHub에서 처럼 쉽게 검색할 수 없기 때문에 대화 중에 질문과 답변이 손실될 수 있습니다. 그리고 GitHub 이슈에 있는 것만 [FastAPI Expert](fastapi-people.md#fastapi-experts){.internal-link target=_blank}가 되는 것으로 간주되므로, GitHub 이슈에서 더 많은 관심을 받을 것입니다. + +반면, 채팅 시스템에는 수천 명의 사용자가 있기 때문에, 거의 항상 대화 상대를 찾을 가능성이 높습니다. 😄 + +## 개발자 스폰서가 되십시오 + +GitHub 스폰서 를 통해 개발자를 경제적으로 지원할 수 있습니다. + +감사하다는 말로 커피를 ☕️ 한잔 사줄 수 있습니다. 😄 + +또한 FastAPI의 실버 또는 골드 스폰서가 될 수 있습니다. 🏅🎉 + +## FastAPI를 강화하는 도구의 스폰서가 되십시오 + +문서에서 보았듯이, FastAPI는 Starlette과 Pydantic 라는 거인의 어깨에 타고 있습니다. + +다음의 스폰서가 될 수 있습니다 + +* Samuel Colvin (Pydantic) +* Encode (Starlette, Uvicorn) + +--- + +감사합니다! 🚀 diff --git a/docs/ko/docs/index.md b/docs/ko/docs/index.md index 8b00d90bc..0df2000fa 100644 --- a/docs/ko/docs/index.md +++ b/docs/ko/docs/index.md @@ -11,15 +11,18 @@ FastAPI 프레임워크, 고성능, 간편한 학습, 빠른 코드 작성, 준비된 프로덕션

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

--- diff --git a/docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md new file mode 100644 index 000000000..ff174937d --- /dev/null +++ b/docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md @@ -0,0 +1,275 @@ +# yield를 사용하는 의존성 + +FastAPI는 작업 완료 후 추가 단계를 수행하는 의존성을 지원합니다. + +이를 구현하려면 `return` 대신 `yield`를 사용하고, 추가로 실행할 단계 (코드)를 그 뒤에 작성하세요. + +/// tip | 팁 + +각 의존성마다 `yield`는 한 번만 사용해야 합니다. + +/// + +/// note | 기술 세부사항 + +다음과 함께 사용할 수 있는 모든 함수: + +* `@contextlib.contextmanager` 또는 +* `@contextlib.asynccontextmanager` + +는 **FastAPI**의 의존성으로 사용할 수 있습니다. + +사실, FastAPI는 내부적으로 이 두 데코레이터를 사용합니다. + +/// + +## `yield`를 사용하는 데이터베이스 의존성 + +예를 들어, 이 기능을 사용하면 데이터베이스 세션을 생성하고 작업이 끝난 후에 세션을 종료할 수 있습니다. + +응답을 생성하기 전에는 `yield`문을 포함하여 그 이전의 코드만이 실행됩니다: + +{* ../../docs_src/dependencies/tutorial007.py hl[2:4] *} + +yield된 값은 *경로 작업* 및 다른 의존성들에 주입되는 값 입니다: + +{* ../../docs_src/dependencies/tutorial007.py hl[4] *} + +`yield`문 다음의 코드는 응답을 생성한 후 보내기 전에 실행됩니다: + +{* ../../docs_src/dependencies/tutorial007.py hl[5:6] *} + +/// tip | 팁 + +`async` 함수와 일반 함수 모두 사용할 수 있습니다. + +**FastAPI**는 일반 의존성과 마찬가지로 각각의 함수를 올바르게 처리할 것입니다. + +/// + +## `yield`와 `try`를 사용하는 의존성 + +`yield`를 사용하는 의존성에서 `try` 블록을 사용한다면, 의존성을 사용하는 도중 발생한 모든 예외를 받을 수 있습니다. + +예를 들어, 다른 의존성이나 *경로 작업*의 중간에 데이터베이스 트랜잭션 "롤백"이 발생하거나 다른 오류가 발생한다면, 해당 예외를 의존성에서 받을 수 있습니다. + +따라서, 의존성 내에서 `except SomeException`을 사용하여 특정 예외를 처리할 수 있습니다. + +마찬가지로, `finally`를 사용하여 예외 발생 여부와 관계 없이 종료 단계까 실행되도록 할 수 있습니다. + +{* ../../docs_src/dependencies/tutorial007.py hl[3,5] *} + +## `yield`를 사용하는 하위 의존성 + +모든 크기와 형태의 하위 의존성과 하위 의존성의 "트리"도 가질 수 있으며, 이들 모두가 `yield`를 사용할 수 있습니다. + +**FastAPI**는 `yield`를 사용하는 각 의존성의 "종료 코드"가 올바른 순서로 실행되도록 보장합니다. + +예를 들어, `dependency_c`는 `dependency_b`에 의존할 수 있고, `dependency_b`는 `dependency_a`에 의존할 수 있습니다. + +{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[6,14,22] *} + +이들 모두는 `yield`를 사용할 수 있습니다. + +이 경우 `dependency_c`는 종료 코드를 실행하기 위해, `dependency_b`의 값 (여기서는 `dep_b`로 명명)이 여전히 사용 가능해야 합니다. + +그리고, `dependency_b`는 종료 코드를 위해 `dependency_a`의 값 (여기서는 `dep_a`로 명명) 이 사용 가능해야 합니다. + +{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[18:19,26:27] *} + +같은 방식으로, `yield`를 사용하는 의존성과 `return`을 사용하는 의존성을 함께 사용할 수 있으며, 이들 중 일부가 다른 것들에 의존할 수 있습니다. + +그리고 `yield`를 사용하는 다른 여러 의존성을 필요로 하는 단일 의존성을 가질 수도 있습니다. + +원하는 의존성을 원하는 대로 조합할 수 있습니다. + +**FastAPI**는 모든 것이 올바른 순서로 실행되도록 보장합니다. + +/// note | 기술 세부사항 + +파이썬의 Context Managers 덕분에 이 기능이 작동합니다. + +**FastAPI**는 이를 내부적으로 컨텍스트 관리자를 사용하여 구현합니다. + +/// + +## `yield`와 `HTTPException`를 사용하는 의존성 + +`yield`와 `try` 블록이 있는 의존성을 사용하여 예외를 처리할 수 있다는 것을 알게 되었습니다. + +같은 방식으로, `yield` 이후의 종료 코드에서 `HTTPException`이나 유사한 예외를 발생시킬 수 있습니다. + +/// tip | 팁 + +이는 다소 고급 기술이며, 대부분의 경우 경로 연산 함수 등 나머지 애플리케이션 코드 내부에서 예외 (`HTTPException` 포함)를 발생시킬 수 있으므로 실제로는 필요하지 않을 것입니다. + +하지만 필요한 경우 사용할 수 있습니다. 🤓 + +/// + +{* ../../docs_src/dependencies/tutorial008b_an_py39.py hl[18:22,31] *} + +예외를 처리하고(또는 추가로 다른 `HTTPException`을 발생시키기 위해) 사용할 수 있는 또 다른 방법은 [사용자 정의 예외 처리기](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}를 생성하는 것 입니다. + +## `yield`와 `except`를 사용하는 의존성 + +`yield`를 사용하는 의존성에서 `except`를 사용하여 예외를 포착하고 예외를 다시 발생시키지 않거나 (또는 새 예외를 발생시키지 않으면), FastAPI는 해당 예외가 발생했는지 알 수 없습니다. 이는 일반적인 Python 방식과 동일합니다: + +{* ../../docs_src/dependencies/tutorial008c_an_py39.py hl[15:16] *} + +이 경우, `HTTPException`이나 유사한 예외를 발생시키지 않기 때문에 클라이언트는 HTTP 500 Internal Server Error 응답을 보게 되지만, 서버는 어떤 오류가 발생했는지에 대한 **로그**나 다른 표시를 전혀 가지지 않게 됩니다. 😱 + +### `yield`와 `except`를 사용하는 의존성에서 항상 `raise` 하기 + +`yield`가 있는 의존성에서 예외를 잡았을 때는 `HTTPException`이나 유사한 예외를 새로 발생시키지 않는 한, 반드시 원래의 예외를 다시 발생시켜야 합니다. + +`raise`를 사용하여 동일한 예외를 다시 발생시킬 수 있습니다: + +{* ../../docs_src/dependencies/tutorial008d_an_py39.py hl[17] *} + +이제 클라이언트는 동일한 *HTTP 500 Internal Server Error* 오류 응답을 받게 되지만, 서버 로그에는 사용자 정의 예외인 `InternalError"가 기록됩니다. 😎 + +## `yield`를 사용하는 의존성의 실행 순서 + +실행 순서는 아래 다이어그램과 거의 비슷합니다. 시간은 위에서 아래로 흐릅니다. 그리고 각 열은 상호 작용하거나 코드를 실행하는 부분 중 하나입니다. + +```mermaid +sequenceDiagram + +participant client as Client +participant handler as Exception handler +participant dep as Dep with yield +participant operation as Path Operation +participant tasks as Background tasks + + Note over client,operation: Can raise exceptions, including HTTPException + client ->> dep: Start request + Note over dep: Run code up to yield + opt raise Exception + dep -->> handler: Raise Exception + handler -->> client: HTTP error response + end + dep ->> operation: Run dependency, e.g. DB session + opt raise + operation -->> dep: Raise Exception (e.g. HTTPException) + opt handle + dep -->> dep: Can catch exception, raise a new HTTPException, raise other exception + end + handler -->> client: HTTP error response + end + + operation ->> client: Return response to client + Note over client,operation: Response is already sent, can't change it anymore + opt Tasks + operation -->> tasks: Send background tasks + end + opt Raise other exception + tasks -->> tasks: Handle exceptions in the background task code + end +``` + +/// info | 정보 + +클라이언트에 **하나의 응답** 만 전송됩니다. 이는 오류 응답 중 하나일 수도 있고,*경로 작업*에서 생성된 응답일 수도 있습니다. + +이러한 응답 중 하나가 전송된 후에는 다른 응답을 보낼 수 없습니다. + +/// + +/// tip | 팁 + +이 다이어그램은 `HTTPException`을 보여주지만, `yield`를 사용하는 의존성에서 처리한 예외나 [사용자 정의 예외처리기](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}.를 사용하여 처리한 다른 예외도 발생시킬 수 있습니다. + +어떤 예외가 발생하든, `HTTPException`을 포함하여 yield를 사용하는 의존성으로 전달됩니다. 대부분의 경우 예외를 다시 발생시키거나 새로운 예외를 발생시켜야 합니다. + +/// + +## `yield`, `HTTPException`, `except` 및 백그라운드 작업을 사용하는 의존성 + +/// warning | 경고 + +이러한 기술적 세부 사항은 대부분 필요하지 않으므로 이 섹션을 건너뛰고 아래에서 계속 진행해도 됩니다. + +이러한 세부 정보는 주로 FastAPI 0.106.0 이전 버전에서 `yield`가 있는 의존성의 리소스를 백그라운드 작업에서 사용했던 경우메 유용합니다. + +/// + +### `yield`와 `except`를 사용하는 의존성, 기술 세부사항 + +FastAPI 0.110.0 이전에는 `yield`가 포함된 의존성을 사용한 후 해당 의존성에서 `except`가 포함된 예외를 캡처하고 다시 예외를 발생시키지 않으면 예외가 자동으로 예외 핸들러 또는 내부 서버 오류 핸들러로 발생/전달되었습니다. + +이는 처리기 없이 전달된 예외(내부 서버 오류)에서 처리되지 않은 메모리 소비를 수정하고 일반 파이썬 코드의 동작과 일치하도록 하기 위해 0.110.0 버전에서 변경되었습니다. + +### 백그라운드 작업과 `yield`를 사용하는 의존성, 기술 세부사항 + +FastAPI 0.106.0 이전에는 `yield` 이후에 예외를 발생시키는 것이 불가능했습니다. `yield`가 있는 의존성 종료 코드는 응답이 전송된 이후에 실행되었기 때문에, [예외 처리기](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}가 이미 실행된 상태였습니다. + +이는 주로 백그라운드 작업 내에서 의존성에서 "yield된" 동일한 객체를 사용할 수 있도록 하기 위해 이런 방식으로 설계되었습니다. 종료 코드는 백그라운드 작업이 완료된 후에 실행되었기 때문입니다 + +하지만 이렇게 하면 리소스를 불필요하게 양보한 의존성(예: 데이터베이스 연결)에서 보유하면서 응답이 네트워크를 통해 이동할 때까지 기다리는 것을 의미하기 때문에 FastAPI 0.106.0에서 변경되었습니다. + +/// tip | 팁 + +또한 백그라운드 작업은 일반적으로 자체 리소스(예: 자체 데이터베이스 연결)를 사용하여 별도로 처리해야 하는 독립적인 로직 집합입니다. + +따라서 이렇게 하면 코드가 더 깔끔해집니다. + +/// + +만약 이전에 이러한 동작에 의존했다면, 이제는 백그라운드 작업 내부에서 백그라운드 작업을 위한 리소스를 생성하고, `yield`가 있는 의존성의 리소스에 의존하지 않는 데이터만 내부적으로 사용해야합니다. + +예를 들어, 동일한 데이터베이스 세션을 사용하는 대신, 백그라운드 작업 내부에서 새로운 데이터베이스 세션을 생성하고 이 새로운 세션을 사용하여 데이터베이스에서 객체를 가져와야 합니다. 그리고 데이터베이스 객체를 백그라운드 작업 함수의 매개변수로 직접 전달하는 대신, 해당 객체의 ID를 전달한 다음 백그라운드 작업 함수 내부에서 객체를 다시 가져와야 합니다 + +## 컨텍스트 관리자 + +### "컨텍스트 관리자"란? + +"컨텍스트 관리자"는 Python에서 `with` 문에서 사용할 수 있는 모든 객체를 의미합니다. + +예를 들어, `with`를 사용하여 파일을 읽을 수 있습니다: + +```Python +with open("./somefile.txt") as f: + contents = f.read() + print(contents) +``` + +내부적으로 `open("./somefile.txt")` 는 "컨텍스트 관리자(Context Manager)"라고 불리는 객체를 생성합니다. + +`with` 블록이 끝나면, 예외가 발생했더라도 파일을 닫도록 보장합니다. + +`yield`가 있는 의존성을 생성하면 **FastAPI**는 내부적으로 이를 위한 컨텍스트 매니저를 생성하고 다른 관련 도구들과 결합합니다. + +### `yield`를 사용하는 의존성에서 컨텍스트 관리자 사용하기 + +/// warning | 경고 + +이것은 어느 정도 "고급" 개념입니다. + +**FastAPI**를 처음 시작하는 경우 지금은 이 부분을 건너뛰어도 좋습니다. + +/// + +Python에서는 다음을 통해 컨텍스트 관리자를 생성할 수 있습니다. 두 가지 메서드가 있는 클래스를 생성합니다: `__enter__()` and `__exit__()`. + +**FastAPI**의 `yield`가 있는 의존성 내에서 +`with` 또는 `async with`문을 사용하여 이들을 활용할 수 있습니다: + +{* ../../docs_src/dependencies/tutorial010.py hl[1:9,13] *} + +/// tip | 팁 + +컨텍스트 관리자를 생성하는 또 다른 방법은 다음과 같습니다: + +* `@contextlib.contextmanager` 또는 +* `@contextlib.asynccontextmanager` + +이들은 단일 `yield`가 있는 함수를 꾸미는 데 사용합니다. + +이것이 **FastAPI**가 `yield`가 있는 의존성을 위해 내부적으로 사용하는 방식입니다. + +하지만 FastAPI 의존성에는 이러한 데코레이터를 사용할 필요가 없습니다(그리고 사용해서도 안됩니다). + +FastAPI가 내부적으로 이를 처리해 줄 것입니다. + +/// diff --git a/docs/ko/docs/tutorial/extra-models.md b/docs/ko/docs/tutorial/extra-models.md new file mode 100644 index 000000000..8e4559061 --- /dev/null +++ b/docs/ko/docs/tutorial/extra-models.md @@ -0,0 +1,223 @@ +# 추가 모델 + +지난 예제에 이어서, 연관된 모델을 여러개 갖는 것은 흔한 일입니다. + +특히 사용자 모델의 경우에 그러한데, 왜냐하면: + +* **입력 모델** 은 비밀번호를 가져야 합니다. +* **출력 모델** 은 비밀번호를 가지면 안됩니다. +* **데이터베이스 모델** 은 해시처리된 비밀번호를 가질 것입니다. + +/// danger | 위험 + +절대 사용자의 비밀번호를 평문으로 저장하지 마세요. 항상 이후에 검증 가능한 "안전한 해시(secure hash)"로 저장하세요. + +만약 이게 무엇인지 모르겠다면, [security chapters](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}.에서 비밀번호 해시에 대해 배울 수 있습니다. + +/// + +## 다중 모델 + +아래는 비밀번호 필드와 해당 필드가 사용되는 위치를 포함하여, 각 모델들이 어떤 형태를 가질 수 있는지 전반적인 예시입니다: + +{* ../../docs_src/extra_models/tutorial001_py310.py hl[7,9,14,20,22,27:28,31:33,38:39] *} + + +/// info | 정보 + +Pydantic v1에서는 해당 메서드가 `.dict()`로 불렸으며, Pydantic v2에서는 `.model_dump()`로 이름이 변경되었습니다. `.dict()`는 여전히 지원되지만 더 이상 권장되지 않습니다. + +여기에서 사용하는 예제는 Pydantic v1과의 호환성을 위해 `.dict()`를 사용하지만, Pydantic v2를 사용할 수 있다면 `.model_dump()`를 사용하는 것이 좋습니다. + +/// + +### `**user_in.dict()` 에 대하여 + +#### Pydantic의 `.dict()` + +`user_in`은 Pydantic 모델 클래스인 `UserIn`입니다. + +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` 언패킹(Unpacking) + +`user_dict`와 같은 `dict`를 함수(또는 클래스)에 `**user_dict`로 전달하면, Python은 이를 "언팩(unpack)"합니다. 이 과정에서 `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`이며, 이를 `**`로 Python이 "언팩(unpack)"하도록 하여 `UserInDB`에 전달하기 때문입니다. + +따라서, 다른 Pydantic 모델의 데이터를 사용하여 새로운 Pydantic 모델을 생성할 수 있습니다. + +#### `dict` 언패킹(Unpacking)과 추가 키워드 + +그리고 다음과 같이 추가 키워드 인자 `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 | 경고 + +추가적으로 제공된 함수 `fake_password_hasher`와 `fake_save_user`는 데이터 흐름을 시연하기 위한 예제일 뿐이며, 실제 보안을 제공하지 않습니다. + +/// + +## 중복 줄이기 + +코드 중복을 줄이는 것은 **FastAPI**의 핵심 아이디어 중 하나입니다. + +코드 중복은 버그, 보안 문제, 코드 비동기화 문제(한 곳은 업데이트되었지만 다른 곳은 업데이트되지 않는 문제) 등의 가능성을 증가시킵니다. + +그리고 이 모델들은 많은 데이터를 공유하면서 속성 이름과 타입을 중복하고 있습니다. + +더 나은 방법이 있습니다. + +`UserBase` 모델을 선언하여 다른 모델들의 기본(base)으로 사용할 수 있습니다. 그런 다음 이 모델을 상속받아 속성과 타입 선언(유형 선언, 검증 등)을 상속하는 서브클래스를 만들 수 있습니다. + +모든 데이터 변환, 검증, 문서화 등은 정상적으로 작동할 것입니다. + +이렇게 하면 각 모델 간의 차이점만 선언할 수 있습니다(평문 `password`가 있는 경우, `hashed_password`만 있는 경우, 혹은 비밀번호가 없는 경우): + +{* ../../docs_src/extra_models/tutorial002_py310.py hl[7,13:14,17:18,21:22] *} + +## `Union` 또는 `anyOf` + +두 가지 이상의 타입을 포함하는 `Union`으로 응답을 선언할 수 있습니다. 이는 응답이 그 중 하나의 타입일 수 있음을 의미합니다. + +OpenAPI에서는 이를 `anyOf`로 정의합니다. + +이를 위해 표준 Python 타입 힌트인 `typing.Union`을 사용할 수 있습니다: + +/// note | 참고 + +`Union`을 정의할때는 더 구체적인 타입을 먼저 포함하고, 덜 구체적인 타입을 그 뒤에 나열해야합니다. 아래 예제에서는 `Union[PlaneItem, CarItem]` 를 보면, 더 구체적인 `PlaneItem`이 `CarItem`보다 앞에 위치합니다. + +/// + +{* ../../docs_src/extra_models/tutorial003_py310.py hl[1,14:15,18:20,33] *} + + +### Python 3.10에서 `Union` + +위의 예제에서는 `response_model` 인자 값으로 `Union[PlaneItem, CarItem]`을 전달합니다. + +이 경우, 이를 **타입 어노테이션(type annotation)** 이 아닌 **인자 값(argument value)** 으로 전달하고 있기 때문에 Python 3.10에서도 `Union`을 사용해야 합니다. + +만약 타입 어노테이션에 사용한다면, 다음과 같이 수직 막대(|)를 사용할 수 있습니다: + +```Python +some_variable: PlaneItem | CarItem +``` + +하지만 이를 `response_model=PlaneItem | CarItem`과 같이 할당하면 에러가 발생합니다. 이는 Python이 이를 타입 어노테이션으로 해석하지 않고, `PlaneItem`과 `CarItem` 사이의 **잘못된 연산(invalid operation)**을 시도하기 때문입니다 + +## 모델 리스트 + +마찬가지로, 객체 리스트 형태의 응답을 선언할 수도 있습니다. + +이를 위해 표준 Python의 `typing.List`를 사용하세요(또는 Python 3.9 이상에서는 단순히 `list`를 사용할 수 있습니다): + +{* ../../docs_src/extra_models/tutorial004_py39.py hl[18] *} + + +## 임의의 `dict` 응답 + +Pydantic 모델을 사용하지 않고, 키와 값의 타입만 선언하여 평범한 임의의 `dict`로 응답을 선언할 수도 있습니다. + +이는 Pydantic 모델에 필요한 유효한 필드/속성 이름을 사전에 알 수 없는 경우에 유용합니다. + +이 경우, `typing.Dict`를 사용할 수 있습니다(또는 Python 3.9 이상에서는 단순히 `dict`를 사용할 수 있습니다): + +{* ../../docs_src/extra_models/tutorial005_py39.py hl[6] *} + + +## 요약 + +여러 Pydantic 모델을 사용하고, 각 경우에 맞게 자유롭게 상속하세요. + +엔터티가 서로 다른 "상태"를 가져야 하는 경우, 엔터티당 단일 데이터 모델을 사용할 필요는 없습니다. 예를 들어, 사용자 "엔터티"가 `password`, `password_hash`, 또는 비밀번호가 없는 상태를 포함할 수 있는 경우처럼 말입니다. diff --git a/docs/ko/docs/tutorial/security/oauth2-jwt.md b/docs/ko/docs/tutorial/security/oauth2-jwt.md new file mode 100644 index 000000000..d8bac8346 --- /dev/null +++ b/docs/ko/docs/tutorial/security/oauth2-jwt.md @@ -0,0 +1,273 @@ +# 패스워드 해싱을 이용한 OAuth2, JWT 토큰을 사용하는 Bearer 인증 + +모든 보안 흐름을 구성했으므로, 이제 JWT 토큰과 패스워드 해싱을 사용해 애플리케이션을 안전하게 만들 것입니다. + +이 코드는 실제로 애플리케이션에서 패스워드를 해싱하여 DB에 저장하는 등의 작업에 활용할 수 있습니다. + +이전 장에 이어서 시작해 봅시다. + +## JWT + +JWT 는 "JSON Web Tokens" 을 의미합니다. + +JSON 객체를 공백이 없는 긴 문자열로 인코딩하는 표준이며, 다음과 같은 형태입니다: + +``` +eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c +``` + +JWT는 암호화되지 않아 누구든지 토큰에서 정보를 복원할 수 있습니다. + +하지만 JWT는 서명되어 있습니다. 그래서 자신이 발급한 토큰을 받았을 때, 실제로 자신이 발급한게 맞는지 검증할 수 있습니다. + +만료 기간이 일주일인 토큰을 발행했다고 가정해 봅시다. 다음 날 사용자가 토큰을 가져왔을 때, 그 사용자가 시스템에 여전히 로그인되어 있다는 것을 알 수 있습니다. + +일주일 뒤에는 토큰이 만료될 것이고, 사용자는 인가되지 않아 새 토큰을 받기 위해 다시 로그인해야 할 것입니다. 만약 사용자(또는 제3자)가 토큰을 수정하거나 만료일을 변경하면, 서명이 일치하지 않기 때문에 알아챌 수 있을 것입니다. + +만약 JWT 토큰을 다뤄보고, 작동 방식도 알아보고 싶다면 https://jwt.io 을 확인하십시오. + +## `PyJWT` 설치 + +파이썬으로 JWT 토큰을 생성하고 검증하려면 `PyJWT` 를 설치해야 합니다. + +[가상환경](../../virtual-environments.md){.internal-link target=_blank} 을 만들고 활성화한 다음 `pyjwt` 를 설치하십시오: + +
+ +```console +$ pip install pyjwt + +---> 100% +``` + +
+ +/// info | 참고 + +RSA나 ECDSA 같은 전자 서명 알고리즘을 사용하려면, `pyjwt[crypto]`라는 암호화 라이브러리 의존성을 설치해야 합니다. + +더 자세한 내용은 PyJWT 설치 에서 확인할 수 있습니다. + +/// + +## 패스워드 해싱 + +"해싱(Hashing)"은 어떤 내용(여기서는 패스워드)을 해석할 수 없는 일련의 바이트 집합(단순 문자열)으로 변환하는 것을 의미합니다. + +동일한 내용(똑같은 패스워드)을 해싱하면 동일한 문자열을 얻습니다. + +하지만 그 문자열을 다시 패스워드로 되돌릴 수는 없습니다. + +### 패스워드를 해싱하는 이유 + +데이터베이스를 탈취당하더라도, 침입자는 사용자의 평문 패스워드 대신 해시 값만 얻을 수 있습니다. + +따라서 침입자는 훔친 사용자 패스워드를 다른 시스템에서 활용할 수 없습니다. (대다수 사용자가 여러 시스템에서 동일한 패스워드를 사용하기 때문에 평문 패스워드가 유출되면 위험합니다.) + +## `passlib` 설치 + +PassLib는 패스워드 해시를 다루는 훌륭한 파이썬 패키지입니다. + +많은 안전한 해시 알고리즘과 도구들을 지원합니다. + +추천하는 알고리즘은 "Bcrypt"입니다. + +[가상환경](../../virtual-environments.md){.internal-link target=_blank} 을 만들고 활성화한 다음 PassLib와 Bcrypt를 설치하십시오: + +
+ +```console +$ pip install "passlib[bcrypt]" + +---> 100% +``` + +
+ +/// tip | 팁 + +`passlib`를 사용하여, **Django**, **Flask** 의 보안 플러그인이나 다른 도구로 생성한 패스워드를 읽을 수 있도록 설정할 수도 있습니다. + +예를 들자면, FastAPI 애플리케이션과 Django 애플리케이션이 같은 데이터베이스에서 데이터를 공유할 수 있습니다. 또는 같은 데이터베이스를 사용하여 Django 애플리케이션을 점진적으로 마이그레이션 할 수도 있습니다. + +그리고 사용자는 FastAPI 애플리케이션과 Django 애플리케이션에 동시에 로그인할 수 있습니다. + +/// + +## 패스워드의 해시와 검증 + +필요한 도구를 `passlib`에서 임포트합니다. + +PassLib "컨텍스트(context)"를 생성합니다. 이것은 패스워드를 해싱하고 검증하는데 사용합니다. + +/// tip | 팁 + +PassLib 컨텍스트는 다양한 해싱 알고리즘을 사용할 수 있는 기능을 제공하며, 더 이상 사용이 권장되지 않는 오래된 해싱 알고리즘을 검증하는 기능도 포함되어 있습니다. + +예를 들어, 다른 시스템(Django 같은)에서 생성한 패스워드를 읽고 검증할 수 있으며, 새로운 패스워드를 Bcrypt 같은 다른 알고리즘으로 해싱할 수도 있습니다. + +그리고 동시에 그런 모든 알고리즘과 호환성을 유지합니다. + +/// + +사용자로부터 받은 패스워드를 해싱하는 유틸리티 함수를 생성합니다. + +그리고 받은 패스워드가 저장된 해시와 일치하는지 검증하는 또 다른 유틸리티 함수도 생성합니다. + +그리고 사용자를 인증하고 반환하는 또 다른 함수도 생성합니다. + +{* ../../docs_src/security/tutorial004_an_py310.py hl[8,49,56:57,60:61,70:76] *} + +/// note + +새로운 (가짜) 데이터베이스 `fake_users_db`를 확인하면, 해시 처리된 패스워드가 어떻게 생겼는지 볼 수 있습니다: `"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"`. + +/// + +## JWT 토큰 처리 + +설치된 모듈을 임포트 합니다. + +JWT 토큰 서명에 사용될 임의의 비밀키를 생성합니다. + +안전한 임의의 비밀키를 생성하려면 다음 명령어를 사용하십시오: + +
+ +```console +$ openssl rand -hex 32 + +09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7 +``` + +
+ +그리고 생성한 비밀키를 복사해 변수 `SECRET_KEY`에 대입합니다. (이 예제의 변수 값을 그대로 사용하지 마십시오.) + +JWT 토큰을 서명하는 데 사용될 알고리즘을 위한 변수 `ALGORITHM` 을 생성하고 `"HS256"` 으로 설정합니다. + +토큰 만료 기간을 위한 변수를 생성합니다. + +응답을 위한 토큰 엔드포인트에 사용될 Pydantic 모델을 정의합니다. + +새 액세스 토큰을 생성하기 위한 유틸리티 함수를 생성합니다. + +{* ../../docs_src/security/tutorial004_an_py310.py hl[4,7,13:15,29:31,79:87] *} + +## 의존성 수정 + +`get_current_user` 함수를 이전과 동일한 토큰을 받도록 수정하되, 이번에는 JWT 토큰을 사용하도록 합니다. + +받은 토큰을 디코딩하여 검증한 후 현재 사용자를 반환합니다. + +토큰이 유효하지 않다면 HTTP 오류를 반환합니다. + +{* ../../docs_src/security/tutorial004_an_py310.py hl[90:107] *} + +## `/token` 경로 작업 수정 + +토큰의 만료 시각을 설정하기 위해 `timedelta` 를 생성합니다. + +실제 JWT 액세스 토큰을 생성하여 반환합니다. + +{* ../../docs_src/security/tutorial004_an_py310.py hl[118:133] *} + +### JWT "주체(subject)" `sub`에 대한 기술 세부 사항 + +JWT 명세에 따르면 토큰의 주체를 포함하는 `sub`라는 키가 있습니다. + +사용 여부는 선택사항이지만, 사용자의 식별 정보를 저장할 수 있으므로 여기서는 이를 사용합니다. + +JWT는 사용자를 식별하고 사용자가 API를 직접 사용할 수 있도록 허용하는 것 외에도 다른 용도로 사용될 수도 있습니다. + +예를 들어 "자동차"나 "블로그 게시물"을 식별하는 데 사용할 수 있습니다. + +그리고 "자동차를 운전하다"나 "블로그 게시물을 수정하다"처럼 해당 엔터티에 대한 권한을 추가할 수 있습니다. + +그 후 이 JWT 토큰을 사용자(또는 봇)에게 제공하면, 그들은 계정을 따로 만들 필요 없이 API가 생성한 JWT 토큰만으로 작업(자동차 운전 또는 블로그 게시물 편집)을 수행할 수 있습니다. + +이러한 개념을 활용하면 JWT는 훨씬 더 복잡한 시나리오에도 사용할 수 있습니다. + +이 경우 여러 엔터티가 동일한 ID를 가질 수 있습니다. 예를 들어 foo라는 ID를 가진 사용자, 자동차, 블로그 게시물이 있을 수 있습니다. + +그래서 ID 충돌을 방지하기 위해, 사용자의 JWT 토큰을 생성할 때 접두사로 `sub` 키를 추가할 수 있습니다. 예를 들어 `username:` 을 붙이는 방식입니다. 이 예제에서는 `sub` 값이 `username:johndoe`이 될 수 있습니다. + +가장 중요한 점은 `sub` 키는 전체 애플리케이션에서 고유한 식별자가 되어야 하며 문자열이어야 한다는 점입니다. + +## 확인해봅시다 + +서버를 실행하고 문서로 이동하십시오: http://127.0.0.1:8000/docs. + +다음과 같은 사용자 인터페이스를 볼 수 있습니다: + + + +이전과 같은 방법으로 애플리케이션에 인증하십시오. + +다음 인증 정보를 사용하십시오: + +Username: `johndoe` +Password: `secret` + +/// check + +코드 어디에도 평문 패스워드 "`secret`" 이 없다는 점에 유의하십시오. 해시된 버전만 있습니다. + +/// + + + +`/users/me/` 를 호출하면 다음과 같은 응답을 얻을 수 있습니다: + +```JSON +{ + "username": "johndoe", + "email": "johndoe@example.com", + "full_name": "John Doe", + "disabled": false +} +``` + + + +개발자 도구를 열어보면 전송된 데이터에 토큰만 포함된 것을 확인할 수 있습니다. 패스워드는 사용자를 인증하고 액세스 토큰을 받기 위한 첫 번째 요청에만 전송되며, 이후에는 전송되지 않습니다: + + + +/// note + +`Bearer `로 시작하는 `Authorization` 헤더에 주목하십시오. + +/// + +## `scopes` 의 고급 사용법 + +OAuth2는 "스코프(scopes)" 라는 개념을 갖고 있습니다. + +이를 사용하여 JWT 토큰에 특정 권한 집합을 추가할 수 있습니다. + +그 후 이 토큰을 사용자에게 직접 제공하거나 제3자에게 제공하여, 특정 제한사항 하에있는 API와 통신하도록 할 수 있습니다. + +**FastAPI** 에서의 사용 방법과 통합 방식은 **심화 사용자 안내서** 에서 자세히 배울 수 있습니다. + +## 요약 + +지금까지 살펴본 내용을 바탕으로, OAuth2와 JWT 같은 표준을 사용하여 안전한 **FastAPI** 애플리케이션을 만들 수 있습니다. + +거의 모든 프레임워크에서 보안 처리는 상당히 복잡한 주제입니다. + +이를 단순화하는 많은 패키지는 데이터 모델, 데이터베이스, 사용 가능한 기능들에 대해 여러 제약이 있습니다. 그리고 지나치게 단순화하는 일부 패키지들은 심각한 보안 결함을 가질 수도 있습니다. + +--- + +**FastAPI** 는 어떤 데이터베이스, 데이터 모델, 도구도 강요하지 않습니다. + +프로젝트에 가장 적합한 것을 선택할 수 있는 유연성을 제공합니다. + +그리고 `passlib` 와 `PyJWT` 처럼 잘 관리되고 널리 사용되는 패키지들을 바로 사용할 수 있습니다. **FastAPI** 는 외부 패키지 통합을 위해 복잡한 메커니즘이 필요하지 않기 때문입니다. + +그러나 유연성, 견고성, 보안성을 해치지 않으면서 과정을 단순화할 수 있는 도구들을 제공합니다. + +그리고 OAuth2와 같은 표준 프로토콜을 비교적 간단한 방법으로 구현하고 사용할 수 있습니다. + +더 세분화된 권한 체계를 위해 OAuth2의 "스코프"를 사용하는 방법은 **심화 사용자 안내서**에서 더 자세히 배울 수 있습니다. OAuth2의 스코프는 제3자 애플리케이션이 사용자를 대신해 그들의 API와 상호작용하도록 권한을 부여하기 위해, Facebook, Google, GitHub, Microsoft, Twitter 등의 많은 대형 인증 제공업체들이 사용하는 메커니즘입니다. diff --git a/docs/ko/docs/tutorial/security/simple-oauth2.md b/docs/ko/docs/tutorial/security/simple-oauth2.md index ddc7430af..f10c4f588 100644 --- a/docs/ko/docs/tutorial/security/simple-oauth2.md +++ b/docs/ko/docs/tutorial/security/simple-oauth2.md @@ -32,7 +32,7 @@ OAuth2는 (우리가 사용하고 있는) "패스워드 플로우"을 사용할 * `instagram_basic`은 페이스북/인스타그램에서 사용합니다. * `https://www.googleapis.com/auth/drive`는 Google에서 사용합니다. -/// 정보 +/// info | 정보 OAuth2에서 "범위"는 필요한 특정 권한을 선언하는 문자열입니다. @@ -61,7 +61,7 @@ OAuth2의 경우 문자열일 뿐입니다. * `scope`는 선택적인 필드로 공백으로 구분된 문자열로 구성된 큰 문자열입니다. * `grant_type`(선택적으로 사용). -/// 팁 +/// tip | 팁 OAuth2 사양은 실제로 `password`라는 고정 값이 있는 `grant_type` 필드를 *요구*하지만 `OAuth2PasswordRequestForm`은 이를 강요하지 않습니다. @@ -72,7 +72,7 @@ OAuth2 사양은 실제로 `password`라는 고정 값이 있는 `grant_type` * `client_id`(선택적으로 사용) (예제에서는 필요하지 않습니다). * `client_secret`(선택적으로 사용) (예제에서는 필요하지 않습니다). -/// 정보 +/// info | 정보 `OAuth2PasswordRequestForm`은 `OAuth2PasswordBearer`와 같이 **FastAPI**에 대한 특수 클래스가 아닙니다. @@ -86,7 +86,7 @@ OAuth2 사양은 실제로 `password`라는 고정 값이 있는 `grant_type` ### 폼 데이터 사용하기 -/// 팁 +/// tip | 팁 종속성 클래스 `OAuth2PasswordRequestForm`의 인스턴스에는 공백으로 구분된 긴 문자열이 있는 `scope` 속성이 없고 대신 전송된 각 범위에 대한 실제 문자열 목록이 있는 `scopes` 속성이 있습니다. @@ -126,7 +126,7 @@ OAuth2 사양은 실제로 `password`라는 고정 값이 있는 `grant_type` 따라서 해커는 다른 시스템에서 동일한 암호를 사용하려고 시도할 수 없습니다(많은 사용자가 모든 곳에서 동일한 암호를 사용하므로 이는 위험할 수 있습니다). -//// tab | P파이썬 3.7 이상 +//// tab | 파이썬 3.7 이상 {* ../../docs_src/security/tutorial003.py hl[80:83] *} @@ -150,7 +150,7 @@ UserInDB( ) ``` -/// 정보 +/// info | 정보 `**user_dict`에 대한 자세한 설명은 [**추가 모델** 문서](../extra-models.md#about-user_indict){.internal-link target=_blank}를 다시 읽어봅시다. @@ -166,7 +166,7 @@ UserInDB( 이 간단한 예제에서는 완전히 안전하지 않고, 동일한 `username`을 토큰으로 반환합니다. -/// 팁 +/// tip | 팁 다음 장에서는 패스워드 해싱 및 JWT 토큰을 사용하여 실제 보안 구현을 볼 수 있습니다. @@ -176,7 +176,7 @@ UserInDB( {* ../../docs_src/security/tutorial003.py hl[85] *} -/// 팁 +/// tip | 팁 사양에 따라 이 예제와 동일하게 `access_token` 및 `token_type`이 포함된 JSON을 반환해야 합니다. @@ -202,7 +202,7 @@ UserInDB( {* ../../docs_src/security/tutorial003.py hl[58:66,69:72,90] *} -/// 정보 +/// info | 정보 여기서 반환하는 값이 `Bearer`인 추가 헤더 `WWW-Authenticate`도 사양의 일부입니다. diff --git a/docs/ko/docs/virtual-environments.md b/docs/ko/docs/virtual-environments.md new file mode 100644 index 000000000..0d10c3200 --- /dev/null +++ b/docs/ko/docs/virtual-environments.md @@ -0,0 +1,846 @@ +# 가상 환경 + +Python 프로젝트를 작업할 때는 **가상 환경** (또는 이와 유사한 도구)을 사용하는 것이 좋습니다. 각 프로젝트 마다 설치하는 패키지를 분리하여 관리할 수 있습니다. + +/// info | 정보 + +이미 가상 환경에 대해 잘 알고 있다면, 이 섹션은 건너 뛰어도 괜찮습니다. 🤓 + +/// + +/// tip | 팁 + +**가상 환경(Virtual Environment)** 은 **환경 변수(Environment Variable)** 와 다릅니다. + +**환경 변수**는 시스템에 존재하며, 프로그램이 사용할 수 있는 변수입니다. + +**가상 환경**은 몇몇 파일로 구성된 하나의 디렉터리입니다. + +/// + +/// info | 정보 + +이 페이지에서는 **가상 환경**의 사용 방법과 작동 방식을 설명합니다. + +만약 **모든 것을 관리해주는 도구** (Python 설치까지 포함)를 사용하고 싶다면 uv를 사용해보세요. + +/// + +## 프로젝트 생성 + +먼저, 프로젝트를 위한 디렉터리를 하나 생성합니다. + +보통 사용자 홈 디렉터리 안에 `code`라는 디렉터리를 만들고, 그 안에 프로젝트마다 하나씩 디렉터리를 만들어 관리합니다. + +
+ +```console +// 홈 디렉터리로 이동 +$ cd +// 모든 코드 프로젝트를 위한 디렉터리 생성 +$ mkdir code +// code 디렉터리로 이동 +$ cd code +// 이번 프로젝트를 위한 디렉터리 생성 +$ mkdir awesome-project +// 해당 프로젝트 디렉터리로 이동 +$ cd awesome-project +``` + +
+ +## 가상 환경 생성 + +Python 프로젝트를 **처음 시작할 때**, 가상 환경을 **프로젝트 내부**에 생성합니다. + +/// tip | 팁 + +이 작업은 **프로젝트를 처음 설정할 때 한번만** 해주면 됩니다. 이후 작업할 때 반복할 필요는 없습니다. + +/// + +//// tab | `venv` + +Python 표준 라이브러리에 포함된 venv 모듈을 사용해 가상 환경을 생성할 수 있습니다. + +
+ +```console +$ python -m venv .venv +``` + +
+ +/// details | 명령어 상세 설명 + +* `python`: `python` 프로그램을 실행합니다. +* `-m`: 특정 모듈을 스크립트처럼 실행합니다. 대상 모듈을 바로 뒤에 지정합니다. +* `venv`: Python 표준 라이브러리에 포함된 `venv` 모듈을 실행합니다. +* `.venv`: 가상 환경을 `.venv` 디렉터리에 생성합니다. + +/// + +//// + +//// tab | `uv` + +`uv`가 설치되어 있다면, uv를 통해 가상 환경을 생성할 수 있습니다. + +
+ +```console +$ uv venv +``` + +
+ +/// tip | 팁 + +`uv`는 기본적으로 `.venv` 디렉터리에 가상 환경을 생성합니다. + +별도로 디렉터리 이름을 추가 인자로 넘겨 주면 경로를 지정 할 수 있습니다. + +/// + +//// + +해당 명령어는 `.venv` 디렉터리에 새로운 가상 환경을 생성합니다. + +/// details | `.venv` 또는 다른 이름 + +가상 환경을 다른 디렉터리에 생성할 수도 있지만, 관례적으로 `.venv` 디렉터리 이름을 사용합니다. + +/// + +## 가상 환경 활성화 + +이후 실행하는 Python 명령어와 패키지 설치가 가상 환경을 따르도록, 가상 환경을 활성화하세요. + +/// tip | 팁 + +**터미널을 새로 열고** 프로젝트 작업을 시작할 때는, **항상 이 작업을** 해주세요. + +/// + +//// tab | Linux, macOS + +
+ +```console +$ source .venv/bin/activate +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ .venv\Scripts\Activate.ps1 +``` + +
+ +//// + +//// tab | Windows Bash + +Windows에서 Bash(예: Git Bash)를 사용하는 경우: + +
+ +```console +$ source .venv/Scripts/activate +``` + +
+ +//// + +/// tip | 팁 + +가상 환경에 새로운 패키지를 설치할 때마다, 해당 환경을 다시 활성화하세요. + +이렇게 하면 해당 패키지로 설치된 **터미널(CLI) 프로그램**을 사용할 때, 전역에 설치된 다른 버전이 아니라, 가상 환경 안에 설치된 정확한 버전을 사용합니다. + +/// + +## 가상 환경이 활성화 여부 확인 + +가상 환경이 활성화되었는지 확인합니다. (이전 명령어가 제대로 작동했는지 확인합니다). + +/// tip | 팁 + +이 단계는 **선택 사항**이지만, 모든 것이 예상대로 작동하고 있는지, 그리고 의도한 가상 환경이 활성화 되었는 지 **확인**하는 좋은 방법입니다. + +/// + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +
+ +`python` 위치가 프로젝트 내부(이 예시에서는 `awesome-project`)의 `.venv/bin/python` 경로로 표시된다면 성공입니다. 🎉 + +//// + +//// tab | Windows PowerShell + +
+ +```console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +
+ +`python` 위치가 프로젝트 내부(이 예시에서는 `awesome-project`)의 `.venv\bin\python` 경로로 표시된다면 성공입니다. 🎉 + +//// + +## pip 업그레이드 + +/// tip | 팁 + +`uv`를 사용한다면, `pip` 대신 `uv`로 패키지를 설치하게 되므로 `pip`을 업그레이드할 필요가 없습니다. 😎 + +/// + +`pip`을 사용하여 패키지를 설치하는 경우 (Python 표준 라이브러리에 포함되어 있습니다), **최신 버전으로 업그레이드**하는 것이 좋습니다. + +패키지 설치 중 발생하는 다양하고 특이한 에러들은 `pip` 업그레이드로 쉽게 해결되는 경우가 많습니다. + +/// tip | 팁 + +이 작업은 보통 가상 환경을 생성한 **직후 한 번만** 하면 됩니다. + +/// + +가상 환경이 활성화된 상태인지 확인한 후(앞서 설명한 명령어 사용), 아래 명령어를 실행하세요: + +
+ +```console +$ python -m pip install --upgrade pip + +---> 100% +``` + +
+ +## `.gitignore` 추가하기 + +**Git**을 사용하고 있다면 (사용하는 것이 좋습니다), `.gitignore` 파일을 추가해서 `.venv` 디렉터리 전체를 Git에서 제외하세요. + +/// tip | 팁 + +`uv`를 사용해 가상 환경을 생성했다면, 이미 이 작업이 자동으로 처리되어 있으므로 이 단계는 건너뛰어도 됩니다. 😎 + +/// + +/// tip | 팁 + +이 작업도 마찬가지로, 가상 환경을 생성한 **직후 한 번만** 하면 됩니다. + +/// + +
+ +```console +$ echo "*" > .venv/.gitignore +``` + +
+ +/// details | 명령어 상세 설명 + +* `echo "*"`: 터미널에 `*` 텍스트를 "출력"합니다 (다음 설명에서 조금 바뀝니다) +* `>`: 왼쪽 명령어의 출력 내용을 터미널에 출력하지 않고, 오른쪽에 지정된 파일로 **기록(write)** 하라는 의미입니다. +* `.gitignore`: 출력된 텍스트가 기록될 파일 이름입니다. + +그리고 Git에서 `*`는 "모든 것"을 의미합니다. 따라서 `.venv` 디렉터리 안의 모든 것을 무시하게 됩니다. + +이 명령어는 다음과 같은 내용을 가진 `.gitignore` 파일을 생성합니다: + + +```gitignore +* +``` + +/// + +## 패키지 설치 + +가상 환경을 활성화한 후, 그 안에 필요한 패키지들을 설치할 수 있습니다. + +/// tip | 팁 + +프로젝트에서 필요한 패키지를 설치하거나 업그레이드할 때는 이 작업을 **한 번만** 하면 됩니다. + +만약 특정 패키지의 버전을 업그레이드하거나, 새로운 패키지를 추가할 필요가 생기면 **다시 이 작업을 반복**하면 됩니다. + +/// + +### 패키지 직접 설치 + +급하게 작업하거나, 프로젝트에 필요한 패키지 목록을 따로 파일로 관리하고 싶지 않은 경우, 패키지를 직접 설치할 수도 있습니다. + +/// tip | 팁 + +패키지 이름과 버전 정보를 파일에 정리해두는 것(예: `requirements.txt` 또는 `pyproject.toml`)은 (매우) 좋은 생각입니다. + +/// + +//// tab | `pip` + +
+ +```console +$ pip install "fastapi[standard]" + +---> 100% +``` + +
+ +//// + +//// tab | `uv` + +`uv`를 사용하는 경우: + +
+ +```console +$ uv pip install "fastapi[standard]" +---> 100% +``` + +
+ +//// + +### `requirements.txt`에서 설치 + +`requirements.txt` 파일이 있다면, 그 안에 명시된 패키지들을 한 번에 설치할 수 있습니다. + +//// tab | `pip` + +
+ +```console +$ pip install -r requirements.txt +---> 100% +``` + +
+ +//// + +//// tab | `uv` + +`uv`를 사용하는 경우: + +
+ +```console +$ uv pip install -r requirements.txt +---> 100% +``` + +
+ +//// + +/// details | `requirements.txt` + +다음은 몇 가지 패키지를 포함한 `requirements.txt`의 예시입니다: + +```requirements.txt +fastapi[standard]==0.113.0 +pydantic==2.8.0 +``` + +/// + +## 프로그램 실행 + +가상 환경을 활성화한 후에는 프로그램을 실행할 수 있습니다. 이때 해당 가상 환경에 설치된 Python과 패키지들이 사용됩니다. + +
+ +```console +$ python main.py + +Hello World +``` + +
+ +## 에디터 설정 + +에디터를 사용할 경우, 앞서 만든 가상 환경을 사용하도록 설정하는 것이 좋습니다. (대부분의 에디터는 자동으로 감지하기도 합니다.) +이렇게 하면 자동 완성 기능이나 코드 내 오류 표시 기능을 제대로 사용할 수 있습니다. + +예시: + +* VS Code +* PyCharm + +/// tip | 팁 + +이 설정은 보통 가상 환경을 **처음 만들었을 때 한 번만** 해주면 됩니다. + +/// + +## 가상 환경 비활성화 + +프로젝트 작업이 끝났다면, 가상 환경을 **비활성화**할 수 있습니다. + +
+ +```console +$ deactivate +``` + +
+ +이렇게 하면 이후에 `python` 명령어를 실행했을 때, 가상 환경의 Python이나 그 안에 설치된 패키지들을 사용하지 않게 됩니다. + +## 이제 작업할 준비가 되었습니다 + +이제 프로젝트 작업을 시작할 준비가 완료되었습니다. + + +/// tip | 팁 + +위 내용을 더 깊이 이해하고 싶으신가요? + +그렇다면 계속 읽어 주세요. 👇🤓 + +/// + +## 가상 환경을 왜 사용하는가 + +FastAPI를 사용하려면 먼저 Python을 설치해야 합니다. + +그 후에는 FastAPI와 함께 사용할 **기타 패키지들**을 **설치**해야 합니다. + +패키지를 설치할 때 보통 Python에 기본 포함된 `pip` 명령어(또는 유사한 도구)를 사용합니다. + +하지만 `pip`을 그냥 직접 사용하면, 해당 패키지들은 **전역 Python 환경**(시스템 전체에 설치된 Python)에 설치됩니다. + +### 문제점 + +그렇다면, 전역 Python 환경에 패키지를 설치하면 어떤 문제가 발생할까요? + +어느 시점이 되면, **서로 다른 패키지들**에 의존하는 여러 개의 프로그램을 작성하게 될 것입니다. 그리고 이들 중 일부는 **같은 패키지의 서로 다른 버전**을 필요로 할 수 있습니다. 😱 + +예를 들어, `마법사의 돌(philosophers-stone)` 프로젝트를 만들었다고 가정해봅시다. 이 프로그램은 `해리 포터(harry)`라는 패키지의 `v1` 버전을 **의존**합니다. 따라서 `harry`를 설치해야 합니다. + +```mermaid +flowchart LR + stone(philosophers-stone) -->|requires| harry-1[harry v1] +``` + +그런데 나중에 `아즈카반의 죄수(prisoner-of-azkaban)`이라는 또 다른 프로젝트를 만들게 되었고, 이 프로젝트도 역시 `harry` 패키지를 사용합니다. 그런데 이 프로젝트는 `harry`의 `v3` 버전이 필요합니다. + +```mermaid +flowchart LR + azkaban(prisoner-of-azkaban) --> |requires| harry-3[harry v3] +``` + +하지만 이제 문제가 생깁니다. 로컬 가상 환경 대신에 전역 환경에 패키지를 설치하게 되면, 어떤 버전의 `harry`를 설치할지를 선택해야 하기 때문입니다. + +예를 들어, `마법사의 돌(philosophers-stone)`을 실행하고 싶다면 먼저 `harry` `v1` 버전을 다음과 같이 설치 해야 합니다: + +
+ +```console +$ pip install "harry==1" +``` + +
+ +그러면 결국 전역 Python 환경에는 `harry` `v1`버전이 설치된 상태가 됩니다. + +```mermaid +flowchart LR + subgraph global[global env] + harry-1[harry v1] + end + subgraph stone-project[philosophers-stone project] + stone(philosophers-stone) -->|requires| harry-1 + end +``` + +하지만 이제 `아즈카반의 죄수(prisoner-of-azkaban)`을 실행하고 싶다면, `harry` `v1`버전을 제거하고 `harry` `v3`버전을 설치해야 합니다. (또는 단순히 `v3`버전을 설치하는 것만으로도 기존의 `v1`버전이 자동으로 제거됩니다.) + +
+ +```console +$ pip install "harry==3" +``` + +
+ +그렇게 하면 이제 전역 Python 환경에는 `harry` `v3`버전이 설치된 상태가 됩니다. + +그리고 다시 `마법사의 돌(philosophers-stone)`을 실행하려고 하면, **작동하지** 않을 수 있습니다. 왜냐하면 이 프로그램은 `harry` `v1`버전을 필요로 하기 때문입니다. + +```mermaid +flowchart LR + subgraph global[global env] + harry-1[harry v1] + style harry-1 fill:#ccc,stroke-dasharray: 5 5 + harry-3[harry v3] + end + subgraph stone-project[philosophers-stone project] + stone(philosophers-stone) -.-x|⛔️| harry-1 + end + subgraph azkaban-project[prisoner-of-azkaban project] + azkaban(prisoner-of-azkaban) --> |requires| harry-3 + end +``` + +/// tip | 팁 + +Python 패키지들은 **새 버전**에서 **호환성 문제(breaking changes)**가 발생하지 않도록 최대한 노력하는 것이 일반적입니다. 하지만 그래도 안전하게 작업하려면, 테스트를 실행해보면서 새 버전을 의도적으로 설치하는 것이 좋습니다. + +/// + +이제, 이런 일이 여러분의 **모든 프로젝트**가 사용하는 **수많은 패키지들**에서 동시에 발생한다고 상상해보세요. 이는 매우 관리하기 어려우며, 결국 **서로 호환되지 않는 버전**의 패키지로 프로젝트를 실행하게 될 가능성이 높고, 그로 인해 어떤 문제가 왜 발생하는지 알 수 없게 될 수 있습니다. + +또한 사용하는 운영체제(Linux, Windows, macOS 등)에 따라 Python이 **미리 설치되어 있을 수도** 있습니다. 이런 경우에는 운영체제의 동작에 필요한 특정 버전의 패키지들이 함께 설치되어 있을 수 있습니다. 이 상태에서 전역 Python 환경에 임의의 패키지를 설치하면, 운영체제에 포함된 프로그램 일부가 **깨질 위험**도 있습니다. + +## 패키지들은 어디에 설치되는가 + +Python을 설치하면, 컴퓨터에 여러 디렉터리와 파일들이 생성됩니다. + +이 중 일부 디렉터리는 사용자가 설치한 패키지들을 보관하는 역할을 합니다. + +예를 들어, 아래 명령어를 실행하면: + +
+ +```console +// 지금 실행하지 않아도 됩니다, 그냥 예제일 뿐이에요 🤓 +$ pip install "fastapi[standard]" +---> 100% +``` + +
+ +해당 명령어는 FastAPI 코드를 포함한 압축 파일을 다운로드합니다. 이 파일은 보통 PyPI에서 받아옵니다. + +또한 FastAPI가 의존하는 다른 패키지들도 함께 **다운로드**됩니다. + +그리고 그 모든 파일들을 **압축 해제**한 뒤, 컴퓨터의 특정 디렉터리에 저장합니다. + +기본적으로 이 파일들은 Python이 설치된 디렉터리 안, 즉 **전역 환경**에 내의 디렉터리에 저장됩니다. + +## 가상 환경이란 + +전역 환경에 모든 패키지를 설치하면서 발생하는 문제에 대한 해결책은, 작업하는 **각 프로젝트마다 가상 환경**을 사용하는 것입니다. + +가상 환경은 전역 환경과 매우 유사한 하나의 **디렉터리**이며, 그 안에 해당 프로젝트를 위한 패키지들을 설치할 수 있습니다. + +이렇게 하면 각 프로젝트는 자체적인 가상 환경(`.venv` 디렉터리)을 가지게 되며, 그 안에 해당 프로젝트 전용 패키지들을 보유하게 됩니다. + + +```mermaid +flowchart TB + subgraph stone-project[philosophers-stone project] + stone(philosophers-stone) --->|requires| harry-1 + subgraph venv1[.venv] + harry-1[harry v1] + end + end + subgraph azkaban-project[prisoner-of-azkaban project] + azkaban(prisoner-of-azkaban) --->|requires| harry-3 + subgraph venv2[.venv] + harry-3[harry v3] + end + end + stone-project ~~~ azkaban-project +``` + +## 가상 환경 활성화 의미 + +가상 환경을 활성화한다는 것은, 예를 들어 다음과 같은 명령어를 실행하는 것을 의미합니다: + +//// tab | Linux, macOS + +
+ +```console +$ source .venv/bin/activate +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ .venv\Scripts\Activate.ps1 +``` + +
+ +//// + +//// tab | Windows Bash + +Windows에서 Bash(예: Git Bash)를 사용하는 경우: + +
+ +```console +$ source .venv/Scripts/activate +``` + +
+ +//// + +이 명령어는 이후에 실행될 명령어에서 사용될 [환경 변수](environment-variables.md){.internal-link target=_blank} 몇 개를 생성하거나 수정합니다. + +이 변수들 중 하나가 바로 `PATH` 변수입니다. + +/// tip | 팁 + +`PATH` 환경 변수에 대해 더 알고 싶다면 [환경 변수 문서의 PATH 환경 변수 섹션](environment-variables.md#path-environment-variable){.internal-link target=_blank}을 참고하세요. + +/// + +가상 환경을 활성화하면, 가상 환경의 경로인 `.venv/bin` (Linux와 macOS) 또는 `.venv\Scripts`(Windows)를 `PATH` 환경 변수에 추가됩니다. + +예를 들어, 가상 환경을 활성화하기 전의 `PATH` 변수는 다음과 같았다고 가정해봅시다: + +//// tab | Linux, macOS + +```plaintext +/usr/bin:/bin:/usr/sbin:/sbin +``` + +시스템은 다음 경로들에서 프로그램을 찾게 됩니다: + +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Windows\System32 +``` + +시스템은 다음 경로들에서 프로그램을 찾게 됩니다: + +* `C:\Windows\System32` + +//// + +가상 환경을 활성화한 후에는, `PATH` 변수는 다음과 같은 형태가 됩니다: + +//// tab | Linux, macOS + +```plaintext +/home/user/code/awesome-project/.venv/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +시스템은 가장 먼저 다음 경로에서 프로그램을 찾기 시작합니다: + +```plaintext +/home/user/code/awesome-project/.venv/bin +``` + +그 후에 다른 디렉터리들을 탐색합니다. + +따라서 터미널에 `python`을 입력하면, 시스템은 다음 위치에 있는 Python 프로그램을 찾게 됩니다: + +```plaintext +/home/user/code/awesome-project/.venv/bin/python +``` + +그리고 해당 Python을 사용하게 됩니다. + +//// + +//// tab | Windows + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts;C:\Windows\System32 +``` + +시스템은 가장 먼저 다음 경로에서 프로그램을 찾기 시작합니다: + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts +``` + +그 후에 다른 디렉터리들을 탐색합니다. + +따라서 터미널에 `python`을 입력하면, 시스템은 다음 경로에 있는 Python 프로그램을 찾게 됩니다: + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +그리고 해당 Python을 사용하게 됩니다. + +//// + +중요한 세부 사항 중 하나는, 가상 환경의 경로가 `PATH` 변수의 가장 **앞**에 추가된다는 점입니다. 시스템은 사용 가능한 다른 Python들보다 **먼저** 이 경로를 찾습니다. 그래서 터미널에서 `python`을 실행하면, 전역 환경의 Python이 아닌 **가상 환경에 있는** Python이 사용됩니다. (예: 전역 환경에 설치된 `python`이 있더라도 그보다 우선합니다.) + +가상 환경을 활성화하면 이 외에도 몇 가지 다른 것들이 변경되지만, 이는 그중에서도 가장 중요한 변화 중 하나입니다. + +## 가상 환경 확인하기 + +가상 환경이 활성화 되었는지 확인하려면, 아래 명령어를 사용할 수 있습니다: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +
+ +//// + +즉, 현재 사용되는 `python` 프로그램은 **가상 환경 내부에 있는 것**입니다. + +Linux와 macOS에서는 `which`, Windows PowerShell에서는 `Get-Command` 명령어를 사용합니다. + +이 명령어는 `PATH` 환경 변수에 지정된 경로들을 **순서대로 탐색**하면서 `python`이라는 이름의 프로그램을 찾습니다. +찾는 즉시, 해당 프로그램의 **경로를 출력**합니다. + +중요한 점은 터미널에서 `python`을 실행했을 때, 실제로 실행되는 "`python`"이 어떤 것인지 정확히 알 수 있다는 것입니다. + +따라서 현재 올바른 가상 환경에 있는지 확인할 수 있습니다. + +/// tip | 팁 + +하나의 가상 환경을 활성화한 뒤, 해당 Python을 가진 상태에서 **또 다른 프로젝트**로 이동하는 것은 흔히 발생합니다. + +하지만 이때 이전 프로젝트의 가상 환경에 있는 **잘못된 Python 실행 파일**을 사용하게 되어 새 프로젝트가 **정상 작동하지 않을 수 있습니다.** + +그래서 현재 어떤 `python`이 사용되고 있는지 확인할 수 있는 능력은 매우 유용합니다. 🤓 + +/// + +## 가상 환경을 비활성화하는 이유 + +예를 들어 `마법사의 돌(philosophers-stone)`이라는 프로젝트에서 작업 중이라고 해보겠습니다. 이때 해당 **가상 환경을 활성화**하고, 필요한 패키지를 설치하며 작업을 진행합니다. + +그런데 이제는 **다른 프로젝트**인 `아즈카반의 죄수(prisoner-of-azkaban)`을 작업하고 싶어졌습니다. + +그래서 그 프로젝트 디렉터리로 이동합니다: + +
+ +```console +$ cd ~/code/prisoner-of-azkaban +``` + +
+ +만약 `마법사의 돌(philosophers-stone)`의 가상 환경을 비활성화하지 않았다면, 터미널에서 `python`을 실행할 때 여전히 `마법사의 돌(philosophers-stone)` 가상 환경의 Python을 사용하게 됩니다. + +
+ +```console +$ cd ~/code/prisoner-of-azkaban + +$ python main.py + +// sirius를 임포트하는 데 실패했습니다. 설치되어 있지 않아요 😱 +Traceback (most recent call last): + File "main.py", line 1, in + import sirius +``` + +
+ +하지만 `마법사의 돌(philosophers-stone)`의 가상 환경을 비활성화한 다음, `아즈카반의 죄수(prisoner-of-azkaban)` 프로젝트의 가상 환경을 활성화하면, 이제 `python` 명령어는 `아즈카반의 죄수(prisoner-of-azkaban)` 가상 환경의 Python을 사용하게 됩니다. + +
+ +```console +$ cd ~/code/prisoner-of-azkaban + +// 이전 디렉터리에 있을 필요 없이, 어디서든 가상 환경을 비활성화할 수 있습니다. 다른 프로젝트 디렉터리로 이동한 후에도 괜찮아요 😎 +$ deactivate + +// prisoner-of-azkaban/.venv 가상 환경을 활성화합니다 🚀 +$ source .venv/bin/activate + +// 이제 python을 실행하면, 이 가상 환경에 설치된 sirius 패키지를 찾게 됩니다 ✨ +$ python main.py + +못된 짓을 꾸미고 있음을 엄숙히 맹세합니다.🧙 +ImportError는 이제 없습니다. 🐺 +``` + +
+ +## 대안들 + +이 문서는 여러분이 Python 프로젝트를 시작하고, **그 내부에서** 어떻게 돌아가는지 알려주는 간단한 가이드입니다. + +가상 환경, 패키지 의존성(Requirements), 프로젝트를 관리하는 방법에는 이 외에도 다양한 **대안**들이 존재합니다. + +만약 준비가 되었다면, **프로젝트 전체**, 패키지 의존성, 가상 환경 등을 통합적으로 **관리**할 수 있는 도구를 써보는 것도 좋습니다. 그럴 때 추천하는 도구가 바로 uv입니다. + +`uv`는 다양한 기능을 지원합니다: + +* 다양한 버전의 **Python 설치** +* 각 프로젝트 별 **가상 환경 관리** +* **패키지 설치** +* 프로젝트의 **의존성과 버전** 관리 +* 설치된 패키지들과 그 버전을 **정확히 고정(lock)**해서,개발 환경과 운영 환경이 완전히 동일하게 작동할 수 있도록 보장 +* 이 외에도 다양한 기능을 지원 + +## 결론 + +여기까지 모두 읽고 이해했다면, 이제 많은 개발자들보다 가상 환경을 **훨씬 더 깊이 있게 이해**하게 되셨습니다. 🤓 + +이런 세부적인 내용을 알고 있으면, 언젠가 복잡해 보이는 문제를 디버깅할 때 분명히 큰 도움이 될 것입니다. 이제는 **이 모든 것들이 내부에서 어떻게 작동하는지** 알고 있기 때문입니다. 😎 diff --git a/docs/nl/docs/index.md b/docs/nl/docs/index.md index d88bb7771..32b20e31e 100644 --- a/docs/nl/docs/index.md +++ b/docs/nl/docs/index.md @@ -12,7 +12,7 @@

- Test + Test Coverage diff --git a/docs/pl/docs/index.md b/docs/pl/docs/index.md index 9a96c6553..0e13d2631 100644 --- a/docs/pl/docs/index.md +++ b/docs/pl/docs/index.md @@ -11,15 +11,18 @@ FastAPI to szybki, prosty w nauce i gotowy do użycia w produkcji framework

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

--- diff --git a/docs/pt/docs/deployment/concepts.md b/docs/pt/docs/deployment/concepts.md index 8cf70d0b4..014ca3797 100644 --- a/docs/pt/docs/deployment/concepts.md +++ b/docs/pt/docs/deployment/concepts.md @@ -216,7 +216,7 @@ Este Processo de Gerenciador provavelmente seria o que escutaria na **porta** no Esses processos de trabalho seriam aqueles que executariam seu aplicativo, eles executariam os cálculos principais para receber uma **solicitação** e retornar uma **resposta**, e carregariam qualquer coisa que você colocasse em variáveis ​​na RAM. - + E, claro, a mesma máquina provavelmente teria **outros processos** em execução, além do seu aplicativo. diff --git a/docs/pt/docs/deployment/https.md b/docs/pt/docs/deployment/https.md index 9ad419934..904d04eaa 100644 --- a/docs/pt/docs/deployment/https.md +++ b/docs/pt/docs/deployment/https.md @@ -85,7 +85,7 @@ Primeiro, o navegador iria verificar com os **servidores DNS** qual o **IP do do Os servidores DNS iriam informar o navegador para utilizar algum **endereço IP** específico. Esse seria o endereço IP público em uso no seu servidor, que você configurou nos servidores DNS. - + ### Início do Handshake TLS @@ -93,7 +93,7 @@ O navegador então irá comunicar-se com esse endereço IP na **porta 443** (a p A primeira parte dessa comunicação é apenas para estabelecer a conexão entre o cliente e o servidor e para decidir as chaves criptográficas a serem utilizadas, etc. - + Esse interação entre o cliente e o servidor para estabelecer uma conexão TLS é chamada de **Handshake TLS**. @@ -111,7 +111,7 @@ Utilizando a **extensão SNI** discutida acima, o Proxy de Terminação TLS iria Nesse caso, ele usaria o certificado para `someapp.example.com`. - + O cliente já **confia** na entidade que gerou o certificado TLS (nesse caso, o Let's Encrypt, mas veremos sobre isso mais tarde), então ele pode **verificar** que o certificado é válido. @@ -133,19 +133,19 @@ Agora que o cliente e servidor (especialmente o navegador e o Proxy de Terminaç Então, o cliente envia uma **solicitação HTTPS**. Que é apenas uma solicitação HTTP sobre uma conexão TLS encriptada. - + ### Desencriptando a Solicitação O Proxy de Terminação TLS então usaria a encriptação combinada para **desencriptar a solicitação**, e transmitiria a **solicitação básica (desencriptada)** para o processo executando a aplicação (por exemplo, um processo com Uvicorn executando a aplicação FastAPI). - + ### Resposta HTTP A aplicação processaria a solicitação e retornaria uma **resposta HTTP básica (não encriptada)** para o Proxy de Terminação TLS. - + ### Resposta HTTPS @@ -153,7 +153,7 @@ O Proxy de Terminação TLS iria **encriptar a resposta** utilizando a criptogra No próximo passo, o navegador verifica que a resposta é válida e encriptada com a chave criptográfica correta, etc. E depois **desencripta a resposta** e a processa. - + O cliente (navegador) saberá que a resposta vem do servidor correto por que ela usa a criptografia que foi combinada entre eles usando o **certificado HTTPS** anterior. @@ -163,7 +163,7 @@ Podem existir **múltiplas aplicações** em execução no mesmo servidor (ou se Apenas um processo pode estar vinculado a um IP e porta (o Proxy de Terminação TLS, por exemplo), mas outras aplicações/processos também podem estar em execução no(s) servidor(es), desde que não tentem usar a mesma **combinação de IP público e porta**. - + Dessa forma, o Proxy de Terminação TLS pode gerenciar o HTTPS e os certificados de **múltiplos domínios**, para múltiplas aplicações, e então transmitir as requisições para a aplicação correta em cada caso. @@ -173,7 +173,7 @@ Em algum momento futuro, cada certificado irá **expirar** (aproximadamente 3 me E então, haverá outro programa (em alguns casos pode ser o próprio Proxy de Terminação TLS) que irá interagir com o Let's Encrypt e renovar o(s) certificado(s). - + Os **certificados TLS** são **associados com um nome de domínio**, e não a um endereço IP. diff --git a/docs/pt/docs/how-to/custom-docs-ui-assets.md b/docs/pt/docs/how-to/custom-docs-ui-assets.md index 3adc7529e..b7de6c8bd 100644 --- a/docs/pt/docs/how-to/custom-docs-ui-assets.md +++ b/docs/pt/docs/how-to/custom-docs-ui-assets.md @@ -98,7 +98,7 @@ Você provavelmente pode clicar com o botão direito em cada link e selecionar u E o **ReDoc** usa os arquivos: -* `redoc.standalone.js` +* `redoc.standalone.js` Depois disso, sua estrutura de arquivos deve se parecer com: @@ -129,14 +129,8 @@ Você deverá ver um arquivo JavaScript muito longo para o **ReDoc**. Esse arquivo pode começar com algo como: ```JavaScript -/*! - * ReDoc - OpenAPI/Swagger-generated API Reference Documentation - * ------------------------------------------------------------- - * Version: "2.0.0-rc.18" - * Repo: https://github.com/Redocly/redoc - */ -!function(e,t){"object"==typeof exports&&"object"==typeof m - +/*! For license information please see redoc.standalone.js.LICENSE.txt */ +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("null")): ... ``` diff --git a/docs/pt/docs/index.md b/docs/pt/docs/index.md index 138048f06..9f08d5224 100644 --- a/docs/pt/docs/index.md +++ b/docs/pt/docs/index.md @@ -12,7 +12,7 @@

- Test + Test Coverage diff --git a/docs/pt/docs/tutorial/bigger-applications.md b/docs/pt/docs/tutorial/bigger-applications.md index a094005fd..b621f3c72 100644 --- a/docs/pt/docs/tutorial/bigger-applications.md +++ b/docs/pt/docs/tutorial/bigger-applications.md @@ -52,7 +52,7 @@ from app.routers import items * Há também um subdiretório `app/internal/` com outro arquivo `__init__.py`, então ele é outro "subpacote Python":`app.internal`. * E o arquivo `app/internal/admin.py` é outro submódulo: `app.internal.admin`. - + A mesma estrutura de arquivos com comentários: @@ -270,7 +270,7 @@ Mas esse arquivo não existe, nossas dependências estão em um arquivo em `app/ Lembre-se de como nossa estrutura app/file se parece: - + --- diff --git a/docs/ru/docs/advanced/response-cookies.md b/docs/ru/docs/advanced/response-cookies.md new file mode 100644 index 000000000..e04ff577c --- /dev/null +++ b/docs/ru/docs/advanced/response-cookies.md @@ -0,0 +1,48 @@ + +# Cookies в ответе + +## Использование параметра `Response` + +Вы можете объявить параметр типа `Response` в вашей функции эндпоинта. + +Затем установить cookies в этом временном объекте ответа. + +{* ../../docs_src/response_cookies/tutorial002.py hl[1, 8:9] *} + +После этого можно вернуть любой объект, как и раньше (например, `dict`, объект модели базы данных и так далее). + +Если вы указали `response_model`, он всё равно будет использоваться для фильтрации и преобразования возвращаемого объекта. + +**FastAPI** извлечет cookies (а также заголовки и коды состояния) из временного ответа и включит их в окончательный ответ, содержащий ваше возвращаемое значение, отфильтрованное через `response_model`. + +Вы также можете объявить параметр типа Response в зависимостях и устанавливать cookies (и заголовки) там. + +## Возвращение `Response` напрямую + +Вы также можете установить cookies, если возвращаете `Response` напрямую в вашем коде. + +Для этого создайте объект `Response`, как описано в разделе [Возвращение ответа напрямую](response-directly.md){.target=_blank}. + +Затем установите cookies и верните этот объект: + +{* ../../docs_src/response_cookies/tutorial001.py hl[10:12] *} + +/// tip | Примечание +Имейте в виду, что если вы возвращаете ответ напрямую, вместо использования параметра `Response`, **FastAPI** отправит его без дополнительной обработки. + +Убедитесь, что ваши данные имеют корректный тип. Например, они должны быть совместимы с JSON, если вы используете `JSONResponse`. + +Также убедитесь, что вы не отправляете данные, которые должны были быть отфильтрованы через `response_model`. +/// + +### Дополнительная информация + +/// note | Технические детали +Вы также можете использовать `from starlette.responses import Response` или `from starlette.responses import JSONResponse`. + +**FastAPI** предоставляет `fastapi.responses`, которые являются теми же объектами, что и `starlette.responses`, просто для удобства. Однако большинство доступных типов ответов поступает непосредственно из **Starlette**. + +Для установки заголовков и cookies `Response` используется часто, поэтому **FastAPI** также предоставляет его через `fastapi.responses`. +/// + +Чтобы увидеть все доступные параметры и настройки, ознакомьтесь с документацией Starlette. diff --git a/docs/ru/docs/deployment/concepts.md b/docs/ru/docs/deployment/concepts.md index 7cdc29526..acfa1f4fe 100644 --- a/docs/ru/docs/deployment/concepts.md +++ b/docs/ru/docs/deployment/concepts.md @@ -216,7 +216,7 @@ Каждый из этих процессов будет запускать ваше приложение для обработки полученного **запроса** и возвращения вычисленного **ответа** и они будут использовать оперативную память. - + Безусловно, на этом же сервере будут работать и **другие процессы**, которые не относятся к вашему приложению. diff --git a/docs/ru/docs/deployment/https.md b/docs/ru/docs/deployment/https.md index 85c4cce60..d8877a9a1 100644 --- a/docs/ru/docs/deployment/https.md +++ b/docs/ru/docs/deployment/https.md @@ -92,7 +92,7 @@ DNS-сервера присылают браузеру определённый **IP-адрес**, тот самый публичный IP-адрес вашего сервера, который вы указали в ресурсной "записи А" при настройке. - + ### Рукопожатие TLS @@ -100,7 +100,7 @@ DNS-сервера присылают браузеру определённый Первым шагом будет установление соединения между клиентом (браузером) и сервером и выбор криптографического ключа (для шифрования). - + Эта часть клиент-серверного взаимодействия устанавливает TLS-соединение и называется **TLS-рукопожатием**. @@ -118,7 +118,7 @@ DNS-сервера присылают браузеру определённый То есть будет выбран сертификат для домена `someapp.example.com`. - + Клиент уже **доверяет** тому, кто выдал этот TLS-сертификат (в нашем случае - Let's Encrypt, но мы ещё обсудим это), потому может **проверить**, действителен ли полученный от сервера сертификат. @@ -140,19 +140,19 @@ DNS-сервера присылают браузеру определённый Так клиент отправляет **HTTPS-запрос**. То есть обычный HTTP-запрос, но через зашифрованное TLS-содинение. - + ### Расшифровка запроса Прокси-сервер, используя согласованный с клиентом ключ, расшифрует полученный **зашифрованный запрос** и передаст **обычный (незашифрованный) HTTP-запрос** процессу, запускающему приложение (например, процессу Uvicorn запускающему приложение FastAPI). - + ### HTTP-ответ Приложение обработает запрос и вернёт **обычный (незашифрованный) HTTP-ответ** прокси-серверу. - + ### HTTPS-ответ @@ -160,7 +160,7 @@ DNS-сервера присылают браузеру определённый Наконец, браузер проверит ответ, в том числе, что тот зашифрован с нужным ключом, **расшифрует его** и обработает. - + Клиент (браузер) знает, что ответ пришёл от правильного сервера, так как использует методы шифрования, согласованные ими раннее через **HTTPS-сертификат**. @@ -171,7 +171,7 @@ DNS-сервера присылают браузеру определённый Напомню, что только один процесс (например, прокси-сервер) может прослушивать определённый порт определённого IP-адреса. Но другие процессы и приложения тоже могут работать на этом же сервере (серверах), если они не пытаются использовать уже занятую **комбинацию IP-адреса и порта** (сокет). - + Таким образом, сервер завершения TLS может обрабатывать HTTPS-запросы и использовать сертификаты для **множества доменов** или приложений и передавать запросы правильным адресатам (другим приложениям). @@ -181,7 +181,7 @@ DNS-сервера присылают браузеру определённый Когда это произойдёт, можно запустить другую программу, которая подключится к Let's Encrypt и обновит сертификат(ы). Существуют прокси-серверы, которые могут сделать это действие самостоятельно. - + **TLS-сертификаты** не привязаны к IP-адресу, но **связаны с именем домена**. diff --git a/docs/ru/docs/index.md b/docs/ru/docs/index.md index 5ebe1494b..a9546cf1e 100644 --- a/docs/ru/docs/index.md +++ b/docs/ru/docs/index.md @@ -12,10 +12,10 @@

- Test + Test - - Coverage + + Coverage Package version diff --git a/docs/ru/docs/tutorial/bigger-applications.md b/docs/ru/docs/tutorial/bigger-applications.md index 7c3dc288f..8b9080d39 100644 --- a/docs/ru/docs/tutorial/bigger-applications.md +++ b/docs/ru/docs/tutorial/bigger-applications.md @@ -52,7 +52,7 @@ from app.routers import items * Подкаталог `app/internal/`, содержащий файл `__init__.py`, является ещё одним суб-пакетом: `app.internal`. * А файл `app/internal/admin.py` является ещё одним суб-модулем: `app.internal.admin`. - + Та же самая файловая структура приложения, но с комментариями: @@ -269,7 +269,7 @@ from .dependencies import get_token_header Вспомните, как выглядит файловая структура нашего приложения: - + --- diff --git a/docs/ru/docs/tutorial/cookie-param-models.md b/docs/ru/docs/tutorial/cookie-param-models.md new file mode 100644 index 000000000..3a57443bb --- /dev/null +++ b/docs/ru/docs/tutorial/cookie-param-models.md @@ -0,0 +1,76 @@ +# Модели параметров cookie + +Если у вас есть группа **cookies**, которые связаны между собой, вы можете создать **Pydantic-модель** для их объявления. 🍪 + +Это позволит вам **переиспользовать модель** в **разных местах**, а также объявить проверки и метаданные сразу для всех параметров. 😎 + +/// note | Заметка + +Этот функционал доступен с версии `0.115.0`. 🤓 + +/// + +/// tip | Совет + +Такой же подход применяется для `Query`, `Cookie`, и `Header`. 😎 + +/// + +## Pydantic-модель для cookies + +Объявите параметры **cookie**, которые вам нужны, в **Pydantic-модели**, а затем объявите параметр как `Cookie`: + +{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *} + +**FastAPI** **извлечёт** данные для **каждого поля** из **cookies**, полученных в запросе, и выдаст вам объявленную Pydantic-модель. + +## Проверка сгенерированной документации + +Вы можете посмотреть объявленные cookies в графическом интерфейсе Документации по пути `/docs`: + +

+ +
+ +/// info | Дополнительная информация + +Имейте в виду, что, поскольку **браузеры обрабатывают cookies** особым образом и под капотом, они **не** позволят **JavaScript** легко получить доступ к ним. + +Если вы перейдёте к **графическому интерфейсу документации API** по пути `/docs`, то сможете увидеть **документацию** по cookies для ваших *операций путей*. + +Но даже если вы **заполните данные** и нажмёте "Execute", поскольку графический интерфейс Документации работает с **JavaScript**, cookies не будут отправлены, и вы увидите сообщение об **ошибке** как будто не указывали никаких значений. + +/// + +## Запрет дополнительных cookies + +В некоторых случаях (не особо часто встречающихся) вам может понадобиться **ограничить** cookies, которые вы хотите получать. + +Теперь ваш API сам решает, принимать ли cookies. 🤪🍪 + +Вы можете сконфигурировать Pydantic-модель так, чтобы запретить (`forbid`) любые дополнительные (`extra`) поля: + +{* ../../docs_src/cookie_param_models/tutorial002_an_py39.py hl[10] *} + +Если клиент попробует отправить **дополнительные cookies**, то в ответ он получит **ошибку**. + +Бедные баннеры cookies, они всеми силами пытаются получить ваше согласие — и всё ради того, чтобы API его отклонил. 🍪 + +Например, если клиент попытается отправить cookie `santa_tracker` со значением `good-list-please`, то в ответ он получит **ошибку**, сообщающую ему, что cookie `santa_tracker` не разрешён: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["cookie", "santa_tracker"], + "msg": "Extra inputs are not permitted", + "input": "good-list-please" + } + ] +} +``` + +## Заключение + +Вы можете использовать **Pydantic-модели** для объявления **cookies** в **FastAPI**. 😎 diff --git a/docs/ru/docs/tutorial/header-param-models.md b/docs/ru/docs/tutorial/header-param-models.md new file mode 100644 index 000000000..4f54e3e15 --- /dev/null +++ b/docs/ru/docs/tutorial/header-param-models.md @@ -0,0 +1,72 @@ +# Модели Header-параметров + +Если у вас есть группа связанных **header-параметров**, то вы можете объединить их в одну **Pydantic-модель**. + +Это позволит вам **переиспользовать модель** в **разных местах**, а также задать валидацию и метаданные сразу для всех параметров. 😎 + +/// note | Заметка + +Этот функционал доступен в FastAPI начиная с версии `0.115.0`. 🤓 + +/// + +## Header-параметры в виде Pydantic-модели + +Объявите нужные **header-параметры** в **Pydantic-модели** и затем аннотируйте параметр как `Header`: + +{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *} + +**FastAPI** **извлечёт** данные для **каждого поля** из **заголовков** запроса и выдаст заданную вами Pydantic-модель. + +## Проверьте документацию + +Вы можете посмотреть нужные header-параметры в графическом интерфейсе сгенерированной документации по пути `/docs`: + +
+ +
+ +## Как запретить дополнительные заголовки + +В некоторых случаях (не особо часто встречающихся) вам может понадобиться **ограничить** заголовки, которые вы хотите получать. + +Вы можете использовать возможности конфигурации Pydantic-модели для того, чтобы запретить (`forbid`) любые дополнительные (`extra`) поля: + +{* ../../docs_src/header_param_models/tutorial002_an_py310.py hl[10] *} + +Если клиент попробует отправить **дополнительные заголовки**, то в ответ он получит **ошибку**. + +Например, если клиент попытается отправить заголовок `tool` со значением `plumbus`, то в ответ он получит ошибку, сообщающую ему, что header-параметр `tool` не разрешен: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["header", "tool"], + "msg": "Extra inputs are not permitted", + "input": "plumbus", + } + ] +} +``` + +## Как отключить автоматическое преобразование подчеркиваний + +Как и в случае с обычными заголовками, если у вас в именах параметров имеются символы подчеркивания, они **автоматически преобразовываются в дефис**. + +Например, если в коде есть header-параметр `save_data`, то ожидаемый HTTP-заголовок будет `save-data` и именно так он будет отображаться в документации. + +Если по каким-то причинам вам нужно отключить данное автоматическое преобразование, это можно сделать и для Pydantic-моделей для header-параметров. + +{* ../../docs_src/header_param_models/tutorial003_an_py310.py hl[19] *} + +/// warning | Внимание + +Перед тем как устанавливать для параметра `convert_underscores` значение `False`, имейте в виду, что некоторые HTTP-прокси и серверы не разрешают использовать заголовки с символами подчеркивания. + +/// + +## Резюме + +Вы можете использовать **Pydantic-модели** для объявления **header-параметров** в **FastAPI**. 😎 diff --git a/docs/ru/docs/tutorial/middleware.md b/docs/ru/docs/tutorial/middleware.md new file mode 100644 index 000000000..845e881e1 --- /dev/null +++ b/docs/ru/docs/tutorial/middleware.md @@ -0,0 +1,74 @@ +# Middleware (Промежуточный слой) + +Вы можете добавить промежуточный слой (middleware) в **FastAPI** приложение. + +"Middleware" это функция, которая выполняется с каждым запросом до его обработки какой-либо конкретной *операцией пути*. +А также с каждым ответом перед его возвращением. + + +* Она принимает каждый поступающий **запрос**. +* Может что-то сделать с этим **запросом** или выполнить любой нужный код. +* Затем передает **запрос** для последующей обработки (какой-либо *операцией пути*). +* Получает **ответ** (от *операции пути*). +* Может что-то сделать с этим **ответом** или выполнить любой нужный код. +* И возвращает **ответ**. + +/// note | Технические детали + +Если у вас есть зависимости с `yield`, то код выхода (код после `yield`) будет выполняться *после* middleware. + +Если у вас имеются некие фоновые задачи (см. документацию), то они будут запущены после middleware. + +/// + +## Создание middleware + +Для создания middleware используйте декоратор `@app.middleware("http")`. + +Функция middleware получает: + +* `request` (объект запроса). +* Функцию `call_next`, которая получает `request` в качестве параметра. + * Эта функция передаёт `request` соответствующей *операции пути*. + * Затем она возвращает ответ `response`, сгенерированный *операцией пути*. +* Также имеется возможность видоизменить `response`, перед тем как его вернуть. + +{* ../../docs_src/middleware/tutorial001.py hl[8:9,11,14] *} + +/// tip | Примечание + +Имейте в виду, что можно добавлять свои собственные заголовки
при помощи префикса 'X-'. + +Если же вы хотите добавить собственные заголовки, которые клиент сможет увидеть в браузере, то вам потребуется добавить их в настройки CORS ([CORS (Cross-Origin Resource Sharing)](cors.md){.internal-link target=_blank}), используя параметр `expose_headers`, см. документацию Starlette's CORS docs. + +/// + +/// note | Технические детали + +Вы также можете использовать `from starlette.requests import Request`. + +**FastAPI** предоставляет такой доступ для удобства разработчиков. Но, на самом деле, это `Request` из Starlette. + +/// + +### До и после `response` + +Вы можете добавить код, использующий `request` до передачи его какой-либо *операции пути*. + +А также после формирования `response`, до того, как вы его вернёте. + +Например, вы можете добавить собственный заголовок `X-Process-Time`, содержащий время в секундах, необходимое для обработки запроса и генерации ответа: + +{* ../../docs_src/middleware/tutorial001.py hl[10,12:13] *} + +/// tip | Примечание + +Мы используем `time.perf_counter()` вместо `time.time()` для обеспечения большей точности наших примеров. 🤓 + +/// + +## Другие middleware + +О других middleware вы можете узнать больше в разделе [Advanced User Guide: Advanced Middleware](../advanced/middleware.md){.internal-link target=_blank}. + +В следующем разделе вы можете прочитать, как настроить CORS с помощью middleware. diff --git a/docs/ru/docs/tutorial/query-params-str-validations.md b/docs/ru/docs/tutorial/query-params-str-validations.md index 32a98ff22..13b7015db 100644 --- a/docs/ru/docs/tutorial/query-params-str-validations.md +++ b/docs/ru/docs/tutorial/query-params-str-validations.md @@ -291,22 +291,6 @@ q: Union[str, None] = Query(default=None, min_length=3) {* ../../docs_src/query_params_str_validations/tutorial006_an_py39.py hl[9] *} -### Обязательный параметр с Ellipsis (`...`) - -Альтернативный способ указать обязательность параметра запроса - это указать параметр `default` через многоточие `...`: - -{* ../../docs_src/query_params_str_validations/tutorial006b_an_py39.py hl[9] *} - -/// info | Дополнительная информация - -Если вы ранее не сталкивались с `...`: это специальное значение, часть языка Python и называется "Ellipsis". - -Используется в Pydantic и FastAPI для определения, что значение требуется обязательно. - -/// - -Таким образом, **FastAPI** определяет, что параметр является обязательным. - ### Обязательный параметр с `None` Вы можете определить, что параметр может принимать `None`, но всё ещё является обязательным. Это может потребоваться для того, чтобы пользователи явно указали параметр, даже если его значение будет `None`. @@ -321,18 +305,6 @@ Pydantic, мощь которого используется в FastAPI для /// -### Использование Pydantic's `Required` вместо Ellipsis (`...`) - -Если вас смущает `...`, вы можете использовать `Required` из Pydantic: - -{* ../../docs_src/query_params_str_validations/tutorial006d_an_py39.py hl[4,10] *} - -/// tip | Подсказка - -Запомните, когда вам необходимо объявить query-параметр обязательным, вы можете просто не указывать параметр `default`. Таким образом, вам редко придётся использовать `...` или `Required`. - -/// - ## Множество значений для query-параметра Для query-параметра `Query` можно указать, что он принимает список значений (множество значений). diff --git a/docs/ru/docs/tutorial/request-form-models.md b/docs/ru/docs/tutorial/request-form-models.md new file mode 100644 index 000000000..1034ed27f --- /dev/null +++ b/docs/ru/docs/tutorial/request-form-models.md @@ -0,0 +1,78 @@ +# Модели форм + +Вы можете использовать **Pydantic-модели** для объявления **полей форм** в FastAPI. + +/// info | Дополнительная информация + +Чтобы использовать формы, сначала установите `python-multipart`. + +Убедитесь, что вы создали и активировали [виртуальное окружение](../virtual-environments.md){.internal-link target=_blank}, а затем установите пакет, например: + +```console +$ pip install python-multipart +``` + +/// + +/// note | Заметка + +Этот функционал доступен с версии `0.113.0`. 🤓 + +/// + +## Pydantic-модель для формы + +Вам просто нужно объявить **Pydantic-модель** с полями, которые вы хотите получить как **поля формы**, а затем объявить параметр как `Form`: + +{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *} + +**FastAPI** **извлечёт** данные для **каждого поля** из **данных формы** в запросе и выдаст вам объявленную Pydantic-модель. + +## Проверка сгенерированной документации + +Вы можете посмотреть поля формы в графическом интерфейсе Документации по пути `/docs`: + +
+ +
+ +## Запрет дополнительных полей формы + +В некоторых случаях (не особо часто встречающихся) вам может понадобиться **ограничить** поля формы только теми, которые объявлены в Pydantic-модели. И **запретить** любые **дополнительные** поля. + +/// note | Заметка + +Этот функционал доступен с версии `0.114.0`. 🤓 + +/// + +Вы можете сконфигурировать Pydantic-модель так, чтобы запретить (`forbid`) все дополнительные (`extra`) поля: + +{* ../../docs_src/request_form_models/tutorial002_an_py39.py hl[12] *} + +Если клиент попробует отправить дополнительные данные, то в ответ он получит **ошибку**. + +Например, если клиент попытается отправить поля формы: + +* `username`: `Rick` +* `password`: `Portal Gun` +* `extra`: `Mr. Poopybutthole` + +То в ответ он получит **ошибку**, сообщающую ему, что поле `extra` не разрешено: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["body", "extra"], + "msg": "Extra inputs are not permitted", + "input": "Mr. Poopybutthole" + } + ] +} +``` + +## Заключение + +Вы можете использовать Pydantic-модели для объявления полей форм в FastAPI. 😎 diff --git a/docs/tr/docs/index.md b/docs/tr/docs/index.md index 7ecaf1ba3..f666e2d06 100644 --- a/docs/tr/docs/index.md +++ b/docs/tr/docs/index.md @@ -12,7 +12,7 @@

- Test + Test Coverage diff --git a/docs/uk/docs/index.md b/docs/uk/docs/index.md index 012bac2e2..b573ee259 100644 --- a/docs/uk/docs/index.md +++ b/docs/uk/docs/index.md @@ -6,7 +6,7 @@

- Test + Test Coverage diff --git a/docs/uk/docs/tutorial/background-tasks.md b/docs/uk/docs/tutorial/background-tasks.md new file mode 100644 index 000000000..912ba8c2a --- /dev/null +++ b/docs/uk/docs/tutorial/background-tasks.md @@ -0,0 +1,85 @@ +# Фонові задачі + +Ви можете створювати фонові задачі, які будуть виконуватися *після* повернення відповіді. + +Це корисно для операцій, які потрібно виконати після обробки запиту, але клієнту не обов’язково чекати завершення цієї операції перед отриманням відповіді. + +Приклади використання: + +* Надсилання email-сповіщень після виконання певної дії: + * Підключення до поштового сервера та надсилання листа може займати кілька секунд. Ви можете відразу повернути відповідь, а email відправити у фоні. +* Обробка даних: + * Наприклад, якщо отримано файл, який потрібно обробити довготривалим процесом, можна повернути відповідь "Accepted" ("Прийнято", HTTP 202) і виконати обробку файлу у фоні. + +## Використання `BackgroundTasks` + +Спочатку імпортуйте `BackgroundTasks` і додайте його як параметр у Вашу *функцію операції шляху* (path operation function) до `BackgroundTasks`: + +{* ../../docs_src/background_tasks/tutorial001.py hl[1,13] *} + +**FastAPI** автоматично створить об'єкт `BackgroundTasks` і передасть його у цей параметр. + + +## Створення функції задачі + +Створіть функцію, яка буде виконувати фонову задачу. + +Це звичайна функція, яка може отримувати параметри. + +Вона може бути асинхронною `async def` або звичайною `def` функцією – **FastAPI** обробить її правильно. + +У нашому випадку функція записує у файл (імітуючи надсилання email). + +І оскільки операція запису не використовує `async` та `await`, ми визначаємо функцію як звичайну `def`: + +{* ../../docs_src/background_tasks/tutorial001.py hl[6:9] *} + +## Додавання фонової задачі + +Усередині Вашої *функції обробки шляху*, передайте функцію задачі в об'єкт *background tasks*, використовуючи метод `.add_task()`: + +{* ../../docs_src/background_tasks/tutorial001.py hl[14] *} + +`.add_task()` приймає аргументи: + +* Функція задача, яка буде виконуватися у фоновому режимі (`write_notification`). Зверніть увагу, що передається обʼєкт без дужок. +* Будь-яка послідовність аргументів, які потрібно передати у функцію завдання у відповідному порядку (`email`). +* Будь-які іменовані аргументи, які потрібно передати у функцію задачу (`message="some notification"`). + +## Впровадження залежностей + +Використання `BackgroundTasks` також працює з системою впровадження залежностей. Ви можете оголосити параметр типу `BackgroundTasks` на різних рівнях: у *функції операції шляху*, у залежності (dependable), у під залежності тощо. + +**FastAPI** знає, як діяти в кожному випадку і як повторно використовувати один і той самий об'єкт, щоб усі фонові задачі були об’єднані та виконувалися у фоновому режимі після завершення основного запиту. + +{* ../../docs_src/background_tasks/tutorial002_an_py310.py hl[13,15,22,25] *} + +У цьому прикладі повідомлення будуть записані у файл `log.txt` *після* того, як відповідь буде надіслана. + +Якщо у запиті був переданий query-параметр, він буде записаний у лог у фоновій задачі. + +А потім інша фонова задача, яка створюється у *функції операції шляху*, запише повідомлення з використанням path параметра `email`. + +## Технічні деталі + +Клас `BackgroundTasks` походить безпосередньо з `starlette.background`. + +Він імпортується безпосередньо у FastAPI, щоб Ви могли використовувати його з `fastapi` і випадково не імпортували `BackgroundTask` (без s в кінці) з `starlette.background`. + +Якщо використовувати лише `BackgroundTasks` (а не `BackgroundTask`), то його можна передавати як параметр у *функції операції шляху*, і **FastAPI** подбає про все інше, так само як і про використання об'єкта `Request`. + +Також можна використовувати `BackgroundTask` окремо в FastAPI, але для цього Вам доведеться створити об'єкт у коді та повернути Starlette `Response`, включаючи його. + +Детальніше можна почитати в офіційній документації Starlette про фонові задачі . + +## Застереження + +Якщо Вам потрібно виконувати складні фонові обчислення, і при цьому нема потреби запускати їх у тому ж процесі (наприклад, не потрібно спільного доступу до пам’яті чи змінних), можливо, варто скористатися більш потужними інструментами, такими як Celery. + +Такі інструменти зазвичай потребують складнішої конфігурації та менеджера черги повідомлень/завдань, наприклад, RabbitMQ або Redis. Однак вони дозволяють виконувати фонові задачі в кількох процесах і навіть на кількох серверах. + +Якщо ж Вам потрібно отримати доступ до змінних і об’єктів із тієї ж **FastAPI** - програми або виконувати невеликі фонові завдання (наприклад, надсилати сповіщення електронною поштою), достатньо просто використовувати `BackgroundTasks`. + +## Підсумок + +Імпортуйте та використовуйте `BackgroundTasks` як параметр у *функціях операції шляху* та залежностях, щоб додавати фонові задачі. diff --git a/docs/uk/docs/tutorial/body-multiple-params.md b/docs/uk/docs/tutorial/body-multiple-params.md new file mode 100644 index 000000000..e2acf8a70 --- /dev/null +++ b/docs/uk/docs/tutorial/body-multiple-params.md @@ -0,0 +1,170 @@ +# Тіло запиту - Декілька параметрів + +Тепер, коли ми розглянули використання `Path` та `Query`, розгляньмо більш просунуті способи оголошення тіла запиту в **FastAPI**. + +## Змішування `Path`, `Query` та параметрів тіла запиту + +По-перше, звісно, Ви можете вільно змішувати оголошення параметрів `Path`, `Query` та тіла запиту, і **FastAPI** правильно їх обробить. + +Також Ви можете оголосити параметри тіла як необов’язкові, встановивши для них значення за замовчуванням `None`: + +{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *} + +/// note | Примітка + +Зверніть увагу, що в цьому випадку параметр `item`, який береться з тіла запиту, є необов'язковим, оскільки має значення за замовчуванням `None`. + +/// + +## Декілька параметрів тіла запиту + +У попередньому прикладі *операція шляху* очікувала JSON з атрибутами `Item`, наприклад: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 +} +``` +Але Ви також можете оголосити декілька параметрів тіла, наприклад `item` та `user`: + +{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *} + +У цьому випадку **FastAPI** розпізнає, що є кілька параметрів тіла (два параметри є моделями Pydantic). + +Тому він використає назви параметрів як ключі (назви полів) у тілі запиту, очікуючи: + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + }, + "user": { + "username": "dave", + "full_name": "Dave Grohl" + } +} +``` + +/// note | Примітка + +Зверніть увагу, що хоча `item` оголошено, так само як і раніше, тепер він очікується в тілі під ключем `item`. + +/// + +**FastAPI** автоматично конвертує дані із запиту таким чином, щоб параметр `item` отримав свій вміст, і те ж саме стосується `user`. + +Він виконає валідацію складених даних і задокументує їх відповідним чином у схемі OpenAPI та в автоматичній документації. + +## Одиничні значення в тілі запиту + +Так само як є `Query` і `Path` для визначення додаткових даних для параметрів запиту та шляху, **FastAPI** надає еквівалентний `Body`. + +Наприклад, розширюючи попередню модель, Ви можете вирішити додати ще один ключ `importance` в те ж саме тіло запиту разом із `item` і `user`. + +Якщо Ви оголосите його як є, то, оскільки це одиничне значення, **FastAPI** припускатиме, що це параметр запиту (query parameter). + +Але Ви можете вказати **FastAPI** обробляти його як інший ключ тіла (body key), використовуючи `Body`: + +{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *} + +У цьому випадку **FastAPI** очікуватиме тіло запиту у такому вигляді: + +```JSON +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + }, + "user": { + "username": "dave", + "full_name": "Dave Grohl" + }, + "importance": 5 +} +``` +Знову ж таки, **FastAPI** конвертуватиме типи даних, перевірятиме їх, створюватиме документацію тощо. + +## Декілька body та query параметрів + +Звісно, Ви можете оголошувати додаткові query параметри запиту, коли це необхідно, на додаток до будь-яких параметрів тіла запиту. + +Оскільки за замовчуванням окремі значення інтерпретуються як параметри запиту, Вам не потрібно явно додавати `Query`, можна просто використати: + +```Python +q: Union[str, None] = None +``` + +Або в Python 3.10 та вище: + +```Python +q: str | None = None +``` + +Наприклад: + +{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *} + + +/// info | Інформація + +`Body` також має ті самі додаткові параметри валідації та метаданих, що й `Query`, `Path` та інші, які Ви побачите пізніше. + +/// + +## Вкладений поодинокий параметр тіла запиту + +Припустимо, у вас є лише один параметр тіла запиту `item` з моделі Pydantic `Item`. + +За замовчуванням **FastAPI** очікуватиме, що тіло запиту міститиме вміст безпосередньо. + +Але якщо Ви хочете, щоб він очікував JSON з ключем `item`, а всередині — вміст моделі (так, як це відбувається при оголошенні додаткових параметрів тіла), Ви можете використати спеціальний параметр `Body` — `embed`: + +```Python +item: Item = Body(embed=True) +``` + +як у прикладі: + +{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *} + +У цьому випадку **FastAPI** очікуватиме тіло запиту такого вигляду: + +```JSON hl_lines="2" +{ + "item": { + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 + } +} +``` + +замість: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2 +} +``` + +## Підсумок + +Ви можете додавати кілька параметрів тіла до Вашої *функції операції шляху* (*path operation function*), навіть якщо запит може мати лише одне тіло. + +Але **FastAPI** обробить це, надасть Вам потрібні дані у функції, перевірить їх та задокументує коректну схему в *операції шляху*. + +Також Ви можете оголошувати окремі значення, які будуть отримані як частина тіла запиту. + +Крім того, Ви можете вказати **FastAPI** вбудовувати тіло в ключ, навіть якщо оголошено лише один параметр. diff --git a/docs/uk/docs/tutorial/body-nested-models.md b/docs/uk/docs/tutorial/body-nested-models.md new file mode 100644 index 000000000..abc33f2eb --- /dev/null +++ b/docs/uk/docs/tutorial/body-nested-models.md @@ -0,0 +1,245 @@ +# Тіло запиту - Вкладені моделі + +З **FastAPI** Ви можете визначати, перевіряти, документувати та використовувати моделі, які можуть бути вкладені на будь-яку глибину (завдяки Pydantic). + +## Поля списку + +Ви можете визначити атрибут як підтип. Наприклад, Python-список (`list`): + +{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *} + +Це зробить `tags` списком, хоча не визначається тип елементів списку. + +## Поля списку з параметром типу + +Але Python має специфічний спосіб оголошення списків з внутрішніми типами або "параметрами типу": +### Імпортуємо `List` з модуля typing + +У Python 3.9 і вище можна використовувати стандартний `list` для оголошення таких типів, як ми побачимо нижче. 💡 + +Але в Python версії до 3.9 (від 3.6 і вище) спочатку потрібно імпортувати `List` з модуля стандартної бібліотеки Python `typing`: + +{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *} + +### Оголошення `list` з параметром типу + +Щоб оголосити типи з параметрами типу (внутрішніми типами), такими як `list`, `dict`, `tuple`: + +* Якщо Ви використовуєте версію Python до 3.9, імпортуйте їх відповідну версію з модуля `typing`. +* Передайте внутрішні типи як "параметри типу", використовуючи квадратні дужки: `[` and `]`. + +У Python 3.9 це буде виглядати так: + +```Python +my_list: list[str] +``` + +У версіях Python до 3.9 це виглядає так: + +```Python +from typing import List + +my_list: List[str] +``` + +Це стандартний синтаксис Python для оголошення типів. + +Використовуйте той самий стандартний синтаксис для атрибутів моделей з внутрішніми типами. + +Отже, у нашому прикладі, ми можемо зробити `tags` саме "списком рядків": + +{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *} + +## Типи множин + +Але потім ми подумали, що теги не повинні повторюватися, вони, ймовірно, повинні бути унікальними рядками. + +І Python має спеціальний тип даних для множин унікальних елементів — це `set`. + +Тому ми можемо оголосити `tags` як множину рядків: + +{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *} + +Навіть якщо Ви отримаєте запит з дубльованими даними, він буде перетворений у множину унікальних елементів. + +І коли Ви будете виводити ці дані, навіть якщо джерело містить дублікати, вони будуть виведені як множина унікальних елементів. + +І це буде анотовано/документовано відповідно. + +## Вкладені моделі + +Кожен атрибут моделі Pydantic має тип. + +Але цей тип сам може бути іншою моделлю Pydantic. + +Отже, Ви можете оголосити глибоко вкладені JSON "об'єкти" з конкретними іменами атрибутів, типами та перевірками. + +Усе це, вкладене без обмежень. + +### Визначення підмоделі + +Наприклад, ми можемо визначити модель `Image`: + +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *} + +### Використання підмоделі як типу + +А потім ми можемо використовувати її як тип атрибута: + +{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *} + +Це означатиме, що **FastAPI** очікуватиме тіло запиту такого вигляду: + +```JSON +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2, + "tags": ["rock", "metal", "bar"], + "image": { + "url": "http://example.com/baz.jpg", + "name": "The Foo live" + } +} +``` + +Завдяки такій декларації у **FastAPI** Ви отримуєте: + +* Підтримку в редакторі (автозавершення тощо), навіть для вкладених моделей +* Конвертацію даних +* Валідацію даних +* Автоматичну документацію + +## Спеціальні типи та валідація + +Окрім звичайних типів, таких як `str`, `int`, `float`, та ін. Ви можете використовувати складніші типи, які наслідують `str`. + +Щоб побачити всі доступні варіанти, ознайомтеся з оглядом типів у Pydantic. Деякі приклади будуть у наступних розділах. + +Наприклад, у моделі `Image` є поле `url`, тому ми можемо оголосити його як `HttpUrl` від Pydantic замість `str`: + +{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *} + +Рядок буде перевірено як дійсну URL-адресу і задокументовано в JSON Schema / OpenAPI як URL. + +## Атрибути зі списками підмоделей + +У Pydantic Ви можете використовувати моделі як підтипи для `list`, `set` тощо: + +{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *} + +Це означає, що **FastAPI** буде очікувати (конвертувати, валідувати, документувати тощо) JSON тіло запиту у вигляді: + +```JSON hl_lines="11" +{ + "name": "Foo", + "description": "The pretender", + "price": 42.0, + "tax": 3.2, + "tags": [ + "rock", + "metal", + "bar" + ], + "images": [ + { + "url": "http://example.com/baz.jpg", + "name": "The Foo live" + }, + { + "url": "http://example.com/dave.jpg", + "name": "The Baz" + } + ] +} +``` + +/// info | Інформація + +Зверніть увагу, що тепер ключ `images` містить список об'єктів зображень. + +/// + +## Глибоко вкладені моделі + +Ви можете визначати вкладені моделі довільної глибини: + +{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *} + +/// info | Інформація + +Зверніть увагу, що в моделі `Offer` є список `Item`ів, які, своєю чергою, можуть мати необов'язковий список `Image`ів. + +/// + +## Тіла запитів, що складаються зі списків + +Якщо верхній рівень JSON тіла, яке Ви очікуєте, є JSON `масивом` (у Python — `list`), Ви можете оголосити тип у параметрі функції, як і в моделях Pydantic: + +```Python +images: List[Image] +``` +або в Python 3.9 і вище: + +```Python +images: list[Image] +``` + +наприклад: + +{* ../../docs_src/body_nested_models/tutorial008_py39.py hl[13] *} + +## Підтримка в редакторі всюди + +Ви отримаєте підтримку в редакторі всюди. + +Навіть для елементів у списках: + + + +Ви не змогли б отримати таку підтримку в редакторі, якби працювали напряму зі `dict`, а не з моделями Pydantic. + +Але Вам не потрібно турбуватися про це: вхідні dict'и автоматично конвертуються, а вихідні дані автоматично перетворюються в JSON. + +## Тіла з довільними `dict` + +Ви також можете оголосити тіло як `dict` з ключами одного типу та значеннями іншого типу. + +Це корисно, якщо Ви не знаєте наперед, які імена полів будуть дійсними (як у випадку з моделями Pydantic). + +Це буде корисно, якщо Ви хочете приймати ключі, які заздалегідь невідомі. + +--- + +Це також зручно, якщо Ви хочете мати ключі іншого типу (наприклад, `int`). + +Ось що ми розглянемо далі. + +У цьому випадку Ви можете приймати будь-який `dict`, якщо його ключі — це `int`, а значення — `float`: + +{* ../../docs_src/body_nested_models/tutorial009_py39.py hl[7] *} + +/// tip | Порада + +Майте на увазі, що в JSON тілі ключі можуть бути лише рядками (`str`). + +Але Pydantic автоматично конвертує дані. + +Це означає, що навіть якщо клієнти вашого API надсилатимуть ключі у вигляді рядків, якщо вони містять цілі числа, Pydantic конвертує їх і проведе валідацію. + +Тобто `dict`, який Ви отримаєте як `weights`, матиме ключі типу `int` та значення типу `float`. + +/// + +## Підсумок + +З **FastAPI** Ви маєте максимальну гнучкість завдяки моделям Pydantic, зберігаючи при цьому код простим, коротким та елегантним. + +А також отримуєте всі переваги: + +* Підтримка в редакторі (автодоповнення всюди!) +* Конвертація даних (парсинг/сериалізація) +* Валідація даних +* Документація схем +* Автоматичне створення документації diff --git a/docs/uk/docs/tutorial/cookie-param-models.md b/docs/uk/docs/tutorial/cookie-param-models.md new file mode 100644 index 000000000..f070b6ac8 --- /dev/null +++ b/docs/uk/docs/tutorial/cookie-param-models.md @@ -0,0 +1,76 @@ +# Моделі для Cookie-параметрів + +Якщо у Вас є група **cookies** параметрів, які пов'язані між собою, Ви можете створити **Pydantic-модель**, щоб оголосити їх. 🍪 + +Це дозволить Вам повторно **використовувати модель** у **різних місцях**, а також оголосити валідацію та метадані для всіх параметрів одночасно. 😎 + +/// note | Нотатки + +Це підтримується з версії FastAPI `0.115.0`. 🤓 + +/// + +/// tip | Порада + +Ця ж техніка застосовується до `Query`, `Cookie`, та `Header`. 😎 + +/// + +## Cookie з Pydantic-моделлю + +Оголосіть **cookie-параметри**, які Вам потрібні, у **Pydantic-моделі**, а потім оголосіть параметр як `Cookie`: + +{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *} + +**FastAPI** буде **витягувати** дані для **кожного поля** з **cookie** параметрів, отриманих у запиті, і передавати Вам Pydantic-модель, яку Ви визначили. + +## Перевірка у документації + +Ви можете побачити визначені cookie в інтерфейсі документації за адресою `/docs`: + +

+ +
+ +/// info | Інформація + +Майте на увазі, що оскільки **браузери обробляють cookie** особливим чином і "за лаштунками", вони **не** дозволяють **JavaScript** легко з ними працювати. + +Якщо Ви зайдете до **інтерфейсу документації API** за адресою `/docs`, Ви зможете побачити **документацію** для cookie у Ваших **операціях шляху**. + +Але навіть якщо Ви заповните дані й натиснете "Execute", оскільки інтерфейс документації працює з **JavaScript**, cookie не будуть відправлені, і Ви побачите **помилку**, ніби Ви не ввели жодних значень. + +/// + +## Заборона додаткових cookie + +У деяких спеціальних випадках (ймовірно, не дуже поширених) Ви можете захотіти **обмежити** список cookie, які хочете отримувати. + +Ваша API тепер має можливість контролювати власну згоду на cookie. 🤪🍪 + +Ви можете використовувати налаштування моделі Pydantic, щоб `заборонити` будь-які `додаткові` поля: + +{* ../../docs_src/cookie_param_models/tutorial002_an_py39.py hl[10] *} + +Якщо клієнт спробує надіслати якісь **додаткові cookie**, він отримає відповідь з **помилкою**. + +Бідні банери cookie, які так старанно намагаються отримати Вашу згоду, щоб API її відхилила. 🍪 + +Наприклад, якщо клієнт спробує надіслати cookie `santa_tracker` зі значенням `good-list-please`, він отримає відповідь з помилкою, яка повідомить, що cookie `santa_tracker` не дозволено: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["cookie", "santa_tracker"], + "msg": "Extra inputs are not permitted", + "input": "good-list-please", + } + ] +} +``` + +## Підсумок + +Ви можете використовувати **Pydantic-моделі** для оголошення cookie у FastAPI. 😎 diff --git a/docs/uk/docs/tutorial/cors.md b/docs/uk/docs/tutorial/cors.md new file mode 100644 index 000000000..95b204d0f --- /dev/null +++ b/docs/uk/docs/tutorial/cors.md @@ -0,0 +1,89 @@ +# CORS (Обмін ресурсами між різними джерелами) + +CORS або "Обмін ресурсами між різними джерелами" є ситуація, коли фронтенд, що працює в браузері, містить JavaScript-код, який взаємодіє з бекендом, розташованим в іншому "джерелі" (origin). + +## Джерело (Origin) + +Джерело визначається комбінацією протоколу (`http`, `https`), домену (`myapp.com`, `localhost`, `localhost.tiangolo.com`), порту (`80`, `443`, `8080`). + + +Наприклад, такі адреси вважаються різними джерелами: + +* `http://localhost` +* `https://localhost` +* `http://localhost:8080` + +Навіть якщо вони всі містять `localhost`, вони мають різні протоколи або порти, що робить їх окремими "джерелами". + +## Кроки + +Припустимо, що Ваш фронтенд працює в браузері на `http://localhost:8080`, а його JavaScript намагається відправити запит до бекенду, який працює на `http://localhost` (Оскільки ми не вказуємо порт, браузер за замовчуванням припускає порт `80`). + +Потім браузер надішле HTTP-запит `OPTIONS` до бекенду на порту `:80`, і якщо бекенд надішле відповідні заголовки, що дозволяють комунікацію з цього іншого джерела (`http://localhost:8080`), тоді браузер на порту `:8080` дозволить JavaScript у фронтенді надіслати свій запит до бекенду на порту `:80`. + +Щоб досягти цього, бекенд на порту `:80` повинен мати список "дозволених джерел". + +У цьому випадку список має містити `http://localhost:8080`, щоб фронтенд на порту `:8080` працював коректно. + +## Символьне підставляння + +Можна також оголосити список як `"*"` ("символьне підставляння"), що означає дозвіл для всіх джерел. + +Однак це дозволить лише певні типи комунікації, виключаючи все, що пов'язане з обліковими даними: Cookies, заголовки авторизації, такі як ті, що використовуються з Bearer токенами тощо. + +Тому для коректної роботи краще явно вказувати дозволені джерела. + +## Використання `CORSMiddleware` + +Ви можете налаштувати це у Вашому додатку **FastAPI** за допомогою `CORSMiddleware`. + +* Імпортуйте `CORSMiddleware`. +* Створіть список дозволених джерел (у вигляді рядків). +* Додайте його як "middleware" у Ваш додаток **FastAPI**. + + +Також можна вказати, чи дозволяє Ваш бекенд: + +* Облікові дані (заголовки авторизації, сookies, тощо). +* Конкретні HTTP-методи (`POST`, `PUT`) або всі за допомогою `"*"` +* Конкретні HTTP-заголовки або всі за допомогою `"*"`. + + +{* ../../docs_src/cors/tutorial001.py hl[2,6:11,13:19] *} + +Параметри за замовчуванням у `CORSMiddleware` є досить обмеженими, тому Вам потрібно явно вказати конкретні джерела, методи або заголовки, щоб браузери могли використовувати їх у контексті запитів між різними доменами. + + +Підтримуються такі аргументи: + +* `allow_origins` - Список джерел, яким дозволено здійснювати міждоменні запити. Наприклад `['https://example.org', 'https://www.example.org']`. Ви можете використовувати ['*'], щоб дозволити всі джерела. +* `allow_origin_regex` - Рядок регулярного виразу для відповідності джерелам, яким дозволено здійснювати міждоменні запити. Наприклад, `'https://.*\.example\.org'`. +* `allow_methods` - Список HTTP-методів, дозволених для міждоменних запитів. За замовчуванням `['GET']`. Ви можете використовувати `['*']`, щоб дозволити всі стандартні методи. +* `allow_headers` - Список HTTP-заголовків, які підтримуються для міждоменних запитів. За замовчуванням `[]`. Ви можете використовувати `['*']`, щоб дозволити всі заголовки. Заголовки `Accept`, `Accept-Language`, `Content-Language` і `Content-Type` завжди дозволені для простих CORS-запитів. +* `allow_credentials` - Визначає, чи підтримуються файли cookie для міждоменних запитів. За замовчуванням `False`. Також, якщо потрібно дозволити обмін обліковими даними (`allow_credentials = True`), параметр `allow_origins` не може бути встановлений як `['*']`, необхідно вказати конкретні джерела. +* `expose_headers` - Вказує, які заголовки відповіді повинні бути доступні для браузера. За замовчуванням `[]`. +* `max_age` - Встановлює максимальний час (у секундах) для кешування CORS-відповідей у браузерах. За замовчуванням `600`. + +Цей middleware обробляє два типи HTTP-запитів... + +### Попередні CORS-запити (preflight requests) + +Це будь-які `OPTIONS` - запити, що містять заголовки `Origin` та `Access-Control-Request-Method`. + +У такому випадку middleware перехопить вхідний запит і відповість відповідними CORS-заголовками, повертаючи або `200`, або `400` для інформаційних цілей. + +### Прості запити + +Будь-які запити із заголовком `Origin`. У цьому випадку middleware пропустить запит як звичайний, але додасть відповідні CORS-заголовки у відповідь. + +## Додаткова інформація + +Більше про CORS можна дізнатися в документації Mozilla. + +/// note | Технічні деталі + +Також можна використовувати `from starlette.middleware.cors import CORSMiddleware`. + +**FastAPI** надає кілька middleware у `fastapi.middleware` для зручності розробників. Але більшість доступних middleware походять безпосередньо зі Starlette. + +/// diff --git a/docs/uk/docs/tutorial/debugging.md b/docs/uk/docs/tutorial/debugging.md new file mode 100644 index 000000000..b0e5344f8 --- /dev/null +++ b/docs/uk/docs/tutorial/debugging.md @@ -0,0 +1,112 @@ +# Налагодження (Debugging) + +Ви можете під'єднати дебагер у Вашому редакторі коду, наприклад, у Visual Studio Code або PyCharm. + +## Виклик `uvicorn` + +У Вашому FastAPI-додатку імпортуйте та запустіть `uvicorn` безпосередньо: + +{* ../../docs_src/debugging/tutorial001.py hl[1,15] *} + +### Про `__name__ == "__main__"` + +Головна мета використання `__name__ == "__main__"` — це забезпечення виконання певного коду тільки тоді, коли файл запускається безпосередньо: + +
+ +```console +$ python myapp.py +``` + +
+ +але не виконується при його імпорті в інший файл, наприклад: + +```Python +from myapp import app +``` + +#### Детальніше + +Припустимо, Ваш файл називається `myapp.py`. + +Якщо Ви запустите його так: + +
+ +```console +$ python myapp.py +``` + +
+ +тоді внутрішня змінна `__name__`, яка створюється автоматично Python, матиме значення `"__main__"`. + +Отже, цей блок коду: + +```Python + uvicorn.run(app, host="0.0.0.0", port=8000) +``` + +буде виконаний. + +--- + +Це не станеться, якщо Ви імпортуєте цей модуль (файл). + +Якщо у Вас є інший файл, наприклад `importer.py`, з наступним кодом: + +```Python +from myapp import app + +# Додатковий код +``` + +У цьому випадку автоматично створена змінна у файлі `myapp.py` не матиме значення змінної `__name__` як `"__main__"`. + +Отже, рядок: + +```Python + uvicorn.run(app, host="0.0.0.0", port=8000) +``` + +не буде виконано. + +/// info | Інформація + +Більш детальну інформацію можна знайти в офіційній документації Python. + +/// + +## Запуск коду з вашим дебагером + +Оскільки Ви запускаєте сервер Uvicorn безпосередньо з Вашого коду, Ви можете запустити вашу Python програму (ваш FastAPI додаток) безпосередньо з дебагера. + +--- + +Наприклад, у Visual Studio Code Ви можете: + +* Перейдіть на вкладку "Debug". +* Натисніть "Add configuration...". +* Виберіть "Python" +* Запустіть дебагер з опцією "`Python: Current File (Integrated Terminal)`". + +Це запустить сервер з Вашим **FastAPI** кодом, зупиниться на точках зупину тощо. + +Ось як це може виглядати: + + + +--- +Якщо Ви використовуєте PyCharm, ви можете: + +* Відкрити меню "Run". +* Вибрати опцію "Debug...". +* Потім з'явиться контекстне меню. +* Вибрати файл для налагодження (у цьому випадку, `main.py`). + +Це запустить сервер з Вашим **FastAPI** кодом, зупиниться на точках зупину тощо. + +Ось як це може виглядати: + + diff --git a/docs/uk/docs/tutorial/handling-errors.md b/docs/uk/docs/tutorial/handling-errors.md new file mode 100644 index 000000000..12a356cd0 --- /dev/null +++ b/docs/uk/docs/tutorial/handling-errors.md @@ -0,0 +1,255 @@ +# Обробка Помилок + +Є багато ситуацій, коли потрібно повідомити клієнта, який використовує Ваш API, про помилку. + +Цим клієнтом може бути браузер із фронтендом, код іншого розробника, IoT-пристрій тощо. + +Можливо, Вам потрібно повідомити клієнта, що: + +* У нього недостатньо прав для виконання цієї операції. +* Він не має доступу до цього ресурсу. +* Елемент, до якого він намагається отримати доступ, не існує. +* тощо. + +У таких випадках зазвичай повертається **HTTP статус-код** в діапазоні **400** (від 400 до 499). + +Це схоже на HTTP статус-коди 200 (від 200 до 299). Ці "200" статус-коди означають, що запит пройшов успішно. + +Статус-коди в діапазоні 400 означають, що сталася помилка з боку клієнта. + +Пам'ятаєте всі ці помилки **404 Not Found** (і жарти про них)? + +## Використання `HTTPException` + +Щоб повернути HTTP-відповіді з помилками клієнту, використовуйте `HTTPException`. + +### Імпорт `HTTPException` + +{* ../../docs_src/handling_errors/tutorial001.py hl[1] *} + +### Використання `HTTPException` у коді + +`HTTPException` — це звичайна помилка Python із додатковими даними, які стосуються API. + +Оскільки це помилка Python, Ви не `повертаєте` його, а `генеруєте` (генеруєте помилку). + +Це також означає, що якщо Ви перебуваєте всередині допоміжної функції, яку викликаєте всередині своєї *функції операції шляху*, і там генеруєте `HTTPException`, всередині цієї допоміжної функції, то решта коду в *функції операції шляху* не буде виконана. Запит одразу завершиться, і HTTP-помилка з `HTTPException` буде надіслана клієнту. + +Перевага використання `генерації` (raise) помилки замість `повернення` значення (return) стане більш очевидним в розділі про Залежності та Безпеку. + +У цьому прикладі, якщо клієнт запитує елемент за ID, якого не існує, буде згенеровано помилку зі статус-кодом `404`: + +{* ../../docs_src/handling_errors/tutorial001.py hl[11] *} + +### Отримана відповідь + +Якщо клієнт робить запит за шляхом `http://example.com/items/foo` (де `item_id` `"foo"`), він отримає статус-код 200 і JSON відповідь: + +```JSON +{ + "item": "The Foo Wrestlers" +} +``` + +Але якщо клієнт робить запит на `http://example.com/items/bar` (де `item_id` має не існуюче значення `"bar"`), то отримає статус-код 404 (помилка "не знайдено") та відповідь: + +```JSON +{ + "detail": "Item not found" +} +``` + +/// tip | Порада + +Під час виклику `HTTPException` Ви можете передати будь-яке значення, яке може бути перетворене в JSON, як параметр `detail`, а не лише рядок (`str`). + +Ви можете передати `dict`, `list` тощо. + +Вони обробляються автоматично за допомогою **FastAPI** та перетворюються в JSON. + +/// + +## Додавання власних заголовків + +Іноді потрібно додати власні заголовки до HTTP-помилки, наприклад, для певних типів безпеки. + +Ймовірно, Вам не доведеться використовувати це безпосередньо у своєму коді. + +Але якщо Вам знадобиться це для складного сценарію, Ви можете додати власні заголовки: + +{* ../../docs_src/handling_errors/tutorial002.py hl[14] *} + +## Встановлення власних обробників помилок + +Ви можете додати власні обробники помилок за допомогою тих самих утиліт обробки помилок зі Starlette. + +Припустимо, у Вас є власний обʼєкт помилки `UnicornException`, яке Ви (або бібліотека, яку Ви використовуєте) може `згенерувати` (`raise`). + +І Ви хочете обробляти це виключення глобально за допомогою FastAPI. + +Ви можете додати власний обробник виключень за допомогою `@app.exception_handler()`: + +{* ../../docs_src/handling_errors/tutorial003.py hl[5:7,13:18,24] *} + +Тут, якщо Ви звернетеся до `/unicorns/yolo`, то згенерується помилка `UnicornException`. + +Але вона буде оброблена функцією-обробником `unicorn_exception_handler`. + +Отже, Ви отримаєте зрозумілу помилку зі HTTP-статусом `418` і JSON-відповіддю: + +```JSON +{"message": "Oops! yolo did something. There goes a rainbow..."} +``` + +/// note | Технічні деталі + +Ви також можете використовувати `from starlette.requests import Request` і `from starlette.responses import JSONResponse`. + +**FastAPI** надає ті самі `starlette.responses`, що й `fastapi.responses`, просто для зручності розробника. Але більшість доступних відповідей надходять безпосередньо зі Starlette. Те ж саме стосується і `Request`. + +/// + +## Перевизначення обробників помилок за замовчуванням + +**FastAPI** має кілька обробників помилок за замовчуванням. + +Ці обробники відповідають за повернення стандартних JSON-відповідей, коли Ви `генеруєте` (`raise`) `HTTPException`, а також коли запит містить некоректні дані. + +Ви можете перевизначити ці обробники, створивши власні. + +### Перевизначення помилок валідації запиту + +Коли запит містить некоректні дані, **FastAPI** генерує `RequestValidationError`. + +І також включає обробник помилок за замовчуванням для нього. + +Щоб перевизначити його, імпортуйте `RequestValidationError` і використовуйте його з `@app.exception_handler(RequestValidationError)` для декорування обробника помилок. + +Обробник помилок отримує `Request` і саму помилку. + +{* ../../docs_src/handling_errors/tutorial004.py hl[2,14:16] *} + +Тепер, якщо Ви перейдете за посиланням `/items/foo`, замість того, щоб отримати стандартну JSON-помилку: + +```JSON +{ + "detail": [ + { + "loc": [ + "path", + "item_id" + ], + "msg": "value is not a valid integer", + "type": "type_error.integer" + } + ] +} +``` + +Ви отримаєте текстову версію: + +``` +1 validation error +path -> item_id + value is not a valid integer (type=type_error.integer) +``` + +#### `RequestValidationError` проти `ValidationError` + +/// warning | Увага + +Це технічні деталі, які Ви можете пропустити, якщо вони зараз не важливі для Вас. + +/// + +`RequestValidationError` є підкласом Pydantic `ValidationError`. + +**FastAPI** використовує його для того, якщо Ви використовуєте модель Pydantic у `response_model` і у ваших даних є помилка, Ви побачили помилку у своєму журналі. + +Але клієнт/користувач не побачить її. Натомість клієнт отримає "Internal Server Error" зі статусом HTTP `500`. + +Так має бути, якщо у Вас виникла `ValidationError` Pydantic у *відповіді* або деінде у вашому коді (не у *запиті* клієнта), це насправді є помилкою у Вашому коді. + +І поки Ви її виправляєте, клієнти/користувачі не повинні мати доступу до внутрішньої інформації про помилку, оскільки це може призвести до вразливості безпеки. + +### Перевизначення обробника помилок `HTTPException` + +Аналогічно, Ви можете перевизначити обробник `HTTPException`. + +Наприклад, Ви можете захотіти повернути текстову відповідь замість JSON для цих помилок: + +{* ../../docs_src/handling_errors/tutorial004.py hl[3:4,9:11,22] *} + +/// note | Технічні деталі + +Ви також можете використовувати `from starlette.responses import PlainTextResponse`. + +**FastAPI** надає ті самі `starlette.responses`, що й `fastapi.responses`, просто для зручності розробника. Але більшість доступних відповідей надходять безпосередньо зі Starlette. + +/// + +### Використання тіла `RequestValidationError` + +`RequestValidationError` містить `body`, який він отримав із некоректними даними. + +Ви можете використовувати це під час розробки свого додатка, щоб логувати тіло запиту та налагоджувати його, повертати користувачеві тощо. + +{* ../../docs_src/handling_errors/tutorial005.py hl[14] *} + +Тепер спробуйте надіслати некоректний елемент, наприклад: + +```JSON +{ + "title": "towel", + "size": "XL" +} +``` +Ви отримаєте відповідь, яка повідомить Вам, які саме дані є некоректні у вашому тілі запиту: + + +```JSON hl_lines="12-15" +{ + "detail": [ + { + "loc": [ + "body", + "size" + ], + "msg": "value is not a valid integer", + "type": "type_error.integer" + } + ], + "body": { + "title": "towel", + "size": "XL" + } +} +``` + +#### `HTTPException` FastAPI проти `HTTPException` Starlette + +**FastAPI** має власний `HTTPException`. + +І клас помилки `HTTPException` в **FastAPI** успадковується від класу помилки `HTTPException` в Starlette. + +Єдина різниця полягає в тому, що `HTTPException` в **FastAPI** приймає будь-які дані, які можна перетворити на JSON, для поля `detail`, тоді як `HTTPException` у Starlette приймає тільки рядки. + +Отже, Ви можете продовжувати використовувати `HTTPException` в **FastAPI** як зазвичай у своєму коді. + +Але коли Ви реєструєте обробник виключень, слід реєструвати його для `HTTPException` зі Starlette. + +Таким чином, якщо будь-яка частина внутрішнього коду Starlette або розширення чи плагін Starlette згенерує (raise) `HTTPException`, Ваш обробник зможе перехопити та обробити її. + +У цьому прикладі, щоб мати можливість використовувати обидва `HTTPException` в одному коді, помилка Starlette перейменовується на `StarletteHTTPException`: + +```Python +from starlette.exceptions import HTTPException as StarletteHTTPException +``` + +### Повторне використання обробників помилок **FastAPI** + +Якщо Ви хочете використовувати помилки разом із такими ж обробниками помилок за замовчуванням, як у **FastAPI**, Ви можете імпортувати та повторно використовувати їх із `fastapi.exception_handlers`: + +{* ../../docs_src/handling_errors/tutorial006.py hl[2:5,15,21] *} + +У цьому прикладі Ви просто використовуєте `print` для виведення дуже інформативного повідомлення, але Ви зрозуміли основну ідею. Ви можете обробити помилку та повторно використовувати обробники помилок за замовчуванням. diff --git a/docs/uk/docs/tutorial/header-param-models.md b/docs/uk/docs/tutorial/header-param-models.md new file mode 100644 index 000000000..6f7b0bdae --- /dev/null +++ b/docs/uk/docs/tutorial/header-param-models.md @@ -0,0 +1,58 @@ +# Моделі Параметрів Заголовків + +Якщо у Вас є група пов’язаних параметрів заголовків, Ви можете створити **Pydantic модель** для їх оголошення. + +Це дозволить Вам повторно **використовувати модель** в **різних місцях**, а також оголосити валідації та метадані для всіх параметрів одночасно. 😎 + +/// note | Нотатки + +Ця можливість підтримується починаючи з версії FastAPI `0.115.0`. 🤓 + +/// + +## Параметри Заголовків з Використанням Pydantic Model + +Оголосіть потрібні **параметри заголовків** у **Pydantic моделі**, а потім оголосіть параметр як `Header`: + +{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *} + +FastAPI буде витягувати дані для кожного поля з заголовків у запиті та передавати їх у створену Вами Pydantic модель. + +**FastAPI** буде **витягувати** дані для **кожного поля** з **заголовків** у запиті та передавати їх у створену Вами Pydantic модель. + +## Перевірка в Документації + +Ви можете побачити необхідні заголовки в інтерфейсі документації за адресою `/docs`: + +
+ +
+ +## Заборона Додаткових Заголовків + +У деяких особливих випадках (ймовірно, не дуже поширених) Ви можете захотіти **обмежити** заголовки, які хочете отримати. + +Ви можете використати конфігурацію моделі Pydantic, щоб `заборонити` будь-які `додаткові` поля: + +{* ../../docs_src/header_param_models/tutorial002_an_py310.py hl[10] *} + +Якщо клієнт спробує надіслати **додаткові заголовки**, він отримає **помилку** у відповіді. + +Наприклад, якщо клієнт спробує надіслати заголовок `tool` зі значенням `plumbus`, він отримає **помилку** з повідомленням про те, що параметр заголовка `tool` не дозволений: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["header", "tool"], + "msg": "Extra inputs are not permitted", + "input": "plumbus", + } + ] +} +``` + +## Підсумок + +Ви можете використовувати **Pydantic моделі** для оголошення **заголовків** у **FastAPI**. 😎 diff --git a/docs/uk/docs/tutorial/header-params.md b/docs/uk/docs/tutorial/header-params.md new file mode 100644 index 000000000..09c70a4f6 --- /dev/null +++ b/docs/uk/docs/tutorial/header-params.md @@ -0,0 +1,91 @@ +# Header-параметри + +Ви можете визначати параметри заголовків, так само як визначаєте `Query`, `Path` і `Cookie` параметри. + +## Імпорт `Header` + +Спочатку імпортуйте `Header`: + +{* ../../docs_src/header_params/tutorial001_an_py310.py hl[3] *} + +## Оголошення параметрів `Header` + +Потім оголосіть параметри заголовків, використовуючи ту ж структуру, що й для `Path`, `Query` та `Cookie`. + +Ви можете визначити значення за замовчуванням, а також усі додаткові параметри валідації або анотації: + +{* ../../docs_src/header_params/tutorial001_an_py310.py hl[9] *} + +/// note | Технічні деталі + +`Header`є "сестринським" класом для `Path`, `Query` і `Cookie`. Він також успадковується від загального класу `Param`. + +Але пам’ятайте, що при імпорті `Query`, `Path`, `Header` та інших із `fastapi`, то насправді вони є функціями, які повертають спеціальні класи. + +/// + +/// info | Інформація + +Щоб оголосити заголовки, потрібно використовувати `Header`, інакше параметри будуть інтерпретуватися як параметри запиту. + +/// + +## Автоматичне перетворення + +`Header` має додатковий функціонал порівняно з `Path`, `Query` та `Cookie`. + +Більшість стандартних заголовків розділяються символом «дефіс», також відомим як «мінус» (`-`). + +Але змінна, така як `user-agent`, є недійсною в Python. + +Тому, за замовчуванням, `Header` автоматично перетворює символи підкреслення (`_`) на дефіси (`-`) для отримання та документування заголовків. + +Оскільки заголовки HTTP не чутливі до регістру, Ви можете використовувати стандартний стиль Python ("snake_case"). + +Тому Ви можете використовувати `user_agent`, як зазвичай у коді Python, замість того щоб писати з великої літери, як `User_Agent` або щось подібне. + +Якщо Вам потрібно вимкнути автоматичне перетворення підкреслень у дефіси, встановіть `convert_underscores` в `Header` значення `False`: + +{* ../../docs_src/header_params/tutorial002_an_py310.py hl[10] *} + +/// warning | Увага + +Перед тим як встановити значення `False` для `convert_underscores` пам’ятайте, що деякі HTTP-проксі та сервери не підтримують заголовки з підкресленнями. + +/// + +## Дубльовані заголовки + +Можливо отримати дубльовані заголовки, тобто той самий заголовок із кількома значеннями. + +Це можна визначити, використовуючи список у типізації параметра. + +Ви отримаєте всі значення дубльованого заголовка у вигляді `list` у Python. + +Наприклад, щоб оголосити заголовок `X-Token`, який може з’являтися більше ніж один раз: + +{* ../../docs_src/header_params/tutorial003_an_py310.py hl[9] *} + +Якщо Ви взаємодієте з цією операцією шляху, надсилаючи два HTTP-заголовки, наприклад: + +``` +X-Token: foo +X-Token: bar +``` + +Відповідь буде така: + +```JSON +{ + "X-Token values": [ + "bar", + "foo" + ] +} +``` + +## Підсумок + +Оголошуйте заголовки за допомогою `Header`, використовуючи той самий підхід, що й для `Query`, `Path` та `Cookie`. + +Не хвилюйтеся про підкреслення у змінних — **FastAPI** автоматично конвертує їх. diff --git a/docs/uk/docs/tutorial/metadata.md b/docs/uk/docs/tutorial/metadata.md new file mode 100644 index 000000000..64e667ec6 --- /dev/null +++ b/docs/uk/docs/tutorial/metadata.md @@ -0,0 +1,120 @@ +# Метадані та URL-адреси документації + +Ви можете налаштувати кілька конфігурацій метаданих у Вашому додатку **FastAPI**. + +## Метадані для API + +Ви можете встановити такі поля, які використовуються в специфікації OpenAPI та в автоматично згенерованих інтерфейсах документації API: + +| Параметр | Тип | Опис | +|------------|------|-------------| +| `title` | `str` | Назва API. | +| `summary` | `str` | Короткий опис API. Доступно з OpenAPI 3.1.0, FastAPI 0.99.0. | +| `description` | `str` | Більш детальний опис API. Може використовувати Markdown. | +| `version` | `string` | Версія API. Це версія Вашого додатка, а не OpenAPI. Наприклад, `2.5.0`. | +| `terms_of_service` | `str` | URL до умов використання API. Якщо вказано, має бути у форматі URL. | +| `contact` | `dict` | Інформація для контакту з API. Може містити кілька полів.
contact поля
ПараметрТипОпис
namestrІм'я контактної особи або організації.
urlstrURL з інформацією для контакту. Повинен бути у форматі URL.
emailstrEmail контактної особи або організації. Повинен бути у форматі електронної пошти.
| +| `license_info` | `dict` | Інформація про ліцензію для API. Може містити кілька полів.
license_info поля
ПараметрТипОпис
namestrОБОВ'ЯЗКОВО (якщо встановлено license_info). Назва ліцензії для API.
identifierstrЛіцензійний вираз за SPDX для API. Поле identifier взаємовиключне з полем url. Доступно з OpenAPI 3.1.0, FastAPI 0.99.0.
urlstrURL до ліцензії, яка використовується для API. Повинен бути у форматі URL.
| + +Ви можете налаштувати їх наступним чином: + +{* ../../docs_src/metadata/tutorial001.py hl[3:16, 19:32] *} + +/// tip | Підказка + +У полі `description` можна використовувати Markdown, і він буде відображатися у результаті. + +/// + +З цією конфігурацією автоматична документація API виглядатиме так: + + + +## Ідентифікатор ліцензії + +З початку використання OpenAPI 3.1.0 та FastAPI 0.99.0 Ви також можете налаштувати `license_info` за допомогою `identifier` замість `url`. + +Наприклад: + +{* ../../docs_src/metadata/tutorial001_1.py hl[31] *} + +## Метадані для тегів + +Ви також можете додати додаткові метадані для різних тегів, які використовуються для групування операцій шляхів, за допомогою параметра `openapi_tags`. + +Він приймає список, який містить один словник для кожного тега. + +Кожен словник може містити: + +* `name` (**обов'язково**): `str` з тією ж назвою тегу, яку Ви використовуєте у параметрі `tags` у Ваших *операціях шляху* та `APIRouter`s. +* `description`: `str` з коротким описом тегу. Може містити Markdown і буде відображено в інтерфейсі документації. +* `externalDocs`: `dict` який описує зовнішню документацію з такими полями: + * `description`: `str` з коротким описом зовнішньої документації. + * `url` (**обов'язково**): `str`з URL-адресою зовнішньої документації. + +### Створення метаданих для тегів + +Спробуймо це на прикладі з тегами для `users` та `items`. + +Створіть метадані для своїх тегів і передайте їх у параметр `openapi_tags`: + +{* ../../docs_src/metadata/tutorial004.py hl[3:16,18] *} + +Зверніть увагу, що в описах можна використовувати Markdown, наприклад, "login" буде показано жирним шрифтом (**login**), а "fancy" буде показано курсивом (_fancy_). + +/// tip | Порада + +Не обов'язково додавати метадані для всіх тегів, які Ви використовуєте. + +/// + +### Використання тегів + +Використовуйте параметр `tags` зі своїми *операціями шляху* (і `APIRouter`) для призначення їх до різних тегів: + +{* ../../docs_src/metadata/tutorial004.py hl[21,26] *} + +/// info | Інформація + +Детальніше про теги читайте в розділі [Конфігурація шляхів операцій](path-operation-configuration.md#tags){.internal-link target=_blank}. + +/// + +### Перевірка документації + +Якщо Ви зараз перевірите документацію, вона покаже всі додаткові метадані: + + + +### Порядок тегів + +Порядок кожного словника метаданих тегу також визначає порядок відображення в інтерфейсі документації. + +Наприклад, хоча `users` мав би йти після `items` в алфавітному порядку, він відображається перед ними, оскільки ми додали його метадані як перший словник у списку. + +## URL для OpenAPI + +За замовчуванням схема OpenAPI надається за адресою `/openapi.json`. + +Але Ви можете налаштувати це за допомогою параметра `openapi_url`. + +Наприклад, щоб налаштувати його на `/api/v1/openapi.json`: + +{* ../../docs_src/metadata/tutorial002.py hl[3] *} + +Якщо Ви хочете повністю вимкнути схему OpenAPI, Ви можете встановити `openapi_url=None`, це також вимкне інтерфейси документації, які її використовують. + +## URL-адреси документації + +Ви можете налаштувати два інтерфейси користувача для документації, які включені: + +* **Swagger UI**: доступний за адресою `/docs`. + * Ви можете змінити його URL за допомогою параметра `docs_url`. + * Ви можете вимкнути його, встановивши `docs_url=None`. +* **ReDoc**: доступний за адресою `/redoc`. + * Ви можете змінити його URL за допомогою параметра `redoc_url`. + * Ви можете вимкнути його, встановивши `redoc_url=None`. + +Наприклад, щоб налаштувати Swagger UI на `/documentation` і вимкнути ReDoc: + +{* ../../docs_src/metadata/tutorial003.py hl[3] *} diff --git a/docs/uk/docs/tutorial/middleware.md b/docs/uk/docs/tutorial/middleware.md new file mode 100644 index 000000000..807be484a --- /dev/null +++ b/docs/uk/docs/tutorial/middleware.md @@ -0,0 +1,75 @@ +# Middleware (Проміжний шар) + +У **FastAPI** можна додавати middleware (проміжний шар). + +"Middleware" — це функція, яка працює з кожним **запитом** перед його обробкою будь-якою конкретною *операцією шляху* (*path operation*), а також з кожною **відповіддю** перед її поверненням. + +* Middleware отримує кожен **запит**, що надходить до Вашого застосунку. +* Може виконати певні дії із цим **запитом** або запустити необхідний код. +* Далі передає **запит** для обробки основним застосунком (*операцією шляху*). +* Отримує **відповідь**, сформовану застосунком (*операцією шляху*). +* Може змінити цю **відповідь** або виконати додатковий код. +* Повертає **відповідь** клієнту. + +/// note | Технічні деталі + +Якщо у Вас є залежності з `yield`, код виходу виконається *після* middleware. + +Якщо були заплановані фонові задачі (background tasks - розглянуто далі), вони виконаються *після* всіх middleware. + +/// + +## Створення middleware + +Щоб створити middleware, Ви використовуєте декоратор `@app.middleware("http")` на функції. + +Функція middleware отримує: + +* `Запит`. +* Функцію `call_next`, яка приймає `запит` як параметр. + * Ця функція передає `запит` відповідній *операції шляху*. + * Потім вона повертає `відповідь`, згенеровану цією *операцією шляху*. + +* Ви можете ще змінити `відповідь` перед тим, як повернути її. + + +{* ../../docs_src/middleware/tutorial001.py hl[8:9,11,14] *} + +/// tip | Порада + +Не забувайте, що власні заголовки можна додавати, використовуючи префікс 'X-'. + +Але якщо у Вас є власні заголовки, які Ви хочете, щоб браузерний клієнт міг побачити, потрібно додати їх до Вашої конфігурації CORS (див. [CORS (Обмін ресурсами між різними джерелами)](cors.md){.internal-link target=_blank} за допомогою параметра `expose_headers`, описаного в документації Starlette по CORS. + +/// + +/// note | Технічні деталі + +Ви також можете використати `from starlette.requests import Request`. + +**FastAPI** надає це для Вашої зручності як розробника. Але він походить безпосередньо зі Starlette. + +/// + +### До і після `response`(`відповіді`) + +Ви можете додати код, який буде виконуватися з `запитом` (`request`), до того, як його обробить будь-яка *операція шляху* (*path operation*). + +Також Ви можете додати код, який буде виконуватися після того, як `відповідь` (`response`) буде згенеровано, перед тим як його повернути. + +Наприклад, Ви можете додати власний заголовок `X-Process-Time`, який міститиме час у секундах, який витратився на обробку запиту та генерацію відповіді: + +{* ../../docs_src/middleware/tutorial001.py hl[10,12:13] *} + + +/// tip | Підказка + +Тут ми використовуємо `time.perf_counter()` замість `time.time()` оскільки він може бути більш точним для таких випадків. 🤓 + +/// + +## Інші middlewares + +Ви можете пізніше прочитати більше про інші middlewares в [Advanced User Guide: Advanced Middleware](../advanced/middleware.md){.internal-link target=_blank}. + +Ви дізнаєтесь, як обробляти CORS за допомогою middleware в наступному розділі. diff --git a/docs/uk/docs/tutorial/path-params-numeric-validations.md b/docs/uk/docs/tutorial/path-params-numeric-validations.md new file mode 100644 index 000000000..281ee183c --- /dev/null +++ b/docs/uk/docs/tutorial/path-params-numeric-validations.md @@ -0,0 +1,165 @@ +# Path Параметри та валідація числових даних + +Так само як Ви можете оголошувати додаткові перевірки та метадані для query параметрів за допомогою `Query`, Ви можете оголошувати той самий тип перевірок і метаданих для параметрів шляху за допомогою `Path`. + +## Імпорт Path + +Спочатку імпортуйте `Path` з `fastapi` і імпортуйте `Annotated`: + +{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[1,3] *} + +/// info | Інформація + +FastAPI додав підтримку `Annotated` (і почав рекомендувати його використання) у версії 0.95.0. + +Якщо у Вас стара версія, при спробі використати `Annotated` можуть виникати помилки. + +Переконайтеся, що Ви [оновили версію FastAPI](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} принаймні до версії 0.95.1 перед використанням `Annotated`. + +/// + +## Оголошення метаданих + +Ви можете оголошувати всі ті ж параметри, що і для `Query`. + +Наприклад, щоб оголосити значення метаданих `title` для параметра шляху `item_id`, Ви можете написати: + +{* ../../docs_src/path_params_numeric_validations/tutorial001_an_py310.py hl[10] *} + +/// note | Примітка + +Параметр шляху завжди є обов’язковим, оскільки він має бути частиною шляху. Навіть якщо Ви оголосите його зі значенням `None` або встановите значення за замовчуванням — він все одно залишатиметься обов’язковим. + +/// + +## Упорядковуйте параметри, як Вам потрібно + +/// tip | Підказка + +Це, мабуть, не настільки важливо або необхідно, якщо Ви використовуєте `Annotated`. + +/// + +Припустимо, Ви хочете оголосити параметр запиту `q` як обов’язковий `str`. + +І Вам не потрібно оголошувати нічого іншого для цього параметра, тому немає потреби використовувати `Query`. + +Але Вам все одно потрібно використовувати `Path` для параметра шляху `item_id`. І з певних причин Ви не хочете використовувати `Annotated`. + +Python видасть помилку, якщо розмістити значення з "default" перед значенням, яке не має "default". + +Але Ви можете змінити порядок і розмістити значення без значення за замовчуванням (параметр запиту `q`) першим. + + +Для **FastAPI** порядок не має значення. Він визначає параметри за їх іменами, типами та значеннями за замовчуванням (`Query`, `Path` тощо) і не звертає уваги на порядок. + +Тому Ви можете оголосити Вашу функцію так: + +//// tab | Python 3.8 non-Annotated + +/// tip | Підказка + +За можливості віддавайте перевагу версії з використанням `Annotated`. + +/// + +{* ../../docs_src/path_params_numeric_validations/tutorial002.py hl[7] *} + +//// + +Але майте на увазі, що якщо Ви використовуєте `Annotated`, ця проблема не виникне, оскільки Ви не використовуєте значення за замовчуванням для параметрів `Query()` або `Path()`. + +{* ../../docs_src/path_params_numeric_validations/tutorial002_an_py39.py *} + +## Упорядковуйте параметри за потребою, хитрощі + +/// tip | Підказка + +Це, мабуть, не настільки важливо або необхідно, якщо Ви використовуєте `Annotated`. + +/// + +Ось **невелика хитрість**, яка може стати в пригоді, хоча вона рідко знадобиться. + +Якщо Ви хочете: + +* оголосити параметр запиту `q` без використання `Query` або значення за замовчуванням +* оголосити параметр шляху `item_id`, використовуючи `Path` +* розмістити їх у різному порядку +* не використовувати `Annotated` + +...у Python є спеціальний синтаксис для цього. + +Передайте `*` як перший параметр функції. + +Python нічого не зробить із цією `*`, але розпізнає, що всі наступні параметри слід викликати як аргументи за ключовим словом (пари ключ-значення), також відомі як kwargs. Навіть якщо вони не мають значення за замовчуванням. + +{* ../../docs_src/path_params_numeric_validations/tutorial003.py hl[7] *} + +### Краще з `Annotated` + +Майте на увазі, якщо Ви використовуєте `Annotated`, оскільки Ви не використовуєте значення за замовчуванням для параметрів функції, цієї проблеми не виникне, і, швидше за все, Вам не потрібно буде використовувати `*`. + +{* ../../docs_src/path_params_numeric_validations/tutorial003_an_py39.py hl[10] *} + +## Валідація числових даних: більше або дорівнює + +За допомогою `Query` і `Path` (та інших, які Ви побачите пізніше) можна оголошувати числові обмеження. + +Тут, завдяки `ge=1`, `item_id` має бути цілим числом, яке "`g`reater than or `e`qual" (більше або дорівнює) `1`. + +{* ../../docs_src/path_params_numeric_validations/tutorial004_an_py39.py hl[10] *} + +## Валідація числових даних: більше ніж і менше або дорівнює + +Те саме застосовується до: + +* `gt`: `g`reater `t`han (більше ніж) +* `le`: `l`ess than or `e`qual (менше або дорівнює) + +{* ../../docs_src/path_params_numeric_validations/tutorial005_an_py39.py hl[10] *} + +## Валідація числових даних: float, більше ніж і менше ніж + +Валідація чисел також працює для значень типу `float`. + +Ось де стає важливо мати можливість оголошувати gt, а не тільки ge. Це дозволяє, наприклад, вимагати, щоб значення було більше `0`, навіть якщо воно менше `1`. + +Таким чином, значення `0.5` буде допустимим. Але `0.0` або `0` — ні. + +Те саме стосується lt. + +{* ../../docs_src/path_params_numeric_validations/tutorial006_an_py39.py hl[13] *} + +## Підсумок + +За допомогою `Query`, `Path` (і інших параметрів, які Ви ще не бачили) можна оголошувати метадані та перевірки рядків, так само як у [Query параметри та валідація рядків](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 | Технічні деталі + +Коли Ви імпортуєте `Query`, `Path` та інші з `fastapi`, насправді це функції. + +При виклику вони повертають екземпляри класів з такими ж іменами. + +Тобто Ви імпортуєте `Query`, яка є функцією. А коли Ви її викликаєте, вона повертає екземпляр класу, який теж називається `Query`. + +Ці функції створені таким чином (замість використання класів напряму), щоб Ваш редактор не відзначав їхні типи як помилки. + +Таким чином, Ви можете користуватися своїм звичайним редактором і інструментами для програмування без додаткових налаштувань для ігнорування таких помилок. + +/// diff --git a/docs/uk/docs/tutorial/path-params.md b/docs/uk/docs/tutorial/path-params.md new file mode 100644 index 000000000..e7df1f19a --- /dev/null +++ b/docs/uk/docs/tutorial/path-params.md @@ -0,0 +1,261 @@ +# Path Параметри + +Ви можете визначити "параметри" або "змінні" шляху, використовуючи синтаксис форматованих рядків: + +{* ../../docs_src/path_params/tutorial001.py hl[6:7] *} + +Значення параметра шляху `item_id` передається у функцію як аргумент `item_id`. + +Якщо запустити цей приклад та перейти за посиланням http://127.0.0.1:8000/items/foo, то отримаємо таку відповідь: + +```JSON +{"item_id":"foo"} +``` + +## Path параметри з типами + +Ви можете визначити тип параметра шляху у функції, використовуючи стандартні анотації типів Python: + +{* ../../docs_src/path_params/tutorial002.py hl[7] *} + +У такому випадку `item_id` визначається як `int`. + +/// check | Примітка + +Це дасть можливість підтримки редактора всередині функції з перевірками помилок, автодоповнення тощо. + +/// + +## Перетворення даних + +Якщо запустити цей приклад і перейти за посиланням http://127.0.0.1:8000/items/3, то отримаєте таку відповідь: + +```JSON +{"item_id":3} +``` + +/// check | Примітка + +Зверніть увагу, що значення, яке отримала (і повернула) ваша функція, — це `3`. Це Python `int`, а не рядок `"3"`. + +Отже, з таким оголошенням типу **FastAPI** автоматично виконує "парсинг" запитів. + +/// + +## Перевірка даних + +Якщо ж відкрити у браузері посилання http://127.0.0.1:8000/items/foo, то побачимо цікаву HTTP-помилку: + +```JSON +{ + "detail": [ + { + "type": "int_parsing", + "loc": [ + "path", + "item_id" + ], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "foo", + "url": "https://errors.pydantic.dev/2.1/v/int_parsing" + } + ] +} +``` +тому що параметр шляху має значення `"foo"`, яке не є типом `int`. + +Таку саму помилку отримаємо, якщо передати `float` замість `int`, як бачимо, у цьому прикладі: http://127.0.0.1:8000/items/4.2 + +/// check | Примітка + +Отже, **FastAPI** надає перевірку типів з таким самим оголошенням типу в Python. + +Зверніть увагу, що помилка також чітко вказує саме на те місце, де валідація не пройшла. + +Це неймовірно корисно під час розробки та дебагінгу коду, що взаємодіє з вашим API. + +/// + +## Документація + +Тепер коли відкриєте свій браузер за посиланням http://127.0.0.1:8000/docs, то побачите автоматично згенеровану, інтерактивну API-документацію: + + + +/// check | Примітка + +Знову ж таки, лише з цим самим оголошенням типу в Python, FastAPI надає вам автоматичну, інтерактивну документацію (з інтеграцією Swagger UI). + +Зверніть увагу, що параметр шляху оголошений як ціле число. + + +/// + +## Переваги стандартизації, альтернативна документація + +І оскільки згенерована схема відповідає стандарту OpenAPI, існує багато сумісних інструментів. + +З цієї причини FastAPI також надає альтернативну документацію API (використовуючи ReDoc), до якої можна отримати доступ за посиланням http://127.0.0.1:8000/redoc: + + + +Таким чином, існує багато сумісних інструментів, включаючи інструменти для генерації коду для багатьох мов. + + +## Pydantic + +Вся валідація даних виконується за лаштунками за допомогою Pydantic, тому Ви отримуєте всі переваги від його використання. І можете бути впевнені, що все в надійних руках. + +Ви можете використовувати ті самі оголошення типів з `str`, `float`, `bool` та багатьма іншими складними типами даних. + +Декілька з них будуть розглянуті в наступних розділах посібника. + +## Порядок має значення + +При створенні *операцій шляху* можуть виникати ситуації, коли шлях фіксований. + +Наприклад, `/users/me`. Припустимо, що це шлях для отримання даних про поточного користувача. + +А також у вас може бути шлях `/users/{user_id}`, щоб отримати дані про конкретного користувача за його ID. + +Оскільки *операції шляху* оцінюються по черзі, Ви повинні переконатися, що шлях для `/users/me` оголошений перед шляхом для `/users/{user_id}`: + +{* ../../docs_src/path_params/tutorial003.py hl[6,11] *} + +Інакше шлях для `/users/{user_id}` також буде відповідати для `/users/me`, "вважаючи", що він отримує параметр `user_id` зі значенням `"me"`. + +Аналогічно, Ви не можете оголосити операцію шляху: + +{* ../../docs_src/path_params/tutorial003b.py hl[6,11] *} + +Перша операція буде завжди використовуватися, оскільки шлях збігається першим. +## Попередньо визначені значення + +Якщо у вас є *операція шляху*, яка приймає *параметр шляху*, але Ви хочете, щоб можливі допустимі значення *параметра шляху* були попередньо визначені, Ви можете використати стандартний Python Enum. + +### Створення класу `Enum` + +Імпортуйте `Enum` і створіть підклас, що наслідується від `str` та `Enum`. + +Наслідуючи від `str`, документація API зможе визначити, що значення повинні бути типу `string`, і правильно їх відобразить. + +Після цього створіть атрибути класу з фіксованими значеннями, які будуть доступними допустимими значеннями: + +{* ../../docs_src/path_params/tutorial005.py hl[1,6:9] *} + +/// info | Додаткова інформація + +Перелічення (або enums) доступні в Python починаючи з версії 3.4. + +/// + +/// tip | Порада + +Якщо вам цікаво, "AlexNet", "ResNet" та "LeNet" — це просто назви ML моделей Machine Learning. + +/// + + +### Оголосіть *параметр шляху* + +Потім створіть *параметр шляху* з анотацією типу, використовуючи створений вами клас enum (`ModelName`): + +{* ../../docs_src/path_params/tutorial005.py hl[16] *} + +### Перевірка документації + +Оскільки доступні значення для *параметра шляху* визначені заздалегідь, інтерактивна документація зможе красиво їх відобразити: + + + +### Робота з *перелічуваннями* у Python + +Значення *параметра шляху* буде елементом *перелічування*. + +#### Порівняння *елементів перелічування* + +Ви можете порівнювати його з *елементами перелічування* у створеному вами enum `ModelName`: + +{* ../../docs_src/path_params/tutorial005.py hl[17] *} + +#### Отримання *значення перелічування* + +Ви можете отримати фактичне значення (у цьому випадку це `str`), використовуючи `model_name.value`, або загалом `your_enum_member.value`: + +{* ../../docs_src/path_params/tutorial005.py hl[20] *} + +/// tip | Порада + +Ви також можете отримати доступ до значення `"lenet"`, використовуючи `ModelName.lenet.value`. + +/// + + +#### Повернення *елементів перелічування* + +Ви можете повертати *елементи перелічування* з вашої *операції шляху*, навіть вкладені у JSON-тіло (наприклад, `dict`). + +Вони будуть перетворені на відповідні значення (у цьому випадку рядки) перед поверненням клієнту: + +{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *} + +На стороні клієнта Ви отримаєте відповідь у форматі JSON, наприклад: + +```JSON +{ + "model_name": "alexnet", + "message": "Deep Learning FTW!" +} +``` + +## Path-параметри, що містять шляхи + +Припустимо, у вас є *операція шляху* з маршрутом `/files/{file_path}`. + +Але вам потрібно, щоб `file_path` містив *шлях*, наприклад `home/johndoe/myfile.txt`. + +Отже, URL для цього файлу виглядатиме так: `/files/home/johndoe/myfile.txt`. + + + +### Підтримка OpenAPI + +OpenAPI не підтримує спосіб оголошення *параметра шляху*, що містить *шлях* всередині, оскільки це може призвести до сценаріїв, які складно тестувати та визначати. + +Однак (одначе), Ви все одно можете зробити це в **FastAPI**, використовуючи один із внутрішніх інструментів Starlette. + +Документація все ще працюватиме, хоча й не додаватиме опису про те, що параметр повинен містити шлях. + +### Конвертер шляху + +Використовуючи опцію безпосередньо зі Starlette, Ви можете оголосити *параметр шляху*, що містить *шлях*, використовуючи URL на кшталт: + +``` +/files/{file_path:path} +``` +У цьому випадку ім'я параметра — `file_path`, а остання частина `:path` вказує на те, що параметр повинен відповідати будь-якому *шляху*. + +Отже, Ви можете використати його так: + +{* ../../docs_src/path_params/tutorial004.py hl[6] *} + +/// tip | Порада + +Вам може знадобитися, щоб параметр містив `/home/johndoe/myfile.txt` із початковою косою рискою (`/`). + +У такому випадку URL виглядатиме так: `/files//home/johndoe/myfile.txt`, із подвійною косою рискою (`//`) між `files` і `home`. + +/// + +## Підсумок + +З **FastAPI**, використовуючи короткі, інтуїтивно зрозумілі та стандартні оголошення типів Python, Ви отримуєте: + +* Підтримку в редакторі: перевірка помилок, автодоповнення тощо. +* "Парсинг" даних +* Валідацію даних +* Анотацію API та автоматичну документацію + +І вам потрібно оголосити їх лише один раз. + +Це, ймовірно, основна видима перевага **FastAPI** порівняно з альтернативними фреймворками (окрім високої продуктивності). diff --git a/docs/uk/docs/tutorial/query-params-str-validations.md b/docs/uk/docs/tutorial/query-params-str-validations.md new file mode 100644 index 000000000..cd3f4ad93 --- /dev/null +++ b/docs/uk/docs/tutorial/query-params-str-validations.md @@ -0,0 +1,491 @@ +# Query параметри та валідація рядків + +**FastAPI** дозволяє оголошувати додаткову інформацію та виконувати валідацію для Ваших параметрів. + +Розглянемо цей додаток як приклад: + +{* ../../docs_src/query_params_str_validations/tutorial001_py310.py hl[7] *} + +Query параметр `q` має тип `str | None`, що означає, що він може бути як `str`, так і `None`. За замовчуванням він має значення `None`, тому FastAPI розуміє, що цей параметр не є обов'язковим. + +/// note | Примітка + +FastAPI знає, що `q` не є обов’язковим, завдяки значенню за замовчуванням `= None`. + +Використання `str | None` дозволить Вашому редактору коду надавати кращу підтримку та виявляти помилки. + +/// + +## Додаткова валідація + +Ми хочемо, щоб навіть якщо `q` є необов’язковим, **його довжина не перевищувала 50 символів**, якщо він все ж буде переданий. + +### Імпорт `Query` та `Annotated` + +Щоб це зробити, спочатку імпортуємо: + +* `Query` з `fastapi` +* `Annotated` з `typing` + +{* ../../docs_src/query_params_str_validations/tutorial002_an_py310.py hl[1,3] *} + +/// info | Інформація + +FastAPI додав підтримку `Annotated` (і почав рекомендувати його) у версії 0.95.0. + +Якщо у Вас старіша версія, під час використання `Annotated` можуть виникати помилки. + +Переконайтеся, що Ви [оновили версію FastAPI](../deployment/versions.md#upgrading-the-fastapi-versions){.internal-link target=_blank} до принаймні 0.95.1, перш ніж використовувати `Annotated`. + +/// + +## Використання `Annotated` у типі параметра `q` + +Пам’ятаєте, як я раніше розповідав, що `Annotated` можна використовувати для додавання метаданих до параметрів у [Вступі до типів Python](../python-types.md#type-hints-with-metadata-annotations){.internal-link target=_blank}? + +Зараз саме час використати його разом із FastAPI. 🚀 + +Раніше ми мали таку анотацію типу: + +//// tab | Python 3.10+ + +```Python +q: str | None = None +``` + +//// + +//// tab | Python 3.8+ + +```Python +q: Union[str, None] = None +``` + +//// + +Тепер ми загорнемо її у `Annotated`, і отримаємо: + +//// tab | Python 3.10+ + +```Python +q: Annotated[str | None] = None +``` + +//// + +//// tab | Python 3.8+ + +```Python +q: Annotated[Union[str, None]] = None +``` + +//// + +Обидві ці версії означають одне й те саме: `q` — це параметр, який може бути `str` або `None`, і за замовчуванням має значення `None`. + +А тепер переходимо до цікавого! 🎉 + +## Додавання `Query` до `Annotated` у параметр `q` + +Тепер, коли у нас є `Annotated`, де ми можемо додавати додаткову інформацію (зокрема валідацію), додамо `Query` всередину `Annotated` і встановимо параметр `max_length` у `50`: + +{* ../../docs_src/query_params_str_validations/tutorial002_an_py310.py hl[9] *} + +Зверніть увагу, що значення за замовчуванням усе ще `None`, тому параметр залишається необов'язковим. + +Але тепер, додавши `Query(max_length=50)` всередину `Annotated`, ми повідомляємо FastAPI, що хочемо **додаткову валідацію** для цього значення — воно має містити максимум 50 символів. 😎 + +/// tip | Підказка + +Ми використовуємо `Query()`, оскільки це **query параметр**. Далі ми розглянемо інші варіанти, як-от `Path()`, `Body()`, `Header()` та `Cookie()`, які приймають ті самі аргументи, що й `Query()`. + +/// + +Тепер FastAPI: + +* **Перевірить** дані, щоб переконатися, що їхня довжина не перевищує 50 символів +* Покажe **чітку помилку** клієнту, якщо дані недійсні +* **Задокументує** параметр в OpenAPI-схемі *операції шляху* (що відобразиться в **автоматично згенерованій документації**) + +## Альтернативний (застарілий) метод: Query як значення за замовчуванням + +У попередніх версіях FastAPI (до 0.95.0) `Query` використовувався як значення за замовчуванням для параметра, а не всередині `Annotated`. Ви, ймовірно, побачите код, який використовує цей підхід, тому варто розглянути його. + +/// tip | Підказка + +Для нового коду та коли це можливо, використовуйте `Annotated`, як показано вище. Це має багато переваг (пояснених нижче) і не має недоліків. 🍰 + +/// + +Раніше ми писали `Query()` як значення за замовчуванням для параметра функції, встановлюючи `max_length` у 50: + +{* ../../docs_src/query_params_str_validations/tutorial002_py310.py hl[7] *} + +Оскільки в цьому випадку (без `Annotated`) нам потрібно замінити `None` у функції на `Query()`, тепер ми повинні явно встановити значення за замовчуванням через параметр `Query(default=None)`. Це виконує ту саму роль визначення значення за замовчуванням (принаймні для FastAPI). + +Таким чином: + +```Python +q: str | None = Query(default=None) +``` + +...робить параметр необов’язковим зі значенням за замовчуванням `None`, що еквівалентно: + + +```Python +q: str | None = None +``` +Але у версії з `Query` ми явно вказуємо, що це query параметр. + +Далі ми можемо передавати `Query` додаткові параметри, зокрема `max_length`, який застосовується до рядків: + +```Python +q: str | None = Query(default=None, max_length=50) +``` + +Це забезпечить валідацію даних, виведе зрозумілу помилку у разі недійсних даних і задокументує параметр у схемі OpenAPI *операції шляху*. + +### `Query` як значення за замовчуванням або всередині `Annotated` + +Важливо пам’ятати, якщо використовувати `Query` всередині `Annotated`, не можна задавати параметр `default` у `Query`. + +Замість цього використовуйте значення за замовчуванням у самій функції. Інакше це буде нелогічно. + +Наприклад, цей варіант є некоректним: + +```Python +q: Annotated[str, Query(default="rick")] = "morty" +``` + +...тому, що не зрозуміло, яке значення має бути значенням за замовчуванням: `"rick"` чи `"morty"`. + +Коректні варіанти: + +```Python +q: Annotated[str, Query()] = "rick" +``` + +...або у старих кодових базах Ви знайдете: + +```Python +q: str = Query(default="rick") +``` + +### Переваги використання `Annotated` + +**Використання `Annotated` є рекомендованим** замість задання значення за замовчуванням у параметрах функції, оскільки воно **краще** з кількох причин. 🤓 + +Значення **за замовчуванням** параметра **функції** є його **фактичним значенням за замовчуванням**, що є більш інтуїтивним у Python загалом. 😌 + +Ви можете **викликати** ту саму функцію **в інших місцях** без FastAPI, і вона **працюватиме очікувано**. Якщо параметр є **обов’язковим** (без значення за замовчуванням), Ваш **редактор** повідомить про помилку, а **Python** також видасть помилку, якщо Ви виконаєте функцію без передавання цього параметра. + +Якщо Ви не використовуєте `Annotated`, а використовуєте **(старий) стиль значень за замовчуванням**, то при виклику цієї функції без FastAPI **в інших місцях**, потрібно **не забути** передати їй аргументи, інакше значення будуть відрізнятися від очікуваних (наприклад, Ви отримаєте `QueryInfo` або подібне замість `str`). Ваш редактор не повідомить про помилку, і Python також не видасть помилку при запуску функції, поки не виникне помилка під час виконання операцій усередині. + +Оскільки `Annotated` може містити кілька анотацій метаданих, Ви навіть можете використовувати ту саму функцію з іншими інструментами, такими як Typer. 🚀 + +## Додавання додаткових валідацій + +Ви також можете додати параметр `min_length`: + +{* ../../docs_src/query_params_str_validations/tutorial003_an_py310.py hl[10] *} + +## Додавання регулярних виразів + +Ви можете визначити регулярний вираз pattern, якому має відповідати параметр: + +{* ../../docs_src/query_params_str_validations/tutorial004_an_py310.py hl[11] *} + +Цей конкретний шаблон регулярного виразу перевіряє, що отримане значення параметра: + +* `^`: починається з наступних символів, перед якими немає інших символів. +* `fixedquery`: точно відповідає значенню `fixedquery`. +* `$`: закінчується тут, після `fixedquery` немає жодних символів. + +Якщо Ви почуваєтеся розгублено щодо **"регулярних виразів"**, не хвилюйтеся. Вони є складною темою для багатьох людей. Ви все одно можете зробити багато речей без їх використання. + +Але тепер Ви знаєте, що коли вони знадобляться, їх можна застосовувати у **FastAPI**. + +### Pydantic v1 `regex` замість `pattern` + +До версії Pydantic 2 і FastAPI 0.100.0 параметр називався `regex` замість `pattern`, але тепер він застарів. + +Ви все ще можете зустріти код, який використовує його: + +//// tab | Pydantic v1 + +{* ../../docs_src/query_params_str_validations/tutorial004_regex_an_py310.py hl[11] *} + +//// + +Але майте на увазі, що він є застарілим і його слід оновити до нового параметра `pattern`. 🤓 + +## Значення за замовчуванням + +Ви можете використовувати значення за замовчуванням, відмінні від `None`. + +Наприклад, якщо Ви хочете оголосити параметр запиту `q` з `min_length` `3` і значенням за замовчуванням `"fixedquery"`: + +{* ../../docs_src/query_params_str_validations/tutorial005_an_py39.py hl[9] *} + +/// note | Технічні деталі + +Наявність значення за замовчуванням будь-якого типу, включаючи `None`, робить параметр необов’язковим (not required). + +/// + +## Обов’язкові параметри + +Якщо нам не потрібно вказувати додаткові перевірки або метадані, ми можемо зробити параметр `q` обов’язковим, просто не оголошуючи значення за замовчуванням, наприклад: + +```Python +q: str +``` + +замість: + +```Python +q: str | None = None +``` + +Але тепер ми оголошуємо його з `Query`, наприклад: + +//// tab | Annotated + +```Python +q: Annotated[str | None, Query(min_length=3)] = None +``` + +//// + +Тому, якщо Вам потрібно зробити значення обов’язковим, використовуючи `Query`, просто не вказуйте значення за замовчуванням: + +{* ../../docs_src/query_params_str_validations/tutorial006_an_py39.py hl[9] *} + +### Обов’язкове значення, яке може бути `None` + +Ви можете вказати, що параметр може приймати `None`, але при цьому залишається обов’язковим. Це змусить клієнтів надіслати значення, навіть якщо воно дорівнює `None`. + +Щоб зробити це, оголосіть, що `None` є допустимим типом, але не вказуйте значення за замовчуванням: + +{* ../../docs_src/query_params_str_validations/tutorial006c_an_py310.py hl[9] *} + +## Список параметрів запиту / кілька значень + +Якщо Ви визначаєте параметр запиту за допомогою `Query`, Ви також можете дозволити отримання списку значень, тобто дозволити отримання кількох значень. + +Наприклад, щоб дозволити параметру запиту `q` з'являтися кілька разів в URL, можна написати: + +{* ../../docs_src/query_params_str_validations/tutorial011_an_py310.py hl[9] *} + +Тоді, у випадку запиту за URL: + +``` +http://localhost:8000/items/?q=foo&q=bar +``` + +Ви отримаєте кілька значень *query параметра* `q` (`foo` і `bar`) у вигляді списку `list` в Python у Вашій *функції обробки шляху*, у *параметрі функції* `q`. + +Отже, відповідь на цей URL буде: + +```JSON +{ + "q": [ + "foo", + "bar" + ] +} +``` + +/// tip | Підказка + +Щоб оголосити параметр запиту з типом `list`, як у наведеному вище прикладі, потрібно явно використовувати `Query`, інакше він буде інтерпретований як тіло запиту. + +/// + +Інтерактивна API-документація оновиться відповідно, дозволяючи передавати кілька значень: + + + +### Список параметрів запиту / кілька значень за замовчуванням + +Ви також можете визначити значення за замовчуванням для `list`, якщо жодне значення не було передане: + +{* ../../docs_src/query_params_str_validations/tutorial012_an_py39.py hl[9] *} + +Якщо Ви перейдете за посиланням: + +``` +http://localhost:8000/items/ +``` + +то значення `q` за замовчуванням буде: `["foo", "bar"]`, і Ваша відповідь виглядатиме так: + +```JSON +{ + "q": [ + "foo", + "bar" + ] +} +``` + +#### Використання тільки `list` + +Ви також можете використовувати `list` без уточнення типу, замість `list[str]`: + +{* ../../docs_src/query_params_str_validations/tutorial013_an_py39.py hl[9] *} + +/// note | Технічні деталі + +Майте на увазі, що в цьому випадку FastAPI не перевірятиме вміст списку. + +Наприклад, `list[int]` перевірятиме (і документуватиме), що всі елементи списку є цілими числами. Але `list` без уточнення цього не робитиме. + +/// + +## Додавання додаткових метаданих + +Ви можете додати більше інформації про параметр. + +Ця інформація буде включена у згенерований OpenAPI та використана в інтерфейсах документації та зовнішніх інструментах. + +/// note | Технічні деталі + +Майте на увазі, що різні інструменти можуть мати різний рівень підтримки OpenAPI. + +Деякі з них можуть ще не відображати всю додаткову інформацію, хоча в більшості випадків ця функція вже запланована для розробки. + +/// + +Ви можете додати `title` : + +{* ../../docs_src/query_params_str_validations/tutorial007_an_py310.py hl[10] *} + +А також `description`: + +{* ../../docs_src/query_params_str_validations/tutorial008_an_py310.py hl[14] *} + +## Аліаси параметрів + +Уявіть, що Ви хочете, щоб параметр називався `item-query`. + +Наприклад: + +``` +http://127.0.0.1:8000/items/?item-query=foobaritems +``` + +Але `item-query` — це некоректна назва змінної в Python. + +Найближчий допустимий варіант — `item_query`. + +Проте Вам потрібно, щоб параметр залишався саме `item-query`... + +У такому випадку можна оголосити `alias`, і саме він буде використовуватися для отримання значення параметра: + +{* ../../docs_src/query_params_str_validations/tutorial009_an_py310.py hl[9] *} + +## Виведення параметрів як застарілих + +Припустимо, що Ви більше не хочете використовувати цей параметр. + +Вам потрібно залишити його на деякий час, оскільки ним користуються клієнти, але Ви хочете, щоб документація чітко показувала, що він є застарілим. + +Тоді Ви можете передати параметр `deprecated=True` до `Query`: + +{* ../../docs_src/query_params_str_validations/tutorial010_an_py310.py hl[19] *} + +Документація буде показувати це таким чином: + + + +## Виняток параметрів з OpenAPI + +Щоб виключити параметр запиту зі згенерованої схеми OpenAPI (і, таким чином, з автоматичних систем документації), встановіть параметр `include_in_schema` для `Query` в `False`: + +{* ../../docs_src/query_params_str_validations/tutorial014_an_py310.py hl[10] *} + +## Кастомна валідація + +Можуть бути випадки, коли Вам потрібно провести **кастомну валідацію**, яку не можна реалізувати за допомогою параметрів, показаних вище. + +У таких випадках ви можете використати **кастомну функцію валідації**, яка буде застосована після звичайної валідації (наприклад, після перевірки, що значення є типом `str`). + +Це можна досягти за допомогою Pydantic's `AfterValidator` в середині `Annotated`. + +/// tip | Підказка + +Pydantic також має `BeforeValidator` та інші. 🤓 + +/// + +Наприклад, цей кастомний валідатор перевіряє, чи починається ID елемента з `isbn-` для номера книги ISBN або з `imdb-` для ID URL фільму на IMDB: + +{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py hl[5,16:19,24] *} + +/// info | Інформація + +Це доступно з версії Pydantic 2 або вище. 😎 + +/// + +/// tip | Підказка + +Якщо Вам потрібно виконати будь-яку валідацію, яка вимагає взаємодії з будь-яким **зовнішнім компонентом**, таким як база даних чи інший API, ви повинні замість цього використовувати **FastAPI Dependencies**. Ви дізнаєтесь про них пізніше. + +Ці кастомні валідатори використовуються для речей, які можна перевірити лише з **тими даними**, що надані в запиті. + +/// + +### Зрозумійте цей код + +Головний момент – це використання **`AfterValidator` з функцією всередині `Annotated`**. Можете пропустити цю частину, якщо хочете. 🤸 + +--- + +Але якщо Вам цікаво розібратися в цьому конкретному прикладі коду і Вам ще не набридло, ось кілька додаткових деталей. + +#### Рядок із `value.startswith()` + +Звернули увагу? Рядок із `value.startswith()` може приймати кортеж, і тоді він перевірятиме кожне значення в кортежі: + +{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[16:19] hl[17] *} + +#### Випадковий елемент + +За допомогою `data.items()` ми отримуємо ітерабельний об'єкт із кортежами, що містять ключ і значення для кожного елемента словника. + +Ми перетворюємо цей ітерабельний об'єкт у звичайний `list` за допомогою `list(data.items())`. + +Потім, використовуючи `random.choice()`, ми можемо отримати випадкове значення зі списку, тобто отримуємо кортеж із `(id, name)`. Це може бути щось на зразок `("imdb-tt0371724", "The Hitchhiker's Guide to the Galaxy")`. + +Далі ми **присвоюємо ці два значення** кортежу змінним `id` і `name`. + +Тож, якщо користувач не вказав ID елемента, він все одно отримає випадкову рекомендацію. + +...і все це реалізовано в **одному рядку коду**. 🤯 Хіба не прекрасний Python? 🐍 + +{* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py ln[22:30] hl[29] *} + +## Підсумок + +Ви можете оголошувати додаткові валідації та метаінформацію для своїх параметрів. + +Загальні валідації та метаінформація: + +* `alias` +* `title` +* `description` +* `deprecated` + +Валідації, специфічні для рядків: + +* `min_length` +* `max_length` +* `pattern` + +Кастомні валідації за допомогою `AfterValidator`. + +У цих прикладах Ви побачили, як оголошувати валідації для значень `str`. + +Дивіться наступні розділи, щоб дізнатися, як оголошувати валідації для інших типів, наприклад чисел. diff --git a/docs/uk/docs/tutorial/query-params.md b/docs/uk/docs/tutorial/query-params.md new file mode 100644 index 000000000..16bb42af3 --- /dev/null +++ b/docs/uk/docs/tutorial/query-params.md @@ -0,0 +1,192 @@ +# Query Параметри + +Коли Ви оголошуєте інші параметри функції, які не є частиною параметрів шляху, вони автоматично інтерпретуються як "query" параметри. + +{* ../../docs_src/query_params/tutorial001.py hl[9] *} + +Query параметри — це набір пар ключ-значення, що йдуть після символу `?` в URL, розділені символами `&`. + +Наприклад, в URL: + +``` +http://127.0.0.1:8000/items/?skip=0&limit=10 +``` + +...query параметрами є: + +* `skip`: зі значенням `0` +* `limit`: зі значенням `10` + +Оскільки вони є частиною URL, вони "за замовчуванням" є рядками. + +Але коли Ви оголошуєте їх із типами Python (у наведеному прикладі як `int`), вони перетворюються на цей тип і проходять перевірку відповідності. + +Увесь той самий процес, який застосовується до параметрів шляху, також застосовується до query параметрів: + +* Підтримка в редакторі (автодоповнення, перевірка помилок) +* "Парсинг" даних +* Валідація даних +* Автоматична документація + + +## Значення за замовчуванням + +Оскільки query параметри не є фіксованою частиною шляху, вони можуть бути необов’язковими та мати значення за замовчуванням. + +У наведеному вище прикладі вони мають значення за замовчуванням: `skip=0` і `limit=10`. + +Отже, результат переходу за URL: + +``` +http://127.0.0.1:8000/items/ +``` +буде таким самим, як і перехід за посиланням: + +``` +http://127.0.0.1:8000/items/?skip=0&limit=10 +``` + +Але якщо Ви перейдете, наприклад, за посиланням: + +``` +http://127.0.0.1:8000/items/?skip=20 +``` + +Значення параметрів у вашій функції будуть такими: + +* `skip=20`: оскільки Ви вказали його в URL +* `limit=10`: оскільки це значення за замовчуванням + +## Необов'язкові параметри + +Аналогічно, Ви можете оголосити необов’язкові query параметри, встановивши для них значення за замовчуванням `None`: + +{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *} + +У цьому випадку параметр функції `q` буде необов’язковим і за замовчуванням матиме значення `None`. + +/// check | Примітка + +Також зверніть увагу, що **FastAPI** достатньо розумний, щоб визначити, що параметр шляху `item_id` є параметром шляху, а `q` — ні, отже, це query параметр. + +/// + +## Перетворення типу Query параметра + +Ви також можете оголошувати параметри типу `bool`, і вони будуть автоматично конвертовані: + +{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *} + +У цьому випадку, якщо Ви звернетесь до: + + +``` +http://127.0.0.1:8000/items/foo?short=1 +``` + +або + +``` +http://127.0.0.1:8000/items/foo?short=True +``` + +або + +``` +http://127.0.0.1:8000/items/foo?short=true +``` + +або + +``` +http://127.0.0.1:8000/items/foo?short=on +``` + +або + +``` +http://127.0.0.1:8000/items/foo?short=yes +``` + +або будь-який інший варіант написання (великі літери, перша літера велика тощо), ваша функція побачить параметр `short` зі значенням `True` з типом даних `bool`. В іншому випадку – `False`. + +## Кілька path і query параметрів + +Ви можете одночасно оголошувати кілька path і query параметрів, і **FastAPI** автоматично визначить, який з них до чого належить. + + +Не потрібно дотримуватись певного порядку їх оголошення. + +Вони визначаються за назвою: + +{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *} + +## Обов’язкові Query параметри + +Якщо Ви оголошуєте значення за замовчуванням для параметрів, які не є path-параметрами (у цьому розділі ми бачили поки що лише path параметри), тоді вони стають необов’язковими. + +Якщо Ви не хочете вказувати конкретні значення, але хочете зробити параметр опціональним, задайте `None` як значення за замовчуванням. + +Але якщо Ви хочете зробити query параметр обов’язковим, просто не вказуйте для нього значення за замовчуванням: + +{* ../../docs_src/query_params/tutorial005.py hl[6:7] *} + +Тут `needy` – обов’язковий query параметр типу `str`. + +Якщо Ви відкриєте у браузері URL-адресу: + +``` +http://127.0.0.1:8000/items/foo-item +``` + +...без додавання обов’язкового параметра `needy`, Ви побачите помилку: + +```JSON +{ + "detail": [ + { + "type": "missing", + "loc": [ + "query", + "needy" + ], + "msg": "Field required", + "input": null, + "url": "https://errors.pydantic.dev/2.1/v/missing" + } + ] +} +``` + +Оскільки `needy` є обов’язковим параметром, вам потрібно вказати його в URL: + +``` +http://127.0.0.1:8000/items/foo-item?needy=sooooneedy +``` + +...цей запит поверне: + +```JSON +{ + "item_id": "foo-item", + "needy": "sooooneedy" +} +``` + + +Звичайно, Ви можете визначити деякі параметри як обов’язкові, інші зі значенням за замовчуванням, а ще деякі — повністю опціональні: + +{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *} + +У цьому випадку є 3 query параметри: + +* `needy`, обов’язковий `str`. +* `skip`, `int` зі значенням за замовчуванням `0`. +* `limit`, опціональний `int`. + + +/// tip | Підказка + +Ви також можете використовувати `Enum`-и, так само як і з [Path Parameters](path-params.md#predefined-values){.internal-link target=_blank}. + +/// diff --git a/docs/uk/docs/tutorial/request-files.md b/docs/uk/docs/tutorial/request-files.md new file mode 100644 index 000000000..18b7cc01c --- /dev/null +++ b/docs/uk/docs/tutorial/request-files.md @@ -0,0 +1,175 @@ +# Запит файлів + +Ви можете визначити файли, які будуть завантажуватися клієнтом, використовуючи `File`. + +/// info | Інформація + +Щоб отримувати завантажені файли, спочатку встановіть python-multipart. + +Переконайтеся, що Ви створили [віртуальне середовище](../virtual-environments.md){.internal-link target=_blank}, активували його та встановили пакет, наприклад: + +```console +$ pip install python-multipart +``` + +Це необхідно, оскільки завантажені файли передаються у вигляді "форматованих даних форми". + +/// + +## Імпорт `File` + +Імпортуйте `File` та `UploadFile` з `fastapi`: + +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[3] *} + +## Визначення параметрів `File` + +Створіть параметри файлів так само як Ви б створювали `Body` або `Form`: + +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[9] *} + +/// info | Інформація + +`File` — це клас, який безпосередньо успадковує `Form`. + +Але пам’ятайте, що коли Ви імпортуєте `Query`, `Path`, `File` та інші з `fastapi`, це насправді функції, які повертають спеціальні класи. + +/// + +/// tip | Підказка + +Щоб оголосити тіла файлів, Вам потрібно використовувати `File`, тому що інакше параметри будуть інтерпретовані як параметри запиту або параметри тіла (JSON). + +/// + +Файли будуть завантажені у вигляді "форматованих даних форми". + +Якщо Ви оголосите тип параметра функції обробника маршруту як `bytes`, **FastAPI** прочитає файл за Вас, і Ви отримаєте його вміст у вигляді `bytes`. + +Однак майте на увазі, що весь вміст буде збережено в пам'яті. Це працюватиме добре для малих файлів. + +Але в деяких випадках Вам може знадобитися `UploadFile`. + +## Параметри файлу з `UploadFile` + +Визначте параметр файлу з типом `UploadFile`: + +{* ../../docs_src/request_files/tutorial001_an_py39.py hl[14] *} + +Використання `UploadFile` має кілька переваг перед `bytes`: + +* Вам не потрібно використовувати `File()` у значенні за замовчуванням параметра. +* Використовується "буферизований" файл: + * Файл зберігається в пам'яті до досягнення певного обмеження, після чого він записується на диск. +* Це означає, що він добре працює для великих файлів, таких як зображення, відео, великі двійкові файли тощо, не споживаючи всю пам'ять. +Ви можете отримати метадані про завантажений файл. +* Він має file-like `асинхронний файловий інтерфейс` interface. +* Він надає фактичний об'єкт Python `SpooledTemporaryFile`, який можна передавати безпосередньо іншим бібліотекам. + +### `UploadFile` + +`UploadFile` має такі атрибути: + +* `filename`: Рядок `str` з оригінальною назвою файлу, який був завантажений (наприклад, `myimage.jpg`). +* `content_type`: Рядок `str` з MIME-типом (наприклад, `image/jpeg`). +* `file`: Об'єкт SpooledTemporaryFile (файлоподібний об'єкт). Це фактичний файловий об'єкт Python, який можна безпосередньо передавати іншим функціям або бібліотекам, що очікують "файлоподібний" об'єкт. + +`UploadFile` має такі асинхронні `async` методи. Вони викликають відповідні методи файлу під капотом (використовуючи внутрішній `SpooledTemporaryFile`). + +* `write(data)`: Записує `data` (`str` або `bytes`) у файл. +* `read(size)`: Читає `size` (`int`) байтів/символів з файлу. +* `seek(offset)`: Переміщується до позиції `offset` (`int`) у файлі. + * Наприклад, `await myfile.seek(0)` поверне курсор на початок файлу. + * This is especially useful if you run `await myfile.read()` once and then need to read the contents again. Це особливо корисно, якщо Ви виконуєте await `await myfile.read()` один раз, а потім потрібно знову прочитати вміст. +* `close()`: Закриває файл. + +Оскільки всі ці методи є асинхронними `async`, Вам потрібно використовувати "await": + +Наприклад, всередині `async` *функції обробки шляху* Ви можете отримати вміст за допомогою: + +```Python +contents = await myfile.read() +``` +Якщо Ви знаходитесь у звичайній `def` *функції обробки шляху*, Ви можете отримати доступ до `UploadFile.file` безпосередньо, наприклад: + +```Python +contents = myfile.file.read() +``` + +/// note | Технічні деталі `async` + +Коли Ви використовуєте `async` методи, **FastAPI** виконує файлові операції у пулі потоків та очікує їх завершення. + +/// + +/// note | Технічні деталі Starlette + +`UploadFile` у **FastAPI** успадковується безпосередньо від `UploadFile` у **Starlette**, але додає деякі необхідні частини, щоб зробити його сумісним із **Pydantic** та іншими компонентами FastAPI. + +/// + +## Що таке "Form Data" + +Спосіб, у який HTML-форми (`
`) надсилають дані на сервер, зазвичай використовує "спеціальне" кодування, відмінне від JSON. + +**FastAPI** забезпечує правильне зчитування цих даних з відповідної частини запиту, а не з JSON. + +/// note | Технічні деталі + +Дані з форм зазвичай кодуються за допомогою "media type" `application/x-www-form-urlencoded`, якщо вони не містять файлів. + +Але якщо форма містить файли, вона кодується у форматі `multipart/form-data`. Якщо Ви використовуєте `File`, **FastAPI** визначить, що потрібно отримати файли з відповідної частини тіла запиту. + +Щоб дізнатися більше про ці типи кодування та формові поля, ознайомтеся з документацією MDN щодо POST. + +/// + +/// warning | Увага + +Ви можете оголосити кілька параметрів `File` і `Form` в *операції шляху*, але Ви не можете одночасно оголошувати поля `Body`, які мають надходити у форматі JSON, оскільки тіло запиту буде закодоване у форматі `multipart/form-data`, а не `application/json`. + +Це не обмеження **FastAPI**, а особливість протоколу HTTP. + +/// + +## Опціональне Завантаження Файлів + +Файл можна зробити необов’язковим, використовуючи стандартні анотації типів і встановлюючи значення за замовчуванням `None`: + +{* ../../docs_src/request_files/tutorial001_02_an_py310.py hl[9,17] *} + +## `UploadFile` із Додатковими Мета Даними + +Ви також можете використовувати `File()` разом із `UploadFile`, наприклад, для встановлення додаткових метаданих: + +{* ../../docs_src/request_files/tutorial001_03_an_py39.py hl[9,15] *} + +## Завантаження Кількох Файлів + +Можна завантажувати кілька файлів одночасно. + +Вони будуть пов’язані з одним і тим самим "form field", який передається у вигляді "form data". + +Щоб це реалізувати, потрібно оголосити список `bytes` або `UploadFile`: + +{* ../../docs_src/request_files/tutorial002_an_py39.py hl[10,15] *} + +Ви отримаєте, як і було оголошено, `list` із `bytes` або `UploadFile`. + +/// note | Технічні деталі + +Ви також можете використати `from starlette.responses import HTMLResponse`. + +**FastAPI** надає ті ж самі `starlette.responses`, що й `fastapi.responses`, для зручності розробників. Однак більшість доступних відповідей надходять безпосередньо від Starlette. + +/// + +### Завантаження декількох файлів із додатковими метаданими + +Так само як і раніше, Ви можете використовувати `File()`, щоб встановити додаткові параметри навіть для `UploadFile`: + +{* ../../docs_src/request_files/tutorial003_an_py39.py hl[11,18:20] *} + +## Підсумок + +Використовуйте `File`, `bytes`та `UploadFile`, щоб оголошувати файли для завантаження у запитах, які надсилаються у вигляді form data. diff --git a/docs/uk/docs/tutorial/request-form-models.md b/docs/uk/docs/tutorial/request-form-models.md new file mode 100644 index 000000000..7f5759e79 --- /dev/null +++ b/docs/uk/docs/tutorial/request-form-models.md @@ -0,0 +1,78 @@ +# Моделі форм (Form Models) + +У FastAPI Ви можете використовувати **Pydantic-моделі** для оголошення **полів форми**. + +/// info | Інформація + +Щоб використовувати форми, спочатку встановіть python-multipart. + +Переконайтеся, що Ви створили [віртуальне середовище](../virtual-environments.md){.internal-link target=_blank}, активували його, а потім встановили бібліотеку, наприклад: + +```console +$ pip install python-multipart +``` + +/// + +/// note | Підказка + +Ця функція підтримується, починаючи з FastAPI версії `0.113.0`. 🤓 + +/// + +## Використання Pydantic-моделей для форм + +Вам просто потрібно оголосити **Pydantic-модель** з полями, які Ви хочете отримати як **поля форми**, а потім оголосити параметр як `Form`: + +{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *} + +**FastAPI** **витягне** дані для **кожного поля** з **формових даних** у запиті та надасть вам Pydantic-модель, яку Ви визначили. + +## Перевірка документації + +Ви можете перевірити це в UI документації за `/docs`: + +
+ +
+ +## Заборона додаткових полів форми + +У деяких особливих випадках (ймовірно, рідко) Ви можете **обмежити** форму лише тими полями, які були оголошені в Pydantic-моделі, і **заборонити** будь-які **додаткові** поля. + +/// note | Підказка + +Ця функція підтримується, починаючи з FastAPI версії `0.114.0`. 🤓 + +/// + +Ви можете використати конфігурацію Pydantic-моделі, щоб заборонити `forbid` будь-які додаткові `extra` поля: + +{* ../../docs_src/request_form_models/tutorial002_an_py39.py hl[12] *} + +Якщо клієнт спробує надіслати додаткові дані, він отримає **відповідь з помилкою**. + +Наприклад, якщо клієнт спробує надіслати наступні поля форми: + +* `username`: `Rick` +* `password`: `Portal Gun` +* `extra`: `Mr. Poopybutthole` + +Він отримає відповідь із помилкою, яка повідомляє, що поле `extra` не дозволено: + +```json +{ + "detail": [ + { + "type": "extra_forbidden", + "loc": ["body", "extra"], + "msg": "Extra inputs are not permitted", + "input": "Mr. Poopybutthole" + } + ] +} +``` + +## Підсумок + +Ви можете використовувати Pydantic-моделі для оголошення полів форми у FastAPI. 😎 diff --git a/docs/uk/docs/tutorial/request-forms-and-files.md b/docs/uk/docs/tutorial/request-forms-and-files.md new file mode 100644 index 000000000..a089ef945 --- /dev/null +++ b/docs/uk/docs/tutorial/request-forms-and-files.md @@ -0,0 +1,41 @@ +# Запити з формами та файлами + +У FastAPI Ви можете одночасно отримувати файли та поля форми, використовуючи `File` і `Form`. + +/// info | Інформація + +Щоб отримувати завантажені файли та/або дані форми, спочатку встановіть python-multipart. + +Переконайтеся, що Ви створили [віртуальне середовище](../virtual-environments.md){.internal-link target=_blank}, активували його, а потім встановили бібліотеку, наприклад: + +```console +$ pip install python-multipart +``` + +/// + +## Імпорт `File` та `Form` + +{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[3] *} + +## Оголошення параметрів `File` та `Form` + +Створіть параметри файлів та форми так само як і для `Body` або `Query`: + +{* ../../docs_src/request_forms_and_files/tutorial001_an_py39.py hl[10:12] *} + +Файли та поля форми будуть завантажені як формові дані, і Ви отримаєте як файли, так і введені користувачем поля. + +Ви також можете оголосити деякі файли як `bytes`, а деякі як `UploadFile`. + +/// warning | Увага + +Ви можете оголосити кілька параметрів `File` і `Form` в операції *шляху*, але не можете одночасно оголошувати `Body`-поля, які очікуєте отримати у форматі JSON, оскільки запит матиме тіло, закодоване за допомогою `multipart/form-data`, а не `application/json`. + +Це не обмеження **FastAPI**, а частина протоколу HTTP. + +/// + +## Підсумок + +Використовуйте `File` та `Form` разом, коли вам потрібно отримувати дані форми та файли в одному запиті. diff --git a/docs/uk/docs/tutorial/request-forms.md b/docs/uk/docs/tutorial/request-forms.md new file mode 100644 index 000000000..10c58a73e --- /dev/null +++ b/docs/uk/docs/tutorial/request-forms.md @@ -0,0 +1,73 @@ +# Дані форми + +Якщо Вам потрібно отримувати поля форми замість JSON, Ви можете використовувати `Form`. + +/// info | Інформація + +Щоб використовувати форми, спочатку встановіть `python-multipart`. + +Переконайтеся, що Ви створили [віртуальне середовище](../virtual-environments.md){.internal-link target=_blank}, активували його, і потім встановили бібліотеку, наприклад: + +```console +$ pip install python-multipart +``` + +/// + +## Імпорт `Form` + +Імпортуйте `Form` з `fastapi`: + +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[3] *} + +## Оголошення параметрів `Form` + +Створюйте параметри форми так само як Ви б створювали `Body` або `Query`: + +{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[9] *} + +Наприклад, один зі способів використання специфікації OAuth2 (так званий "password flow") вимагає надсилати `username` та `password` як поля форми. + +spec вимагає, щоб ці поля мали точні назви `username` і `password` та надсилалися у вигляді полів форми, а не JSON. + +З `Form` Ви можете оголошувати ті ж конфігурації, що і з `Body` (та `Query`, `Path`, `Cookie`), включаючи валідацію, приклади, псевдоніми (наприклад, `user-name` замість `username`) тощо. + +/// info | Інформація + +`Form` — це клас, який безпосередньо наслідується від `Body`. + +/// + +/// tip | Порада + +Щоб оголосити тіло форми, потрібно явно використовувати `Form`, оскільки без нього параметри будуть інтерпретуватися як параметри запиту або тіла (JSON). + +/// + +## Про "поля форми" + +HTML-форми (`
`) надсилають дані на сервер у "спеціальному" кодуванні, яке відрізняється від JSON. + +**FastAPI** подбає про те, щоб зчитати ці дані з правильного місця, а не з JSON. + +/// note | Технічні деталі + +Дані з форм зазвичай кодуються за допомогою "типу медіа" `application/x-www-form-urlencoded`. + +Але якщо форма містить файли, вона кодується як `multipart/form-data`. Ви дізнаєтеся про обробку файлів у наступному розділі. + +Якщо Ви хочете дізнатися більше про ці кодування та поля форм, зверніться до MDN вебдокументації для POST. + +/// + +/// warning | Попередження + +Ви можете оголосити кілька параметрів `Form` в *операції шляху*, але не можете одночасно оголосити поля `Body`, які Ви очікуєте отримати у форматі JSON, оскільки тіло запиту буде закодовано у форматі `application/x-www-form-urlencoded`, а не `application/json`. + +Це не обмеження **FastAPI**, а частина HTTP-протоколу. + +/// + +## Підсумок + +Використовуйте `Form` для оголошення вхідних параметрів у вигляді даних форми. diff --git a/docs/uk/docs/tutorial/response-status-code.md b/docs/uk/docs/tutorial/response-status-code.md new file mode 100644 index 000000000..1ed69d6f2 --- /dev/null +++ b/docs/uk/docs/tutorial/response-status-code.md @@ -0,0 +1,100 @@ +# Статус коди Відповідей + +Так само як Ви можете вказати модель відповіді, Ви також можете оголосити HTTP код статусу для відповіді за допомогою параметра `status_code` в будь-якій з *операцій шляху*: + +* `@app.get()` +* `@app.post()` +* `@app.put()` +* `@app.delete()` +* тощо. + +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} + +/// note | Нотатка + +Зверніть увагу, що `status_code` є параметром методу "декоратора" (`get`, `post` і т.д.), а не Вашої *функції операції шляху*, як усі інші параметри та тіло запиту. + +/// + +Параметр `status_code` приймає число, яке відповідає HTTP коду статусу. + +/// info | Інформація +`status_code` також може отримувати значення з `IntEnum`, наприклад, з Python `http.HTTPStatus`. + +/// + +Він буде: + +* Повертати вказаний код статусу у відповіді. +* Документувати його як такий у схемі OpenAPI (і, таким чином, в інтерфейсі користувача): + + + +/// note | Нотатка + +Деякі коди відповіді (див. наступний розділ) вказують, що відповідь не має тіла. + +FastAPI знає про це і створить OpenAPI документацію, яка вказує, що тіла відповіді немає. + +/// + +## Про HTTP статус коди + +/// note | Нотатка + +Якщо Ви вже знаєте, що таке HTTP коди статусу, переходьте до наступного розділу. + +/// + +В HTTP Ви надсилаєте числовий код статусу з 3 цифр як частину відповіді. + +Ці коди статусу мають пов’язану назву для їх розпізнавання, але найважливішою частиною є саме число. + +Коротко: + +* **`100 - 199`** "Інформаційні" відповіді. Ви рідко використовуєте їх напряму. Відповіді з такими кодами не можуть мати тіла. +* **`200 - 299`** "Успішні" відповіді. Це ті, які Ви використовуватимете найчастіше. + * `200` - код за замовчуванням, який означає, що все пройшло "OK". + * Інший приклад – `201`, "Created" (створено). Його зазвичай використовують після створення нового запису в базі даних. + * Особливий випадок – `204`, "No Content" (немає вмісту). Ця відповідь використовується, коли немає даних для повернення клієнту, тому відповідь не повинна мати тіла. +* **`300 - 399`** "Перенаправлення". Відповіді з цими кодами можуть мати або не мати тіла, за винятком `304`, "Not Modified" (не змінено), яка не повинна мати тіла. +* **`400 - 499`** "Помилка клієнта". Це другий тип, який Ви, ймовірно, будете використовувати найчастіше. + * Приклад `404`, "Not Found" (не знайдено). + * Для загальних помилок клієнта можна використовувати `400`. +* `500 - 599` "Помилки сервера". Ви майже ніколи не використовуєте їх напряму. Якщо в коді Вашого застосунку або на сервері щось пішло не так, автоматично буде повернено один із цих кодів статусу. + +/// tip | Порада + +Щоб дізнатися більше про кожен код статусу і призначення кожного з них, перегляньте документацію MDN про HTTP коди статусу. + +/// + +## Легкий спосіб запам'ятати назви + +Розглянемо ще раз попередній приклад: + +{* ../../docs_src/response_status_code/tutorial001.py hl[6] *} + +`201` - це код статусу для "Created" (створено). + +Але Вам не потрібно запам'ятовувати, що означає кожен із цих кодів. + +Ви можете використовувати зручні змінні з `fastapi.status` + +{* ../../docs_src/response_status_code/tutorial002.py hl[1,6] *} + +Ці змінні просто для зручності. Вони містять ті ж самі числа, але Ви можете скористатися автозаповненням в редакторі: + + + +/// note | Технічні деталі + +Ви також можете використати `from starlette import status`. + +**FastAPI** надає ті ж самі змінні `starlette.status` як `fastapi.status`, просто для зручності розробника. Однак вони походять безпосередньо зі Starlette. + +/// + +## Зміна значення за замовчуванням + +Далі, у Посібнику для досвідчених користувачів{.internal-link target=_blank}, Ви дізнаєтесь, як повернути інший код статусу, ніж той, який Ви оголосили тут. diff --git a/docs/uk/docs/tutorial/testing.md b/docs/uk/docs/tutorial/testing.md new file mode 100644 index 000000000..25fc370d6 --- /dev/null +++ b/docs/uk/docs/tutorial/testing.md @@ -0,0 +1,240 @@ +# Тестування + +Тестування **FastAPI** додатків є простим та ефективним завдяки бібліотеці Starlette, яка базується на HTTPX. +Оскільки HTTPX розроблений на основі Requests, його API є інтуїтивно зрозумілим для тих, хто вже знайомий з Requests. + +З його допомогою Ви можете використовувати pytest безпосередньо з **FastAPI**. + +## Використання `TestClient` + +/// info | Інформація + +Щоб використовувати `TestClient`, спочатку встановіть `httpx`. + +Переконайтеся, що Ви створили [віртуальне середовище](../virtual-environments.md){.internal-link target=_blank}, активували його, а потім встановили саму бібліотеку, наприклад: + +```console +$ pip install httpx +``` + +/// + +Імпортуйте `TestClient`. + +Створіть `TestClient`, передавши йому Ваш застосунок **FastAPI**. + +Створюйте функції з іменами, що починаються з `test_` (це стандартна угода для `pytest`). + +Використовуйте об'єкт `TestClient` так само як і `httpx`. + +Записуйте прості `assert`-вирази зі стандартними виразами Python, які потрібно перевірити (це також стандарт для `pytest`). + +{* ../../docs_src/app_testing/tutorial001.py hl[2,12,15:18] *} + + +/// tip | Порада + +Зверніть увагу, що тестові функції — це звичайні `def`, а не `async def`. + +Виклики клієнта також звичайні, без використання `await`. + +Це дозволяє використовувати `pytest` без зайвих ускладнень. + +/// + +/// note | Технічні деталі + +Ви також можете використовувати `from starlette.testclient import TestClient`. + +**FastAPI** надає той самий `starlette.testclient` під назвою `fastapi.testclient` для зручності розробників, але він безпосередньо походить із Starlette. + +/// + +/// tip | Порада + +Якщо Вам потрібно викликати `async`-функції у ваших тестах, окрім відправлення запитів до FastAPI-застосунку (наприклад, асинхронні функції роботи з базою даних), перегляньте [Асинхронні тести](../advanced/async-tests.md){.internal-link target=_blank} у розширеному керівництві. + +/// + +## Розділення тестів + +У реальному застосунку Ваші тести, ймовірно, будуть в окремому файлі. + +Також Ваш **FastAPI**-застосунок може складатися з кількох файлів або модулів тощо. + +### Файл застосунку **FastAPI** + +Припустимо, у Вас є структура файлів, описана в розділі [Більші застосунки](bigger-applications.md){.internal-link target=_blank}: + +``` +. +├── app +│   ├── __init__.py +│   └── main.py +``` +У файлі `main.py` знаходиться Ваш застосунок **FastAPI** : + +{* ../../docs_src/app_testing/main.py *} + +### Файл тестування + +Ви можете створити файл `test_main.py` з Вашими тестами. Він може знаходитися в тому ж пакеті Python (у тій самій директорії з файлом `__init__.py`): + + +``` hl_lines="5" +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + +Оскільки цей файл знаходиться в тому ж пакеті, Ви можете використовувати відносний імпорт, щоб імпортувати об'єкт `app` із модуля `main` (`main.py`): + +{* ../../docs_src/app_testing/test_main.py hl[3] *} + + +...і написати код для тестів так само як і раніше. + +## Тестування: розширений приклад + +Тепер розширимо цей приклад і додамо більше деталей, щоб побачити, як тестувати різні частини. + +### Розширений файл застосунку **FastAPI** + +Залишимо ту саму структуру файлів: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + +Припустимо, що тепер файл `main.py` із Вашим **FastAPI**-застосунком містить додаткові операції шляху (**path operations**). + +Він має `GET`-операцію, яка може повертати помилку. + +Він має `POST`-операцію, яка може повертати кілька помилок. + +Обидві операції шляху вимагають заголовок `X-Token`. + +//// tab | Python 3.10+ + +```Python +{!> ../../docs_src/app_testing/app_b_an_py310/main.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python +{!> ../../docs_src/app_testing/app_b_an_py39/main.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python +{!> ../../docs_src/app_testing/app_b_an/main.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Порада + +Бажано використовувати версію з `Annotated`, якщо це можливо + +/// + +```Python +{!> ../../docs_src/app_testing/app_b_py310/main.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Порада + +Бажано використовувати версію з `Annotated`, якщо це можливо + +/// + +```Python +{!> ../../docs_src/app_testing/app_b/main.py!} +``` + +//// + +### Розширений тестовий файл + +Потім Ви можете оновити `test_main.py`, додавши розширені тести: + +{* ../../docs_src/app_testing/app_b/test_main.py *} + +Коли Вам потрібно передати клієнту інформацію в запиті, але Ви не знаєте, як це зробити, Ви можете пошукати (наприклад, у Google) спосіб реалізації в `httpx`, або навіть у `requests`, оскільки HTTPX розроблений на основі дизайну Requests. + +Далі Ви просто повторюєте ці ж дії у ваших тестах. + +Наприклад: + +* Щоб передати *path* або *query* параметр, додайте його безпосередньо до URL. +* Щоб передати тіло JSON, передайте Python-об'єкт (наприклад, `dict`) у параметр `json`. +* Якщо потрібно надіслати *Form Data* замість JSON, використовуйте параметр `data`. +* Щоб передати заголовки *headers*, використовуйте `dict` у параметрі `headers`. +* Для *cookies* використовуйте `dict` у параметрі `cookies`. + +Докладніше про передачу даних у бекенд (за допомогою `httpx` або `TestClient`) можна знайти в документації HTTPX. + +/// info | Інформація + +Зверніть увагу, що `TestClient` отримує дані, які можна конвертувати в JSON, а не Pydantic-моделі. +Якщо у Вас є Pydantic-модель у тесті, і Ви хочете передати її дані в додаток під час тестування, Ви можете використати `jsonable_encoder`, описаний у розділі [JSON Compatible Encoder](encoder.md){.internal-link target=_blank}. + +/// + +## Запуск тестів + +Після цього вам потрібно встановити `pytest`. + +Переконайтеся, що Ви створили [віртуальне середовище]{.internal-link target=_blank}, активували його і встановили необхідні пакети, наприклад: + +
+ +```console +$ pip install pytest + +---> 100% +``` + +
+ +`pytest` автоматично знайде файли з тестами, виконає їх і надасть вам результати. + +Запустіть тести за допомогою: + +
+ +```console +$ pytest + +================ test session starts ================ +platform linux -- Python 3.6.9, pytest-5.3.5, py-1.8.1, pluggy-0.13.1 +rootdir: /home/user/code/superawesome-cli/app +plugins: forked-1.1.3, xdist-1.31.0, cov-2.8.1 +collected 6 items + +---> 100% + +test_main.py ...... [100%] + +================= 1 passed in 0.03s ================= +``` + +
diff --git a/docs/vi/docs/deployment/cloud.md b/docs/vi/docs/deployment/cloud.md new file mode 100644 index 000000000..9ab72769d --- /dev/null +++ b/docs/vi/docs/deployment/cloud.md @@ -0,0 +1,17 @@ +# Triển khai FastAPI trên các Dịch vụ Cloud + +Bạn có thể sử dụng **bất kỳ nhà cung cấp dịch vụ cloud** nào để triển khai ứng dụng FastAPI của mình. + +Trong hầu hết các trường hợp, các nhà cung cấp dịch vụ cloud lớn đều có hướng dẫn triển khai FastAPI với họ. + +## Nhà cung cấp dịch vụ Cloud - Nhà tài trợ +Một vài nhà cung cấp dịch vụ cloud ✨ [**tài trợ cho FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨, điều này giúp đảm bảo sự phát triển liên tục và khỏe mạnh của FastAPI và hệ sinh thái của nó. + +Thêm nữa, điều này cũng thể hiện cam kết thực sự của họ đối với FastAPI và **cộng đồng người dùng** (bạn), vì họ không chỉ muốn cung cấp cho bạn một **dịch vụ tốt** mà còn muốn đảm bảo rằng bạn có một **framework tốt và bền vững**, đó chính là FastAPI. 🙇 + +Bạn có thể thử các dịch vụ của họ và làm theo hướng dẫn của họ: + +* Platform.sh +* Porter +* Coherence +* Render diff --git a/docs/vi/docs/deployment/index.md b/docs/vi/docs/deployment/index.md new file mode 100644 index 000000000..24ffdc71b --- /dev/null +++ b/docs/vi/docs/deployment/index.md @@ -0,0 +1,21 @@ +# Triển khai + +Triển khai một ứng dụng **FastAPI** khá dễ dàng. + +## Triển khai là gì + +Triển khai một ứng dụng có nghĩa là thực hiện các bước cần thiết để làm cho nó **sẵn sàng phục vụ người dùng**. + +Đối với một **API web**, điều này có nghĩa là đặt nó trong một **máy chủ từ xa**, với một **chương trình máy chủ** cung cấp hiệu suất tốt, ổn định, v.v., để người dùng của bạn có thể truy cập ứng dụng của bạn một cách hiệu quả và không bị gián đoạn hoặc gặp vấn đề. + +Điều này trái ngược với các **giai đoạn phát triển**, trong đó bạn liên tục thay đổi mã, phá vỡ nó và sửa nó, ngừng và khởi động lại máy chủ phát triển, v.v. + +## Các Chiến lược Triển khai + +Có nhiều cách để triển khai ứng dụng của bạn tùy thuộc vào trường hợp sử dụng của bạn và các công cụ mà bạn sử dụng. + +Bạn có thể **triển khai một máy chủ** của riêng bạn bằng cách sử dụng một sự kết hợp các công cụ, hoặc bạn có thể sử dụng một **dịch vụ cloud** để làm một số công việc cho bạn, hoặc các tùy chọn khác. + +Tôi sẽ chỉ ra một số khái niệm chính cần thiết khi triển khai một ứng dụng **FastAPI** (mặc dù hầu hết nó áp dụng cho bất kỳ loại ứng dụng web nào). + +Bạn sẽ thấy nhiều chi tiết cần thiết và một số kỹ thuật để triển khai trong các phần tiếp theo. ✨ diff --git a/docs/vi/docs/deployment/versions.md b/docs/vi/docs/deployment/versions.md new file mode 100644 index 000000000..04de393e7 --- /dev/null +++ b/docs/vi/docs/deployment/versions.md @@ -0,0 +1,93 @@ +# Về các phiên bản của FastAPI + +**FastAPI** đã được sử dụng ở quy mô thực tế (production) trong nhiều ứng dụng và hệ thống. Và phạm vi kiểm thử được giữ ở mức 100%. Nhưng việc phát triển của nó vẫn đang diễn ra nhanh chóng. + +Các tính năng mới được bổ sung thường xuyên, lỗi được sửa định kỳ, và mã nguồn vẫn đang được cải thiện liên tục + +Đó là lí do các phiên bản hiện tại vẫn còn là 0.x.x, điều này phản ánh rằng mỗi phiên bản có thể có các thay đổi gây mất tương thích. Điều này tuân theo các quy ước về Semantic Versioning. + +Bạn có thể tạo ra sản phẩm thực tế với **FastAPI** ngay bây giờ (và bạn có thể đã làm điều này trong một thời gian dài), bạn chỉ cần đảm bảo rằng bạn sử dụng một phiên bản hoạt động đúng với các đoạn mã còn lại của bạn. + +## Cố định phiên bản của `fastapi` + +Điều đầu tiên bạn nên làm là "cố định" phiên bản của **FastAPI** bạn đang sử dụng để phiên bản mới nhất mà bạn biết hoạt động đúng với ứng dụng của bạn. + +Ví dụ, giả sử bạn đang sử dụng phiên bản `0.112.0` trong ứng dụng của bạn. + +Nếu bạn sử dụng một tệp `requirements.txt` bạn có thể chỉ định phiên bản với: + +```txt +fastapi[standard]==0.112.0 +``` + +Như vậy, bạn sẽ sử dụng chính xác phiên bản `0.112.0`. + +Hoặc bạn cũng có thể cố định nó với: + +```txt +fastapi[standard]>=0.112.0,<0.113.0 +``` + +Như vậy, bạn sẽ sử dụng các phiên bản `0.112.0` trở lên, nhưng nhỏ hơn `0.113.0`, ví dụ, một phiên bản `0.112.2` vẫn được chấp nhận. + +Nếu bạn sử dụng bất kỳ công cụ nào để quản lý cài đặt của bạn, như `uv`, Poetry, Pipenv, hoặc bất kỳ công cụ nào khác, chúng đều có một cách để bạn có thể định nghĩa các phiên bản cụ thể cho các gói của bạn. + +## Các phiên bản có sẵn + +Bạn có thể xem các phiên bản có sẵn (ví dụ để kiểm tra phiên bản mới nhất) trong [Release Notes](../release-notes.md){.internal-link target=_blank}. + +## Về các phiên bản + +Theo quy ước về Semantic Versioning, bất kỳ phiên bản nào bên dưới `1.0.0` có thể thêm các thay đổi gây mất tương thích. + +**FastAPI** cũng theo quy ước rằng bất kỳ thay đổi phiên bản "PATCH" nào là cho các lỗi và các thay đổi không gây mất tương thích. + +/// tip + +"PATCH" là số cuối cùng, ví dụ, trong `0.2.3`, phiên bản PATCH là `3`. + +/// + +Vì vậy, bạn có thể cố định đến một phiên bản như: + +```txt +fastapi>=0.45.0,<0.46.0 +``` + +Các thay đổi gây mất tương thích và các tính năng mới được thêm vào trong các phiên bản "MINOR". + +/// tip + +"MINOR" là số ở giữa, ví dụ, trong `0.2.3`, phiên bản MINOR là `2`. + +/// + +## Nâng cấp các phiên bản của FastAPI + +Bạn nên thêm các bài kiểm tra (tests) cho ứng dụng của bạn. + +Với **FastAPI** điều này rất dễ dàng (nhờ vào Starlette), kiểm tra tài liệu: [Testing](../tutorial/testing.md){.internal-link target=_blank} + +Sau khi bạn có các bài kiểm tra, bạn có thể nâng cấp phiên bản **FastAPI** lên một phiên bản mới hơn, và đảm bảo rằng tất cả mã của bạn hoạt động đúng bằng cách chạy các bài kiểm tra của bạn. + +Nếu mọi thứ đang hoạt động, hoặc sau khi bạn thực hiện các thay đổi cần thiết, và tất cả các bài kiểm tra của bạn đều đi qua, thì bạn có thể cố định phiên bản của `fastapi` đến phiên bản mới hơn. + +## Về Starlette + +Bạn không nên cố định phiên bản của `starlette`. + +Các phiên bản khác nhau của **FastAPI** sẽ sử dụng một phiên bản Starlette mới hơn. + +Vì vậy, bạn có thể để **FastAPI** sử dụng phiên bản Starlette phù hợp. + +## Về Pydantic + +Pydantic bao gồm các bài kiểm tra của riêng nó cho **FastAPI**, vì vậy các phiên bản mới hơn của Pydantic (trên `1.0.0`) luôn tương thích với **FastAPI**. + +Bạn có thể cố định Pydantic đến bất kỳ phiên bản nào trên `1.0.0` mà bạn muốn. + +Ví dụ: + +```txt +pydantic>=2.7.0,<3.0.0 +``` diff --git a/docs/vi/docs/index.md b/docs/vi/docs/index.md index 5e346ded8..5c6b7e8a4 100644 --- a/docs/vi/docs/index.md +++ b/docs/vi/docs/index.md @@ -12,7 +12,7 @@

- Test + Test Coverage diff --git a/docs/vi/docs/tutorial/static-files.md b/docs/vi/docs/tutorial/static-files.md new file mode 100644 index 000000000..ecf8c2485 --- /dev/null +++ b/docs/vi/docs/tutorial/static-files.md @@ -0,0 +1,40 @@ +# Tệp tĩnh (Static Files) + +Bạn có thể triển khai tệp tĩnh tự động từ một thư mục bằng cách sử dụng StaticFiles. + +## Sử dụng `Tệp tĩnh` + +- Nhập `StaticFiles`. +- "Mount" a `StaticFiles()` instance in a specific path. + +{* ../../docs_src/static_files/tutorial001.py hl[2,6] *} + +/// note | Chi tiết kỹ thuật + +Bạn cũng có thể sử dụng `from starlette.staticfiles import StaticFiles`. + +**FastAPI** cung cấp cùng `starlette.staticfiles` như `fastapi.staticfiles` giúp đơn giản hóa việc sử dụng, nhưng nó thực sự đến từ Starlette. + +/// + +### "Mounting" là gì + +"Mounting" có nghĩa là thêm một ứng dụng "độc lập" hoàn chỉnh vào một đường dẫn cụ thể, sau đó ứng dụng đó sẽ chịu trách nhiệm xử lý tất cả các đường dẫn con. + +Điều này khác với việc sử dụng `APIRouter` vì một ứng dụng được gắn kết là hoàn toàn độc lập. OpenAPI và tài liệu từ ứng dụng chính của bạn sẽ không bao gồm bất kỳ thứ gì từ ứng dụng được gắn kết, v.v. + +Bạn có thể đọc thêm về điều này trong [Hướng dẫn Người dùng Nâng cao](../advanced/index.md){.internal-link target=\_blank}. + +## Chi tiết + +Đường dẫn đầu tiên `"/static"` là đường dẫn con mà "ứng dụng con" này sẽ được "gắn" vào. Vì vậy, bất kỳ đường dẫn nào bắt đầu bằng `"/static"` sẽ được xử lý bởi nó. + +Đường dẫn `directory="static"` là tên của thư mục chứa tệp tĩnh của bạn. + +Tham số `name="static"` đặt tên cho nó để có thể được sử dụng bên trong **FastAPI**. + +Tất cả các tham số này có thể khác với `static`, điều chỉnh chúng với phù hợp với ứng dụng của bạn. + +## Thông tin thêm + +Để biết thêm chi tiết và tùy chọn, hãy xem Starlette's docs about Static Files. diff --git a/docs/yo/docs/index.md b/docs/yo/docs/index.md index 3ad1483de..d6aa78b3d 100644 --- a/docs/yo/docs/index.md +++ b/docs/yo/docs/index.md @@ -12,7 +12,7 @@

- Test + Test Coverage diff --git a/docs/zh-hant/docs/index.md b/docs/zh-hant/docs/index.md index 137a17284..81d99ede4 100644 --- a/docs/zh-hant/docs/index.md +++ b/docs/zh-hant/docs/index.md @@ -6,7 +6,7 @@

- Test + Test Coverage diff --git a/docs/zh/docs/deployment/concepts.md b/docs/zh/docs/deployment/concepts.md index 7a0b6c3d2..f7208da7c 100644 --- a/docs/zh/docs/deployment/concepts.md +++ b/docs/zh/docs/deployment/concepts.md @@ -220,7 +220,7 @@ 这些工作进程将是运行您的应用程序的进程,它们将执行主要计算以接收 **请求** 并返回 **响应**,并且它们将加载您放入 RAM 中的变量中的任何内容。 - + 当然,除了您的应用程序之外,同一台机器可能还运行**其他进程**。 diff --git a/docs/zh/docs/deployment/https.md b/docs/zh/docs/deployment/https.md index 9c963d587..d994c4add 100644 --- a/docs/zh/docs/deployment/https.md +++ b/docs/zh/docs/deployment/https.md @@ -86,7 +86,7 @@ DNS 服务器会告诉浏览器使用某个特定的 **IP 地址**。 这将是你在 DNS 服务器中为你的服务器配置的公共 IP 地址。 - + ### TLS 握手开始 @@ -94,7 +94,7 @@ DNS 服务器会告诉浏览器使用某个特定的 **IP 地址**。 这将是 通信的第一部分只是建立客户端和服务器之间的连接并决定它们将使用的加密密钥等。 - + 客户端和服务器之间建立 TLS 连接的过程称为 **TLS 握手**。 @@ -112,7 +112,7 @@ TLS 终止代理可以访问一个或多个 **TLS 证书**(HTTPS 证书)。 在这种情况下,它将使用`someapp.example.com`的证书。 - + 客户端已经**信任**生成该 TLS 证书的实体(在本例中为 Let's Encrypt,但我们稍后会看到),因此它可以**验证**该证书是否有效。 @@ -134,19 +134,19 @@ TLS 终止代理可以访问一个或多个 **TLS 证书**(HTTPS 证书)。 接下来,客户端发送一个 **HTTPS 请求**。 这其实只是一个通过 TLS 加密连接的 HTTP 请求。 - + ### 解密请求 TLS 终止代理将使用协商好的加密算法**解密请求**,并将**(解密的)HTTP 请求**传输到运行应用程序的进程(例如运行 FastAPI 应用的 Uvicorn 进程)。 - + ### HTTP 响应 应用程序将处理请求并向 TLS 终止代理发送**(未加密)HTTP 响应**。 - + ### HTTPS 响应 @@ -154,7 +154,7 @@ TLS 终止代理将使用协商好的加密算法**解密请求**,并将**( 接下来,浏览器将验证响应是否有效和是否使用了正确的加密密钥等。然后它会**解密响应**并处理它。 - + 客户端(浏览器)将知道响应来自正确的服务器,因为它使用了他们之前使用 **HTTPS 证书** 协商出的加密算法。 @@ -164,7 +164,7 @@ TLS 终止代理将使用协商好的加密算法**解密请求**,并将**( 只有一个进程可以处理特定的 IP 和端口(在我们的示例中为 TLS 终止代理),但其他应用程序/进程也可以在服务器上运行,只要它们不尝试使用相同的 **公共 IP 和端口的组合**。 - + 这样,TLS 终止代理就可以为多个应用程序处理**多个域名**的 HTTPS 和证书,然后在每种情况下将请求传输到正确的应用程序。 @@ -174,7 +174,7 @@ TLS 终止代理将使用协商好的加密算法**解密请求**,并将**( 然后,会有另一个程序(在某些情况下是另一个程序,在某些情况下可能是同一个 TLS 终止代理)与 Let's Encrypt 通信并更新证书。 - + **TLS 证书** **与域名相关联**,而不是与 IP 地址相关联。 diff --git a/docs/zh/docs/deployment/manually.md b/docs/zh/docs/deployment/manually.md index 30ee7a1e9..3dc5942e3 100644 --- a/docs/zh/docs/deployment/manually.md +++ b/docs/zh/docs/deployment/manually.md @@ -1,159 +1,157 @@ -# 手动运行服务器 - Uvicorn +# 手动运行服务器 -在远程服务器计算机上运行 **FastAPI** 应用程序所需的主要东西是 ASGI 服务器程序,例如 **Uvicorn**。 +## 使用 `fastapi run` 命令 -有 3 个主要可选方案: +简而言之,使用 `fastapi run` 来运行您的 FastAPI 应用程序: -* Uvicorn:高性能 ASGI 服务器。 -* Hypercorn:与 HTTP/2 和 Trio 等兼容的 ASGI 服务器。 -* Daphne:为 Django Channels 构建的 ASGI 服务器。 - -## 服务器主机和服务器程序 - -关于名称,有一个小细节需要记住。 💡 - -“**服务器**”一词通常用于指远程/云计算机(物理机或虚拟机)以及在该计算机上运行的程序(例如 Uvicorn)。 +

-请记住,当您一般读到“服务器”这个名词时,它可能指的是这两者之一。 +```console +$ fastapi run main.py -当提到远程主机时,通常将其称为**服务器**,但也称为**机器**(machine)、**VM**(虚拟机)、**节点**。 这些都是指某种类型的远程计算机,通常运行 Linux,您可以在其中运行程序。 + FastAPI Starting production server 🚀 + Searching for package file structure from directories + with __init__.py files + Importing from /home/user/code/awesomeapp -## 安装服务器程序 + module 🐍 main.py -您可以使用以下命令安装 ASGI 兼容服务器: + code Importing the FastAPI app object from the module with + the following code: -//// tab | Uvicorn + from main import app -* Uvicorn,一个快如闪电 ASGI 服务器,基于 uvloop 和 httptools 构建。 + app Using import string: main:app -
+ server Server started at http://0.0.0.0:8000 + server Documentation at http://0.0.0.0:8000/docs -```console -$ pip install "uvicorn[standard]" + Logs: ----> 100% + INFO Started server process [2306215] + INFO Waiting for application startup. + INFO Application startup complete. + INFO Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C + to quit) ```
-/// tip +这在大多数情况下都能正常运行。😎 -通过添加`standard`,Uvicorn 将安装并使用一些推荐的额外依赖项。 +例如,您可以使用该命令在容器、服务器等环境中启动您的 **FastAPI** 应用。 -其中包括`uvloop`,它是`asyncio`的高性能替代品,它提供了巨大的并发性能提升。 +## ASGI 服务器 -/// +让我们深入了解一些细节。 -//// +FastAPI 使用了一种用于构建 Python Web 框架和服务器的标准,称为 ASGI。FastAPI 本质上是一个 ASGI Web 框架。 -//// tab | Hypercorn +要在远程服务器上运行 **FastAPI** 应用(或任何其他 ASGI 应用),您需要一个 ASGI 服务器程序,例如 **Uvicorn**。它是 `fastapi` 命令默认使用的 ASGI 服务器。 -* Hypercorn,一个也与 HTTP/2 兼容的 ASGI 服务器。 - -
+除此之外,还有其他一些可选的 ASGI 服务器,例如: -```console -$ pip install hypercorn - ----> 100% -``` - -
+* Uvicorn:高性能 ASGI 服务器。 +* Hypercorn:与 HTTP/2 和 Trio 等兼容的 ASGI 服务器。 +* Daphne:为 Django Channels 构建的 ASGI 服务器。 +* Granian:基于 Rust 的 HTTP 服务器,专为 Python 应用设计。 +* NGINX Unit:NGINX Unit 是一个轻量级且灵活的 Web 应用运行时环境。 -...或任何其他 ASGI 服务器。 +## 服务器主机和服务器程序 -//// +关于名称,有一个小细节需要记住。 💡 -## 运行服务器程序 +“**服务器**”一词通常用于指远程/云计算机(物理机或虚拟机)以及在该计算机上运行的程序(例如 Uvicorn)。 -您可以按照之前教程中的相同方式运行应用程序,但不使用`--reload`选项,例如: +请记住,当您一般读到“服务器”这个名词时,它可能指的是这两者之一。 -//// tab | Uvicorn +当提到远程主机时,通常将其称为**服务器**,但也称为**机器**(machine)、**VM**(虚拟机)、**节点**。 这些都是指某种类型的远程计算机,通常运行 Linux,您可以在其中运行程序。 -
-```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) -``` +当您安装 FastAPI 时,它自带一个生产环境服务器——Uvicorn,并且您可以使用 `fastapi run` 命令来启动它。 -
+不过,您也可以手动安装 ASGI 服务器。 -//// +请确保您创建并激活一个[虚拟环境](../virtual-environments.md){.internal-link target=_blank},然后再安装服务器应用程序。 -//// tab | Hypercorn +例如,要安装 Uvicorn,可以运行以下命令:
```console -$ hypercorn main:app --bind 0.0.0.0:80 +$ pip install "uvicorn[standard]" -Running on 0.0.0.0:8080 over http (CTRL + C to quit) +---> 100% ```
-//// +类似的流程也适用于任何其他 ASGI 服务器程序。 -/// warning +/// tip -如果您正在使用`--reload`选项,请记住删除它。 +通过添加 `standard` 选项,Uvicorn 将安装并使用一些推荐的额外依赖项。 - `--reload` 选项消耗更多资源,并且更不稳定。 +其中包括 `uvloop`,这是 `asyncio` 的高性能替代方案,能够显著提升并发性能。 - 它在**开发**期间有很大帮助,但您**不应该**在**生产环境**中使用它。 +当您使用 `pip install "fastapi[standard]"` 安装 FastAPI 时,实际上也会安装 `uvicorn[standard]`。 /// -## Hypercorn with Trio - -Starlette 和 **FastAPI** 基于 AnyIO, 所以它们才能同时与 Python 的标准库 asyncioTrio 兼容。 - -尽管如此,Uvicorn 目前仅与 asyncio 兼容,并且通常使用 `uvloop`, 它是`asyncio`的高性能替代品。 - -但如果你想直接使用**Trio**,那么你可以使用**Hypercorn**,因为它支持它。 ✨ - -### 安装具有 Trio 的 Hypercorn +## 运行服务器程序 -首先,您需要安装具有 Trio 支持的 Hypercorn: +如果您手动安装了 ASGI 服务器,通常需要以特定格式传递一个导入字符串,以便服务器能够正确导入您的 FastAPI 应用:
```console -$ pip install "hypercorn[trio]" ----> 100% +$ uvicorn main:app --host 0.0.0.0 --port 80 + +INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit) ```
-### Run with Trio +/// note -然后你可以传递值`trio`给命令行选项`--worker-class`: +命令 `uvicorn main:app` 的含义如下: -
+* `main`:指的是 `main.py` 文件(即 Python “模块”)。 +* `app`:指的是 `main.py` 文件中通过 `app = FastAPI()` 创建的对象。 -```console -$ hypercorn main:app --worker-class trio +它等价于以下导入语句: + +```Python +from main import app ``` -
+/// + +每种 ASGI 服务器程序通常都会有类似的命令,您可以在它们的官方文档中找到更多信息。 + +/// warning + +Uvicorn 和其他服务器支持 `--reload` 选项,该选项在开发过程中非常有用。 -这将通过您的应用程序启动 Hypercorn,并使用 Trio 作为后端。 +但 `--reload` 选项会消耗更多资源,且相对不稳定。 -现在您可以在应用程序内部使用 Trio。 或者更好的是,您可以使用 AnyIO,使您的代码与 Trio 和 asyncio 兼容。 🎉 +它对于**开发阶段**非常有帮助,但在**生产环境**中**不应该**使用。 + +/// ## 部署概念 -这些示例运行服务器程序(例如 Uvicorn),启动**单个进程**,在所有 IP(`0.0.0.0`)上监听预定义端口(例如`80`)。 +这些示例运行服务器程序(例如 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 index eb0252a5c..e46ba7a09 100644 --- a/docs/zh/docs/deployment/server-workers.md +++ b/docs/zh/docs/deployment/server-workers.md @@ -1,4 +1,4 @@ -# Server Workers - Gunicorn with Uvicorn +# 服务器工作进程(Workers) - 使用 Uvicorn 的多工作进程模式 让我们回顾一下之前的部署概念: @@ -9,125 +9,79 @@ * 内存 * 启动前的先前步骤 -到目前为止,通过文档中的所有教程,您可能已经在**单个进程**上运行了像 Uvicorn 这样的**服务器程序**。 +到目前为止,在文档中的所有教程中,您可能一直是在运行一个**服务器程序**,例如使用 `fastapi` 命令来启动 Uvicorn,而它默认运行的是**单进程模式**。 -部署应用程序时,您可能希望进行一些**进程复制**,以利用**多核**并能够处理更多请求。 +部署应用程序时,您可能希望进行一些**进程复制**,以利用**多核** CPU 并能够处理更多请求。 正如您在上一章有关[部署概念](concepts.md){.internal-link target=_blank}中看到的,您可以使用多种策略。 -在这里我将向您展示如何将 **Gunicorn** 与 **Uvicorn worker 进程** 一起使用。 +在本章节中,我将向您展示如何使用 `fastapi` 命令或直接使用 `uvicorn` 命令以**多工作进程模式**运行 **Uvicorn**。 /// info 如果您正在使用容器,例如 Docker 或 Kubernetes,我将在下一章中告诉您更多相关信息:[容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank}。 -特别是,当在 **Kubernetes** 上运行时,您可能**不想**使用 Gunicorn,而是运行 **每个容器一个 Uvicorn 进程**,但我将在本章后面告诉您这一点。 +比较特别的是,在 **Kubernetes** 环境中运行时,您通常**不需要**使用多个工作进程,而是**每个容器运行一个 Uvicorn 进程**。不过,我会在本章节的后续部分详细介绍这一点。 /// -## Gunicorn with Uvicorn Workers +## 多个工作进程 -**Gunicorn**主要是一个使用**WSGI标准**的应用服务器。 这意味着 Gunicorn 可以为 Flask 和 Django 等应用程序提供服务。 Gunicorn 本身与 **FastAPI** 不兼容,因为 FastAPI 使用最新的 **ASGI 标准**。 +您可以使用 `--workers` 命令行选项来启动多个工作进程: -但 Gunicorn 支持充当 **进程管理器** 并允许用户告诉它要使用哪个特定的 **worker类**。 然后 Gunicorn 将使用该类启动一个或多个 **worker进程**。 +//// tab | `fastapi` -**Uvicorn** 有一个 Gunicorn 兼容的worker类。 - -使用这种组合,Gunicorn 将充当 **进程管理器**,监听 **端口** 和 **IP**。 它会将通信**传输**到运行**Uvicorn类**的worker进程。 - -然后与Gunicorn兼容的**Uvicorn worker**类将负责将Gunicorn发送的数据转换为ASGI标准以供FastAPI使用。 - -## 安装 Gunicorn 和 Uvicorn +如果您使用 `fastapi` 命令:
```console -$ pip install "uvicorn[standard]" gunicorn - ----> 100% -``` - -
+$ fastapi run --workers 4 main.py -这将安装带有`standard`扩展包(以获得高性能)的 Uvicorn 和 Gunicorn。 + FastAPI Starting production server 🚀 -## Run Gunicorn with Uvicorn Workers + Searching for package file structure from directories with + __init__.py files + Importing from /home/user/code/awesomeapp -接下来你可以通过以下命令运行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. -``` - -
+ module 🐍 main.py + code Importing the FastAPI app object from the module with the + following code: -让我们看看每个选项的含义: + from main import app -* `main:app`:这与 Uvicorn 使用的语法相同,`main` 表示名为"`main`"的 Python 模块,因此是文件 `main.py`。 `app` 是 **FastAPI** 应用程序的变量名称。 - * 你可以想象 `main:app` 相当于一个 Python `import` 语句,例如: + app Using import string: main:app - ```Python - from main import app - ``` + server Server started at http://0.0.0.0:8000 + server Documentation at http://0.0.0.0:8000/docs - * 因此,`main:app` 中的冒号相当于 `from main import app` 中的 Python `import` 部分。 + Logs: -* `--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**,并且**在启动时运行它**等。 + INFO Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to + quit) + INFO Started parent process [27365] + INFO Started server process [27368] + INFO Started server process [27369] + INFO Started server process [27370] + INFO Started server process [27367] + INFO Waiting for application startup. + INFO Waiting for application startup. + INFO Waiting for application startup. + INFO Waiting for application startup. + INFO Application startup complete. + INFO Application startup complete. + INFO Application startup complete. + INFO Application startup complete. +``` -## Uvicorn with Workers +
-Uvicorn 也有一个选项可以启动和运行多个 **worker进程**。 +//// -然而,到目前为止,Uvicorn 处理worker进程的能力比 Gunicorn 更有限。 因此,如果您想拥有这个级别(Python 级别)的进程管理器,那么最好尝试使用 Gunicorn 作为进程管理器。 +//// tab | `uvicorn` -无论如何,您都可以像这样运行它: +如果您更想要直接使用 `uvicorn` 命令:
@@ -151,13 +105,15 @@ $ uvicorn main:app --host 0.0.0.0 --port 8080 --workers 4
+//// + 这里唯一的新选项是 `--workers` 告诉 Uvicorn 启动 4 个工作进程。 -您还可以看到它显示了每个进程的 **PID**,父进程(这是 **进程管理器**)的 PID 为`27365`,每个工作进程的 PID 为:`27368`、`27369`, `27370`和`27367`。 +您还可以看到它显示了每个进程的 **PID**,父进程(这是**进程管理器**)的 PID 为`27365`,每个工作进程的 PID 为:`27368`、`27369`, `27370`和`27367`。 ## 部署概念 -在这里,您了解了如何使用 **Gunicorn**(或 Uvicorn)管理 **Uvicorn 工作进程**来**并行**应用程序的执行,利用 CPU 中的 **多核**,并 能够满足**更多请求**。 +在这里,您学习了如何使用多个**工作进程(workers)**来让应用程序的执行**并行化**,充分利用 CPU 的**多核性能**,并能够处理**更多的请求**。 从上面的部署概念列表来看,使用worker主要有助于**复制**部分,并对**重新启动**有一点帮助,但您仍然需要照顾其他部分: @@ -170,15 +126,13 @@ $ uvicorn main:app --host 0.0.0.0 --port 8080 --workers 4 ## 容器和 Docker -在关于 [容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank} 的下一章中,我将介绍一些可用于处理其他 **部署概念** 的策略。 - -我还将向您展示 **官方 Docker 镜像**,其中包括 **Gunicorn 和 Uvicorn worker** 以及一些对简单情况有用的默认配置。 +在关于 [容器中的 FastAPI - Docker](docker.md){.internal-link target=_blank} 的下一章中,我将介绍一些可用于处理其他**部署概念**的策略。 -在那里,我还将向您展示如何 **从头开始构建自己的镜像** 以运行单个 Uvicorn 进程(没有 Gunicorn)。 这是一个简单的过程,并且可能是您在使用像 **Kubernetes** 这样的分布式容器管理系统时想要做的事情。 +我将向您展示如何**从零开始构建自己的镜像**,以运行一个单独的 Uvicorn 进程。这个过程相对简单,并且在使用 **Kubernetes** 等分布式容器管理系统时,这通常是您需要采取的方法。 ## 回顾 -您可以使用**Gunicorn**(或Uvicorn)作为Uvicorn工作进程的进程管理器,以利用**多核CPU**,**并行运行多个进程**。 +您可以在使用 `fastapi` 或 `uvicorn` 命令时,通过 `--workers` CLI 选项启用多个工作进程(workers),以充分利用**多核 CPU**,以**并行运行多个进程**。 如果您要设置**自己的部署系统**,同时自己处理其他部署概念,则可以使用这些工具和想法。 diff --git a/docs/zh/docs/index.md b/docs/zh/docs/index.md index d3e9e3112..94cf8745c 100644 --- a/docs/zh/docs/index.md +++ b/docs/zh/docs/index.md @@ -11,11 +11,11 @@ FastAPI 框架,高性能,易于学习,高效编码,生产可用

- - Test + + Test - - Coverage + + Coverage Package version diff --git a/docs/zh/docs/tutorial/bigger-applications.md b/docs/zh/docs/tutorial/bigger-applications.md index 318e10fd7..554bc654f 100644 --- a/docs/zh/docs/tutorial/bigger-applications.md +++ b/docs/zh/docs/tutorial/bigger-applications.md @@ -52,7 +52,7 @@ from app.routers import items * 还有一个子目录 `app/internal/` 包含另一个 `__init__.py` 文件,因此它是又一个「Python 子包」:`app.internal`。 * `app/internal/admin.py` 是另一个子模块:`app.internal.admin`。 - + 带有注释的同一文件结构: @@ -244,7 +244,7 @@ from .dependencies import get_token_header 请记住我们的程序/文件结构是怎样的: - + --- diff --git a/docs/zh/docs/tutorial/first-steps.md b/docs/zh/docs/tutorial/first-steps.md index c4ff460e0..80a34116a 100644 --- a/docs/zh/docs/tutorial/first-steps.md +++ b/docs/zh/docs/tutorial/first-steps.md @@ -11,26 +11,42 @@

```console -$ uvicorn main:app --reload +$ fastapi dev main.py -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -INFO: Started reloader process [28720] -INFO: Started server process [28722] -INFO: Waiting for application startup. -INFO: Application startup complete. -``` + FastAPI Starting development server 🚀 -
+ Searching for package file structure from directories + with __init__.py files + Importing from /home/user/code/awesomeapp -/// note + module 🐍 main.py -`uvicorn main:app` 命令含义如下: + code Importing the FastAPI app object from the module with + the following code: -* `main`:`main.py` 文件(一个 Python「模块」)。 -* `app`:在 `main.py` 文件中通过 `app = FastAPI()` 创建的对象。 -* `--reload`:让服务器在更新代码后重新启动。仅在开发时使用该选项。 + from main import app -/// + app Using import string: main:app + + server Server started at http://127.0.0.1:8000 + server Documentation at http://127.0.0.1:8000/docs + + tip Running in development mode, for production use: + fastapi run + + Logs: + + INFO Will watch for changes in these directories: + ['/home/user/code/awesomeapp'] + INFO Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C + to quit) + INFO Started reloader process [383138] using WatchFiles + INFO Started server process [383153] + INFO Waiting for application startup. + INFO Application startup complete. +``` + + 在输出中,会有一行信息像下面这样: @@ -38,7 +54,6 @@ $ uvicorn main:app --reload INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` - 该行显示了你的应用在本机所提供服务的 URL 地址。 ### 查看 @@ -63,7 +78,7 @@ INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) 前往 http://127.0.0.1:8000/redoc。 -你将会看到可选的自动生成文档 (由 ReDoc 提供): +你将会看到可选的自动生成文档 (由 ReDoc 提供): ![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) @@ -77,9 +92,9 @@ INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) #### API「模式」 -在这种场景下,OpenAPI 是一种规定如何定义 API 模式的规范。 +在这种场景下,OpenAPI 是一种规定如何定义 API 模式的规范。 -定义的 OpenAPI 模式将包括你的 API 路径,以及它们可能使用的参数等等。 +「模式」的定义包括你的 API 路径,以及它们可能使用的参数等等。 #### 数据「模式」 @@ -93,7 +108,7 @@ OpenAPI 为你的 API 定义 API 模式。该模式中包含了你的 API 发送 #### 查看 `openapi.json` -如果你对原始的 OpenAPI 模式长什么样子感到好奇,其实它只是一个自动生成的包含了所有 API 描述的 JSON。 +如果你对原始的 OpenAPI 模式长什么样子感到好奇,FastAPI 自动生成了包含所有 API 描述的 JSON(模式)。 你可以直接在:http://127.0.0.1:8000/openapi.json 看到它。 @@ -101,7 +116,7 @@ OpenAPI 为你的 API 定义 API 模式。该模式中包含了你的 API 发送 ```JSON { - "openapi": "3.0.2", + "openapi": "3.1.0", "info": { "title": "FastAPI", "version": "0.1.0" @@ -140,7 +155,7 @@ OpenAPI 为你的 API 定义 API 模式。该模式中包含了你的 API 发送 `FastAPI` 是直接从 `Starlette` 继承的类。 -你可以通过 `FastAPI` 使用所有的 Starlette 的功能。 +你可以通过 `FastAPI` 使用所有的 Starlette 的功能。 /// @@ -152,34 +167,6 @@ OpenAPI 为你的 API 定义 API 模式。该模式中包含了你的 API 发送 这个实例将是创建你所有 API 的主要交互对象。 -这个 `app` 同样在如下命令中被 `uvicorn` 所引用: - -
- -```console -$ uvicorn main:app --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- -如果你像下面这样创建应用: - -{* ../../docs_src/first_steps/tutorial002.py hl[3] *} - -将代码放入 `main.py` 文件中,然后你可以像下面这样运行 `uvicorn`: - -
- -```console -$ uvicorn main:my_awesome_api --reload - -INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) -``` - -
- ### 步骤 3:创建一个*路径操作* #### 路径 @@ -279,13 +266,13 @@ https://example.com/items/foo /// tip -您可以随意使用任何一个操作(HTTP方法)。 +你可以随意使用任何一个操作(HTTP方法)。 **FastAPI** 没有强制要求操作有任何特定的含义。 此处提供的信息仅作为指导,而不是要求。 -比如,当使用 GraphQL 时通常你所有的动作都通过 `post` 一种方法执行。 +比如,当使用 GraphQL 时通常你所有的动作都通过 `POST` 一种方法执行。 /// @@ -331,6 +318,6 @@ https://example.com/items/foo * 导入 `FastAPI`。 * 创建一个 `app` 实例。 -* 编写一个**路径操作装饰器**(如 `@app.get("/")`)。 -* 编写一个**路径操作函数**(如上面的 `def root(): ...`)。 -* 运行开发服务器(如 `uvicorn main:app --reload`)。 +* 编写一个**路径操作装饰器**,如 `@app.get("/")`。 +* 定义一个**路径操作函数**,如 `def root(): ...`。 +* 使用命令 `fastapi dev` 运行开发服务器。 diff --git a/docs/zh/docs/tutorial/index.md b/docs/zh/docs/tutorial/index.md index ab19f02c5..3ca927337 100644 --- a/docs/zh/docs/tutorial/index.md +++ b/docs/zh/docs/tutorial/index.md @@ -1,34 +1,58 @@ # 教程 - 用户指南 -本教程将一步步向你展示如何使用 **FastAPI** 的绝大部分特性。 +本教程将一步步向您展示如何使用 **FastAPI** 的绝大部分特性。 -各个章节的内容循序渐进,但是又围绕着单独的主题,所以你可以直接跳转到某个章节以解决你的特定需求。 +各个章节的内容循序渐进,但是又围绕着单独的主题,所以您可以直接跳转到某个章节以解决您的特定需求。 -本教程同样可以作为将来的参考手册。 - -你可以随时回到本教程并查阅你需要的内容。 +本教程同样可以作为将来的参考手册,所以您可以随时回到本教程并查阅您需要的内容。 ## 运行代码 所有代码片段都可以复制后直接使用(它们实际上是经过测试的 Python 文件)。 -要运行任何示例,请将代码复制到 `main.py` 文件中,然后使用以下命令启动 `uvicorn`: +要运行任何示例,请将代码复制到 `main.py` 文件中,然后使用以下命令启动 `fastapi dev`:
```console -$ uvicorn main:app --reload +$ fastapi dev main.py + + FastAPI Starting development server 🚀 + + Searching for package file structure from directories + with __init__.py files + Importing from /home/user/code/awesomeapp + + module 🐍 main.py + + code Importing the FastAPI app object from the module with + the following code: + + from main import app + + app Using import string: main:app + + server Server started at http://127.0.0.1:8000 + server Documentation at http://127.0.0.1:8000/docs + + tip Running in development mode, for production use: + fastapi run + + Logs: -INFO: 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. + INFO Will watch for changes in these directories: + ['/home/user/code/awesomeapp'] + INFO Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C + to quit) + INFO Started reloader process [383138] using WatchFiles + INFO Started server process [383153] + INFO Waiting for application startup. + INFO Application startup complete. ```
-强烈建议你在本地编写或复制代码,对其进行编辑并运行。 +**强烈建议**您在本地编写或复制代码,对其进行编辑并运行。 在编辑器中使用 FastAPI 会真正地展现出它的优势:只需要编写很少的代码,所有的类型检查,代码补全等等。 @@ -36,48 +60,34 @@ $ uvicorn main:app --reload ## 安装 FastAPI -第一个步骤是安装 FastAPI。 +第一个步骤是安装 FastAPI. -为了使用本教程,你可能需要安装所有的可选依赖及对应功能: +请确保您创建并激活一个[虚拟环境](../virtual-environments.md){.internal-link target=_blank},然后**安装 FastAPI**:
```console -$ pip install "fastapi[all]" +$ pip install "fastapi[standard]" ---> 100% ```
-......以上安装还包括了 `uvicorn`,你可以将其用作运行代码的服务器。 - /// note -你也可以分开来安装。 - -假如你想将应用程序部署到生产环境,你可能要执行以下操作: - -``` -pip install fastapi -``` - -并且安装`uvicorn`来作为服务器: - -``` -pip install "uvicorn[standard]" -``` +当您使用 `pip install "fastapi[standard]"` 进行安装时,它会附带一些默认的可选标准依赖项。 -然后对你想使用的每个可选依赖项也执行相同的操作。 +如果您不想安装这些可选依赖,可以选择安装 `pip install fastapi`。 /// ## 进阶用户指南 -在本**教程-用户指南**之后,你可以阅读**进阶用户指南**。 +在本**教程-用户指南**之后,您可以阅读**进阶用户指南**。 **进阶用户指南**以本教程为基础,使用相同的概念,并教授一些额外的特性。 -但是你应该先阅读**教程-用户指南**(即你现在正在阅读的内容)。 +但是您应该先阅读**教程-用户指南**(即您现在正在阅读的内容)。 -教程经过精心设计,使你可以仅通过**教程-用户指南**来开发一个完整的应用程序,然后根据你的需要,使用**进阶用户指南**中的一些其他概念,以不同的方式来扩展它。 +教程经过精心设计,使您可以仅通过**教程-用户指南**来开发一个完整的应用程序,然后根据您的需要,使用**进阶用户指南**中的一些其他概念,以不同的方式来扩展它。 diff --git a/docs/zh/docs/tutorial/query-params-str-validations.md b/docs/zh/docs/tutorial/query-params-str-validations.md index 2fba671f7..c2f9a7e9f 100644 --- a/docs/zh/docs/tutorial/query-params-str-validations.md +++ b/docs/zh/docs/tutorial/query-params-str-validations.md @@ -108,21 +108,6 @@ q: Union[str, None] = Query(default=None, min_length=3) {* ../../docs_src/query_params_str_validations/tutorial006.py hl[7] *} -### 使用省略号(`...`)声明必需参数 - -有另一种方法可以显式的声明一个值是必需的,即将默认参数的默认值设为 `...` : - -{* ../../docs_src/query_params_str_validations/tutorial006b.py hl[7] *} - -/// info - -如果你之前没见过 `...` 这种用法:它是一个特殊的单独值,它是 Python 的一部分并且被称为“Ellipsis”(意为省略号 —— 译者注)。 -Pydantic 和 FastAPI 使用它来显式的声明需要一个值。 - -/// - -这将使 **FastAPI** 知道此查询参数是必需的。 - ### 使用`None`声明必需参数 你可以声明一个参数可以接收`None`值,但它仍然是必需的。这将强制客户端发送一个值,即使该值是`None`。 @@ -137,18 +122,6 @@ Pydantic 是 FastAPI 中所有数据验证和序列化的核心,当你在没 /// -### 使用Pydantic中的`Required`代替省略号(`...`) - -如果你觉得使用 `...` 不舒服,你也可以从 Pydantic 导入并使用 `Required`: - -{* ../../docs_src/query_params_str_validations/tutorial006d.py hl[2,8] *} - -/// tip - -请记住,在大多数情况下,当你需要某些东西时,可以简单地省略 `default` 参数,因此你通常不必使用 `...` 或 `Required` - -/// - ## 查询参数列表 / 多个值 当你使用 `Query` 显式地定义查询参数时,你还可以声明它去接收一组值,或换句话来说,接收多个值。 diff --git a/docs_src/configure_swagger_ui/tutorial002.py b/docs_src/configure_swagger_ui/tutorial002.py index cc569ce45..cc75c2196 100644 --- a/docs_src/configure_swagger_ui/tutorial002.py +++ b/docs_src/configure_swagger_ui/tutorial002.py @@ -1,6 +1,6 @@ from fastapi import FastAPI -app = FastAPI(swagger_ui_parameters={"syntaxHighlight.theme": "obsidian"}) +app = FastAPI(swagger_ui_parameters={"syntaxHighlight": {"theme": "obsidian"}}) @app.get("/users/{username}") diff --git a/docs_src/custom_docs_ui/tutorial001.py b/docs_src/custom_docs_ui/tutorial001.py index f7ceb0c2f..1cfcce19a 100644 --- a/docs_src/custom_docs_ui/tutorial001.py +++ b/docs_src/custom_docs_ui/tutorial001.py @@ -29,7 +29,7 @@ async def redoc_html(): return get_redoc_html( openapi_url=app.openapi_url, title=app.title + " - ReDoc", - redoc_js_url="https://unpkg.com/redoc@next/bundles/redoc.standalone.js", + redoc_js_url="https://unpkg.com/redoc@2/bundles/redoc.standalone.js", ) diff --git a/docs_src/header_param_models/tutorial003.py b/docs_src/header_param_models/tutorial003.py new file mode 100644 index 000000000..dc2eb74bd --- /dev/null +++ b/docs_src/header_param_models/tutorial003.py @@ -0,0 +1,19 @@ +from typing import List, Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: List[str] = [] + + +@app.get("/items/") +async def read_items(headers: CommonHeaders = Header(convert_underscores=False)): + return headers diff --git a/docs_src/header_param_models/tutorial003_an.py b/docs_src/header_param_models/tutorial003_an.py new file mode 100644 index 000000000..e3edb1189 --- /dev/null +++ b/docs_src/header_param_models/tutorial003_an.py @@ -0,0 +1,22 @@ +from typing import List, Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel +from typing_extensions import Annotated + +app = FastAPI() + + +class CommonHeaders(BaseModel): + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: List[str] = [] + + +@app.get("/items/") +async def read_items( + headers: Annotated[CommonHeaders, Header(convert_underscores=False)], +): + return headers diff --git a/docs_src/header_param_models/tutorial003_an_py310.py b/docs_src/header_param_models/tutorial003_an_py310.py new file mode 100644 index 000000000..07bfa83bf --- /dev/null +++ b/docs_src/header_param_models/tutorial003_an_py310.py @@ -0,0 +1,21 @@ +from typing import Annotated + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + host: str + save_data: bool + if_modified_since: str | None = None + traceparent: str | None = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items( + headers: Annotated[CommonHeaders, Header(convert_underscores=False)], +): + return headers diff --git a/docs_src/header_param_models/tutorial003_an_py39.py b/docs_src/header_param_models/tutorial003_an_py39.py new file mode 100644 index 000000000..8be6b01d0 --- /dev/null +++ b/docs_src/header_param_models/tutorial003_an_py39.py @@ -0,0 +1,21 @@ +from typing import Annotated, Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items( + headers: Annotated[CommonHeaders, Header(convert_underscores=False)], +): + return headers diff --git a/docs_src/header_param_models/tutorial003_py310.py b/docs_src/header_param_models/tutorial003_py310.py new file mode 100644 index 000000000..65e92a28c --- /dev/null +++ b/docs_src/header_param_models/tutorial003_py310.py @@ -0,0 +1,17 @@ +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + host: str + save_data: bool + if_modified_since: str | None = None + traceparent: str | None = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: CommonHeaders = Header(convert_underscores=False)): + return headers diff --git a/docs_src/header_param_models/tutorial003_py39.py b/docs_src/header_param_models/tutorial003_py39.py new file mode 100644 index 000000000..848c34111 --- /dev/null +++ b/docs_src/header_param_models/tutorial003_py39.py @@ -0,0 +1,19 @@ +from typing import Union + +from fastapi import FastAPI, Header +from pydantic import BaseModel + +app = FastAPI() + + +class CommonHeaders(BaseModel): + host: str + save_data: bool + if_modified_since: Union[str, None] = None + traceparent: Union[str, None] = None + x_tag: list[str] = [] + + +@app.get("/items/") +async def read_items(headers: CommonHeaders = Header(convert_underscores=False)): + return headers diff --git a/docs_src/query_params_str_validations/tutorial006b.py b/docs_src/query_params_str_validations/tutorial006b.py deleted file mode 100644 index a8d69c889..000000000 --- a/docs_src/query_params_str_validations/tutorial006b.py +++ /dev/null @@ -1,11 +0,0 @@ -from fastapi import FastAPI, Query - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: str = Query(default=..., min_length=3)): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial006b_an.py b/docs_src/query_params_str_validations/tutorial006b_an.py deleted file mode 100644 index ea3b02583..000000000 --- a/docs_src/query_params_str_validations/tutorial006b_an.py +++ /dev/null @@ -1,12 +0,0 @@ -from fastapi import FastAPI, Query -from typing_extensions import Annotated - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: Annotated[str, Query(min_length=3)] = ...): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial006b_an_py39.py b/docs_src/query_params_str_validations/tutorial006b_an_py39.py deleted file mode 100644 index 687a9f544..000000000 --- a/docs_src/query_params_str_validations/tutorial006b_an_py39.py +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Annotated - -from fastapi import FastAPI, Query - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: Annotated[str, Query(min_length=3)] = ...): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial006c.py b/docs_src/query_params_str_validations/tutorial006c.py index 2ac148c94..0a0e820da 100644 --- a/docs_src/query_params_str_validations/tutorial006c.py +++ b/docs_src/query_params_str_validations/tutorial006c.py @@ -6,7 +6,7 @@ app = FastAPI() @app.get("/items/") -async def read_items(q: Union[str, None] = Query(default=..., min_length=3)): +async def read_items(q: Union[str, None] = Query(min_length=3)): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) diff --git a/docs_src/query_params_str_validations/tutorial006c_an.py b/docs_src/query_params_str_validations/tutorial006c_an.py index 10bf26a57..55c4f4adc 100644 --- a/docs_src/query_params_str_validations/tutorial006c_an.py +++ b/docs_src/query_params_str_validations/tutorial006c_an.py @@ -7,7 +7,7 @@ app = FastAPI() @app.get("/items/") -async def read_items(q: Annotated[Union[str, None], Query(min_length=3)] = ...): +async def read_items(q: Annotated[Union[str, None], Query(min_length=3)]): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) diff --git a/docs_src/query_params_str_validations/tutorial006c_an_py310.py b/docs_src/query_params_str_validations/tutorial006c_an_py310.py index 1ab0a7d53..2995d9c97 100644 --- a/docs_src/query_params_str_validations/tutorial006c_an_py310.py +++ b/docs_src/query_params_str_validations/tutorial006c_an_py310.py @@ -6,7 +6,7 @@ app = FastAPI() @app.get("/items/") -async def read_items(q: Annotated[str | None, Query(min_length=3)] = ...): +async def read_items(q: Annotated[str | None, Query(min_length=3)]): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) diff --git a/docs_src/query_params_str_validations/tutorial006c_an_py39.py b/docs_src/query_params_str_validations/tutorial006c_an_py39.py index ac1273331..76a1cd49a 100644 --- a/docs_src/query_params_str_validations/tutorial006c_an_py39.py +++ b/docs_src/query_params_str_validations/tutorial006c_an_py39.py @@ -6,7 +6,7 @@ app = FastAPI() @app.get("/items/") -async def read_items(q: Annotated[Union[str, None], Query(min_length=3)] = ...): +async def read_items(q: Annotated[Union[str, None], Query(min_length=3)]): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) diff --git a/docs_src/query_params_str_validations/tutorial006c_py310.py b/docs_src/query_params_str_validations/tutorial006c_py310.py index 82dd9e5d7..88b499c7a 100644 --- a/docs_src/query_params_str_validations/tutorial006c_py310.py +++ b/docs_src/query_params_str_validations/tutorial006c_py310.py @@ -4,7 +4,7 @@ app = FastAPI() @app.get("/items/") -async def read_items(q: str | None = Query(default=..., min_length=3)): +async def read_items(q: str | None = Query(min_length=3)): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) diff --git a/docs_src/query_params_str_validations/tutorial006d.py b/docs_src/query_params_str_validations/tutorial006d.py deleted file mode 100644 index a8d69c889..000000000 --- a/docs_src/query_params_str_validations/tutorial006d.py +++ /dev/null @@ -1,11 +0,0 @@ -from fastapi import FastAPI, Query - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: str = Query(default=..., min_length=3)): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial006d_an.py b/docs_src/query_params_str_validations/tutorial006d_an.py deleted file mode 100644 index ea3b02583..000000000 --- a/docs_src/query_params_str_validations/tutorial006d_an.py +++ /dev/null @@ -1,12 +0,0 @@ -from fastapi import FastAPI, Query -from typing_extensions import Annotated - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: Annotated[str, Query(min_length=3)] = ...): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial006d_an_py39.py b/docs_src/query_params_str_validations/tutorial006d_an_py39.py deleted file mode 100644 index 687a9f544..000000000 --- a/docs_src/query_params_str_validations/tutorial006d_an_py39.py +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Annotated - -from fastapi import FastAPI, Query - -app = FastAPI() - - -@app.get("/items/") -async def read_items(q: Annotated[str, Query(min_length=3)] = ...): - results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - if q: - results.update({"q": q}) - return results diff --git a/docs_src/query_params_str_validations/tutorial015_an.py b/docs_src/query_params_str_validations/tutorial015_an.py new file mode 100644 index 000000000..f2ec6db12 --- /dev/null +++ b/docs_src/query_params_str_validations/tutorial015_an.py @@ -0,0 +1,31 @@ +import random +from typing import Union + +from fastapi import FastAPI +from pydantic import AfterValidator +from typing_extensions import Annotated + +app = FastAPI() + +data = { + "isbn-9781529046137": "The Hitchhiker's Guide to the Galaxy", + "imdb-tt0371724": "The Hitchhiker's Guide to the Galaxy", + "isbn-9781439512982": "Isaac Asimov: The Complete Stories, Vol. 2", +} + + +def check_valid_id(id: str): + if not id.startswith(("isbn-", "imdb-")): + raise ValueError('Invalid ID format, it must start with "isbn-" or "imdb-"') + return id + + +@app.get("/items/") +async def read_items( + id: Annotated[Union[str, None], AfterValidator(check_valid_id)] = None, +): + if id: + item = data.get(id) + else: + id, item = random.choice(list(data.items())) + return {"id": id, "name": item} diff --git a/docs_src/query_params_str_validations/tutorial015_an_py310.py b/docs_src/query_params_str_validations/tutorial015_an_py310.py new file mode 100644 index 000000000..35f368094 --- /dev/null +++ b/docs_src/query_params_str_validations/tutorial015_an_py310.py @@ -0,0 +1,30 @@ +import random +from typing import Annotated + +from fastapi import FastAPI +from pydantic import AfterValidator + +app = FastAPI() + +data = { + "isbn-9781529046137": "The Hitchhiker's Guide to the Galaxy", + "imdb-tt0371724": "The Hitchhiker's Guide to the Galaxy", + "isbn-9781439512982": "Isaac Asimov: The Complete Stories, Vol. 2", +} + + +def check_valid_id(id: str): + if not id.startswith(("isbn-", "imdb-")): + raise ValueError('Invalid ID format, it must start with "isbn-" or "imdb-"') + return id + + +@app.get("/items/") +async def read_items( + id: Annotated[str | None, AfterValidator(check_valid_id)] = None, +): + if id: + item = data.get(id) + else: + id, item = random.choice(list(data.items())) + return {"id": id, "name": item} diff --git a/docs_src/query_params_str_validations/tutorial015_an_py39.py b/docs_src/query_params_str_validations/tutorial015_an_py39.py new file mode 100644 index 000000000..989b6d2c2 --- /dev/null +++ b/docs_src/query_params_str_validations/tutorial015_an_py39.py @@ -0,0 +1,30 @@ +import random +from typing import Annotated, Union + +from fastapi import FastAPI +from pydantic import AfterValidator + +app = FastAPI() + +data = { + "isbn-9781529046137": "The Hitchhiker's Guide to the Galaxy", + "imdb-tt0371724": "The Hitchhiker's Guide to the Galaxy", + "isbn-9781439512982": "Isaac Asimov: The Complete Stories, Vol. 2", +} + + +def check_valid_id(id: str): + if not id.startswith(("isbn-", "imdb-")): + raise ValueError('Invalid ID format, it must start with "isbn-" or "imdb-"') + return id + + +@app.get("/items/") +async def read_items( + id: Annotated[Union[str, None], AfterValidator(check_valid_id)] = None, +): + if id: + item = data.get(id) + else: + id, item = random.choice(list(data.items())) + return {"id": id, "name": item} diff --git a/docs_src/security/tutorial004.py b/docs_src/security/tutorial004.py index 91d161b8a..222589618 100644 --- a/docs_src/security/tutorial004.py +++ b/docs_src/security/tutorial004.py @@ -95,7 +95,7 @@ async def get_current_user(token: str = Depends(oauth2_scheme)): ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) - username: str = payload.get("sub") + username = payload.get("sub") if username is None: raise credentials_exception token_data = TokenData(username=username) diff --git a/docs_src/security/tutorial004_an.py b/docs_src/security/tutorial004_an.py index df50754af..e2221cd39 100644 --- a/docs_src/security/tutorial004_an.py +++ b/docs_src/security/tutorial004_an.py @@ -96,7 +96,7 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) - username: str = payload.get("sub") + username = payload.get("sub") if username is None: raise credentials_exception token_data = TokenData(username=username) diff --git a/docs_src/security/tutorial004_an_py310.py b/docs_src/security/tutorial004_an_py310.py index eff54ef01..a3f74fc0e 100644 --- a/docs_src/security/tutorial004_an_py310.py +++ b/docs_src/security/tutorial004_an_py310.py @@ -95,7 +95,7 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) - username: str = payload.get("sub") + username = payload.get("sub") if username is None: raise credentials_exception token_data = TokenData(username=username) diff --git a/docs_src/security/tutorial004_an_py39.py b/docs_src/security/tutorial004_an_py39.py index 0455b500c..b33d677ed 100644 --- a/docs_src/security/tutorial004_an_py39.py +++ b/docs_src/security/tutorial004_an_py39.py @@ -95,7 +95,7 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) - username: str = payload.get("sub") + username = payload.get("sub") if username is None: raise credentials_exception token_data = TokenData(username=username) diff --git a/docs_src/security/tutorial004_py310.py b/docs_src/security/tutorial004_py310.py index 78bee22a3..d46ce26bf 100644 --- a/docs_src/security/tutorial004_py310.py +++ b/docs_src/security/tutorial004_py310.py @@ -94,7 +94,7 @@ async def get_current_user(token: str = Depends(oauth2_scheme)): ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) - username: str = payload.get("sub") + username = payload.get("sub") if username is None: raise credentials_exception token_data = TokenData(username=username) diff --git a/docs_src/security/tutorial005_an.py b/docs_src/security/tutorial005_an.py index 5b67cb145..2e8bb3bdb 100644 --- a/docs_src/security/tutorial005_an.py +++ b/docs_src/security/tutorial005_an.py @@ -117,7 +117,7 @@ async def get_current_user( ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) - username: str = payload.get("sub") + username = payload.get("sub") if username is None: raise credentials_exception token_scopes = payload.get("scopes", []) diff --git a/docs_src/security/tutorial005_an_py310.py b/docs_src/security/tutorial005_an_py310.py index 297193e35..90781587f 100644 --- a/docs_src/security/tutorial005_an_py310.py +++ b/docs_src/security/tutorial005_an_py310.py @@ -116,7 +116,7 @@ async def get_current_user( ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) - username: str = payload.get("sub") + username = payload.get("sub") if username is None: raise credentials_exception token_scopes = payload.get("scopes", []) diff --git a/docs_src/security/tutorial005_an_py39.py b/docs_src/security/tutorial005_an_py39.py index 1acf47bdc..a5192d8d6 100644 --- a/docs_src/security/tutorial005_an_py39.py +++ b/docs_src/security/tutorial005_an_py39.py @@ -1,5 +1,5 @@ from datetime import datetime, timedelta, timezone -from typing import Annotated, List, Union +from typing import Annotated, Union import jwt from fastapi import Depends, FastAPI, HTTPException, Security, status @@ -44,7 +44,7 @@ class Token(BaseModel): class TokenData(BaseModel): username: Union[str, None] = None - scopes: List[str] = [] + scopes: list[str] = [] class User(BaseModel): @@ -116,7 +116,7 @@ async def get_current_user( ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) - username: str = payload.get("sub") + username = payload.get("sub") if username is None: raise credentials_exception token_scopes = payload.get("scopes", []) diff --git a/fastapi/__init__.py b/fastapi/__init__.py index e3e0200ae..80eb783da 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.115.8" +__version__ = "0.115.12" from starlette import status as status diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index e2866b488..84dfa4d03 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -133,9 +133,9 @@ def get_param_sub_dependant( def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: - assert callable( - depends.dependency - ), "A parameter-less dependency must have a callable dependency" + assert callable(depends.dependency), ( + "A parameter-less dependency must have a callable dependency" + ) return get_sub_dependant(depends=depends, dependency=depends.dependency, path=path) @@ -302,9 +302,9 @@ def get_dependant( type_annotation=param_details.type_annotation, dependant=dependant, ): - assert ( - param_details.field is None - ), f"Cannot specify multiple FastAPI annotations for {param_name!r}" + assert param_details.field is None, ( + f"Cannot specify multiple FastAPI annotations for {param_name!r}" + ) continue assert param_details.field is not None if isinstance(param_details.field.field_info, params.Body): @@ -439,9 +439,9 @@ def analyze_param( ), ): assert depends is None, f"Cannot specify `Depends` for type {type_annotation!r}" - assert ( - field_info is None - ), f"Cannot specify FastAPI annotation for type {type_annotation!r}" + assert field_info is None, ( + f"Cannot specify FastAPI annotation for type {type_annotation!r}" + ) # Handle default assignations, neither field_info nor depends was not found in Annotated nor default value elif field_info is None and depends is None: default_value = value if value is not inspect.Signature.empty else RequiredParam @@ -494,9 +494,9 @@ def analyze_param( field_info=field_info, ) if is_path_param: - assert is_scalar_field( - field=field - ), "Path params must be of one of the supported types" + assert is_scalar_field(field=field), ( + "Path params must be of one of the supported types" + ) elif isinstance(field_info, params.Query): assert ( is_scalar_field(field) @@ -521,9 +521,9 @@ def add_param_to_fields(*, field: ModelField, dependant: Dependant) -> None: elif field_info_in == params.ParamTypes.header: dependant.header_params.append(field) else: - assert ( - field_info_in == params.ParamTypes.cookie - ), f"non-body parameters must be in path, query, header or cookie: {field.name}" + assert field_info_in == params.ParamTypes.cookie, ( + f"non-body parameters must be in path, query, header or cookie: {field.name}" + ) dependant.cookie_params.append(field) @@ -750,9 +750,15 @@ def request_params_to_args( first_field = fields[0] fields_to_extract = fields single_not_embedded_field = False + default_convert_underscores = True if len(fields) == 1 and lenient_issubclass(first_field.type_, BaseModel): fields_to_extract = get_cached_model_fields(first_field.type_) single_not_embedded_field = True + # If headers are in a Pydantic model, the way to disable convert_underscores + # would be with Header(convert_underscores=False) at the Pydantic model level + default_convert_underscores = getattr( + first_field.field_info, "convert_underscores", True + ) params_to_process: Dict[str, Any] = {} @@ -763,7 +769,9 @@ def request_params_to_args( if isinstance(received_params, Headers): # Handle fields extracted from a Pydantic Model for a header, each field # doesn't have a FieldInfo of type Header with the default convert_underscores=True - convert_underscores = getattr(field.field_info, "convert_underscores", True) + convert_underscores = getattr( + field.field_info, "convert_underscores", default_convert_underscores + ) if convert_underscores: alias = ( field.alias @@ -782,9 +790,9 @@ def request_params_to_args( if single_not_embedded_field: field_info = first_field.field_info - assert isinstance( - field_info, params.Param - ), "Params must be subclasses of Param" + assert isinstance(field_info, params.Param), ( + "Params must be subclasses of Param" + ) loc: Tuple[str, ...] = (field_info.in_.value,) v_, errors_ = _validate_value_with_model_field( field=first_field, value=params_to_process, values=values, loc=loc @@ -794,9 +802,9 @@ def request_params_to_args( for field in fields: value = _get_multidict_value(field, received_params) field_info = field.field_info - assert isinstance( - field_info, params.Param - ), "Params must be subclasses of Param" + assert isinstance(field_info, params.Param), ( + "Params must be subclasses of Param" + ) loc = (field_info.in_.value, field.alias) v_, errors_ = _validate_value_with_model_field( field=field, value=value, values=values, loc=loc diff --git a/fastapi/openapi/docs.py b/fastapi/openapi/docs.py index c2ec358d2..f181b43c1 100644 --- a/fastapi/openapi/docs.py +++ b/fastapi/openapi/docs.py @@ -188,7 +188,7 @@ def get_redoc_html( It is normally set to a CDN URL. """ ), - ] = "https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js", + ] = "https://cdn.jsdelivr.net/npm/redoc@2/bundles/redoc.standalone.js", redoc_favicon_url: Annotated[ str, Doc( diff --git a/fastapi/openapi/utils.py b/fastapi/openapi/utils.py index 947eca948..808646cc2 100644 --- a/fastapi/openapi/utils.py +++ b/fastapi/openapi/utils.py @@ -32,6 +32,7 @@ from fastapi.utils import ( generate_operation_id_for_path, is_body_allowed_for_status_code, ) +from pydantic import BaseModel from starlette.responses import JSONResponse from starlette.routing import BaseRoute from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY @@ -113,6 +114,13 @@ def _get_openapi_operation_parameters( (ParamTypes.header, header_params), (ParamTypes.cookie, cookie_params), ] + default_convert_underscores = True + if len(flat_dependant.header_params) == 1: + first_field = flat_dependant.header_params[0] + if lenient_issubclass(first_field.type_, BaseModel): + default_convert_underscores = getattr( + first_field.field_info, "convert_underscores", True + ) for param_type, param_group in parameter_groups: for param in param_group: field_info = param.field_info @@ -126,8 +134,21 @@ def _get_openapi_operation_parameters( field_mapping=field_mapping, separate_input_output_schemas=separate_input_output_schemas, ) + name = param.alias + convert_underscores = getattr( + param.field_info, + "convert_underscores", + default_convert_underscores, + ) + if ( + param_type == ParamTypes.header + and param.alias == param.name + and convert_underscores + ): + name = param.name.replace("_", "-") + parameter = { - "name": param.alias, + "name": name, "in": param_type.value, "required": param.required, "schema": param_schema, @@ -364,9 +385,9 @@ def get_openapi_path( openapi_response = operation_responses.setdefault( status_code_key, {} ) - assert isinstance( - process_response, dict - ), "An additional response must be a dict" + assert isinstance(process_response, dict), ( + "An additional response must be a dict" + ) field = route.response_fields.get(additional_status_code) additional_field_schema: Optional[Dict[str, Any]] = None if field: @@ -434,9 +455,9 @@ def get_fields_from_routes( route, routing.APIRoute ): if route.body_field: - assert isinstance( - route.body_field, ModelField - ), "A request body must be a Pydantic Field" + assert isinstance(route.body_field, ModelField), ( + "A request body must be a Pydantic Field" + ) body_fields_from_routes.append(route.body_field) if route.response_field: responses_from_routes.append(route.response_field) diff --git a/fastapi/routing.py b/fastapi/routing.py index 8ea4bb219..457481e32 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -504,9 +504,9 @@ class APIRoute(routing.Route): status_code = int(status_code) self.status_code = status_code if self.response_model: - assert is_body_allowed_for_status_code( - status_code - ), f"Status code {status_code} must not have a response body" + assert is_body_allowed_for_status_code(status_code), ( + f"Status code {status_code} must not have a response body" + ) response_name = "Response_" + self.unique_id self.response_field = create_model_field( name=response_name, @@ -537,9 +537,9 @@ class APIRoute(routing.Route): assert isinstance(response, dict), "An additional response must be a dict" model = response.get("model") if model: - assert is_body_allowed_for_status_code( - additional_status_code - ), f"Status code {additional_status_code} must not have a response body" + assert is_body_allowed_for_status_code(additional_status_code), ( + f"Status code {additional_status_code} must not have a response body" + ) response_name = f"Response_{additional_status_code}_{self.unique_id}" response_field = create_model_field( name=response_name, type_=model, mode="serialization" @@ -844,9 +844,9 @@ class APIRouter(routing.Router): ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" - assert not prefix.endswith( - "/" - ), "A path prefix must not end with '/', as the routes will start with '/'" + assert not prefix.endswith("/"), ( + "A path prefix must not end with '/', as the routes will start with '/'" + ) self.prefix = prefix self.tags: List[Union[str, Enum]] = tags or [] self.dependencies = list(dependencies or []) @@ -1256,9 +1256,9 @@ class APIRouter(routing.Router): """ if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" - assert not prefix.endswith( - "/" - ), "A path prefix must not end with '/', as the routes will start with '/'" + assert not prefix.endswith("/"), ( + "A path prefix must not end with '/', as the routes will start with '/'" + ) else: for r in router.routes: path = getattr(r, "path") # noqa: B009 diff --git a/fastapi/security/http.py b/fastapi/security/http.py index e06f3d66d..9ab2df3c9 100644 --- a/fastapi/security/http.py +++ b/fastapi/security/http.py @@ -413,8 +413,11 @@ class HTTPDigest(HTTPBase): else: return None if scheme.lower() != "digest": - raise HTTPException( - status_code=HTTP_403_FORBIDDEN, - detail="Invalid authentication credentials", - ) + if self.auto_error: + raise HTTPException( + status_code=HTTP_403_FORBIDDEN, + detail="Invalid authentication credentials", + ) + else: + return None return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials) diff --git a/pyproject.toml b/pyproject.toml index 51d63fd44..1c540e2f6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -43,7 +43,7 @@ classifiers = [ "Topic :: Internet :: WWW/HTTP", ] dependencies = [ - "starlette>=0.40.0,<0.46.0", + "starlette>=0.40.0,<0.47.0", "pydantic>=1.7.4,!=1.8,!=1.8.1,!=2.0.0,!=2.0.1,!=2.1.0,<3.0.0", "typing-extensions>=4.8.0", ] diff --git a/requirements-docs-tests.txt b/requirements-docs-tests.txt index 908061a72..e7684a2e3 100644 --- a/requirements-docs-tests.txt +++ b/requirements-docs-tests.txt @@ -1,4 +1,4 @@ # For mkdocstrings and tests httpx >=0.23.0,<0.29.0 # For linting and generating docs versions -ruff ==0.6.4 +ruff ==0.11.2 diff --git a/requirements-docs.txt b/requirements-docs.txt index cd2e4e58e..9de608eb2 100644 --- a/requirements-docs.txt +++ b/requirements-docs.txt @@ -3,7 +3,7 @@ mkdocs-material==9.6.1 mdx-include >=1.4.1,<2.0.0 mkdocs-redirects>=1.2.1,<1.3.0 -typer == 0.12.5 +typer == 0.16.0 pyyaml >=5.3.1,<7.0.0 # For Material for MkDocs, Chinese search jieba==0.42.1 @@ -14,6 +14,6 @@ cairosvg==2.7.1 mkdocstrings[python]==0.26.1 griffe-typingdoc==0.2.7 # For griffe, it formats with black -black==24.10.0 +black==25.1.0 mkdocs-macros-plugin==1.3.7 markdown-include-variants==0.0.4 diff --git a/requirements-tests.txt b/requirements-tests.txt index 4a15844e4..b9f2b2b66 100644 --- a/requirements-tests.txt +++ b/requirements-tests.txt @@ -3,14 +3,14 @@ pytest >=7.1.3,<9.0.0 coverage[toml] >= 6.5.0,< 8.0 mypy ==1.8.0 -dirty-equals ==0.8.0 -sqlmodel==0.0.22 +dirty-equals ==0.9.0 +sqlmodel==0.0.24 flask >=1.1.2,<4.0.0 anyio[trio] >=3.2.1,<5.0.0 PyJWT==2.8.0 pyyaml >=5.3.1,<7.0.0 passlib[bcrypt] >=1.7.2,<2.0.0 -inline-snapshot==0.19.3 +inline-snapshot>=0.21.1 # types types-ujson ==5.10.0.20240515 types-orjson ==3.6.2 diff --git a/requirements-translations.txt b/requirements-translations.txt index a8f8a02d7..7a2a8004e 100644 --- a/requirements-translations.txt +++ b/requirements-translations.txt @@ -1 +1 @@ -pydantic-ai==0.0.15 +pydantic-ai==0.0.30 diff --git a/scripts/translate.py b/scripts/translate.py index ce11b3877..9a2136d1b 100644 --- a/scripts/translate.py +++ b/scripts/translate.py @@ -38,9 +38,9 @@ def get_langs() -> dict[str, str]: def generate_lang_path(*, lang: str, path: Path) -> Path: en_docs_path = Path("docs/en/docs") - assert str(path).startswith( - str(en_docs_path) - ), f"Path must be inside {en_docs_path}" + assert str(path).startswith(str(en_docs_path)), ( + f"Path must be inside {en_docs_path}" + ) lang_docs_path = Path(f"docs/{lang}/docs") out_path = Path(str(path).replace(str(en_docs_path), str(lang_docs_path))) return out_path @@ -56,9 +56,9 @@ def translate_page(*, lang: str, path: Path) -> None: lang_prompt_content = lang_prompt_path.read_text() en_docs_path = Path("docs/en/docs") - assert str(path).startswith( - str(en_docs_path) - ), f"Path must be inside {en_docs_path}" + assert str(path).startswith(str(en_docs_path)), ( + f"Path must be inside {en_docs_path}" + ) out_path = generate_lang_path(lang=lang, path=path) out_path.parent.mkdir(parents=True, exist_ok=True) original_content = path.read_text() diff --git a/tests/test_application.py b/tests/test_application.py index 5c62f5f6e..a7d50ea72 100644 --- a/tests/test_application.py +++ b/tests/test_application.py @@ -43,7 +43,7 @@ def test_redoc(): response = client.get("/redoc") assert response.status_code == 200, response.text assert response.headers["content-type"] == "text/html; charset=utf-8" - assert "redoc@next" in response.text + assert "redoc@2" in response.text def test_enum_status_code_response(): diff --git a/tests/test_enforce_once_required_parameter.py b/tests/test_enforce_once_required_parameter.py index b64f8341b..30329282f 100644 --- a/tests/test_enforce_once_required_parameter.py +++ b/tests/test_enforce_once_required_parameter.py @@ -48,7 +48,7 @@ expected_schema = { "type": "array", }, "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error " "Type", "type": "string"}, + "type": {"title": "Error Type", "type": "string"}, }, "required": ["loc", "msg", "type"], "title": "ValidationError", @@ -73,7 +73,7 @@ expected_schema = { "responses": { "200": { "content": {"application/json": {"schema": {}}}, - "description": "Successful " "Response", + "description": "Successful Response", }, "422": { "content": { @@ -83,7 +83,7 @@ expected_schema = { } } }, - "description": "Validation " "Error", + "description": "Validation Error", }, }, "summary": "Foo Handler", diff --git a/tests/test_generic_parameterless_depends.py b/tests/test_generic_parameterless_depends.py index fe13ff89b..5aa35320c 100644 --- a/tests/test_generic_parameterless_depends.py +++ b/tests/test_generic_parameterless_depends.py @@ -55,7 +55,7 @@ def test_openapi_schema(): "responses": { "200": { "content": {"application/json": {"schema": {}}}, - "description": "Successful " "Response", + "description": "Successful Response", } }, "summary": "A", @@ -67,7 +67,7 @@ def test_openapi_schema(): "responses": { "200": { "content": {"application/json": {"schema": {}}}, - "description": "Successful " "Response", + "description": "Successful Response", } }, "summary": "B", diff --git a/tests/test_modules_same_name_body/test_main.py b/tests/test_modules_same_name_body/test_main.py index cc165bdca..263d87df2 100644 --- a/tests/test_modules_same_name_body/test_main.py +++ b/tests/test_modules_same_name_body/test_main.py @@ -1,3 +1,4 @@ +import pytest from fastapi.testclient import TestClient from .app.main import app @@ -5,29 +6,22 @@ from .app.main import app client = TestClient(app) -def test_post_a(): +@pytest.mark.parametrize( + "path", ["/a/compute", "/a/compute/", "/b/compute", "/b/compute/"] +) +def test_post(path): data = {"a": 2, "b": "foo"} - response = client.post("/a/compute", json=data) + response = client.post(path, json=data) assert response.status_code == 200, response.text - data = response.json() + assert data == response.json() -def test_post_a_invalid(): +@pytest.mark.parametrize( + "path", ["/a/compute", "/a/compute/", "/b/compute", "/b/compute/"] +) +def test_post_invalid(path): data = {"a": "bar", "b": "foo"} - response = client.post("/a/compute", json=data) - assert response.status_code == 422, response.text - - -def test_post_b(): - data = {"a": 2, "b": "foo"} - response = client.post("/b/compute/", json=data) - assert response.status_code == 200, response.text - data = response.json() - - -def test_post_b_invalid(): - data = {"a": "bar", "b": "foo"} - response = client.post("/b/compute/", json=data) + response = client.post(path, json=data) assert response.status_code == 422, response.text diff --git a/tests/test_repeated_dependency_schema.py b/tests/test_repeated_dependency_schema.py index d7d0dfa05..c21829bd9 100644 --- a/tests/test_repeated_dependency_schema.py +++ b/tests/test_repeated_dependency_schema.py @@ -41,7 +41,7 @@ schema = { "type": "array", }, "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error " "Type", "type": "string"}, + "type": {"title": "Error Type", "type": "string"}, }, "required": ["loc", "msg", "type"], "title": "ValidationError", @@ -66,7 +66,7 @@ schema = { "responses": { "200": { "content": {"application/json": {"schema": {}}}, - "description": "Successful " "Response", + "description": "Successful Response", }, "422": { "content": { @@ -76,7 +76,7 @@ schema = { } } }, - "description": "Validation " "Error", + "description": "Validation Error", }, }, "summary": "Get Deps", diff --git a/tests/test_security_http_digest_optional.py b/tests/test_security_http_digest_optional.py index 1e6eb8bd7..0d66f9c72 100644 --- a/tests/test_security_http_digest_optional.py +++ b/tests/test_security_http_digest_optional.py @@ -37,8 +37,8 @@ def test_security_http_digest_incorrect_scheme_credentials(): response = client.get( "/users/me", headers={"Authorization": "Other invalidauthorization"} ) - assert response.status_code == 403, response.text - assert response.json() == {"detail": "Invalid authentication credentials"} + assert response.status_code == 200, response.text + assert response.json() == {"msg": "Create an account first"} def test_openapi_schema(): diff --git a/tests/test_tutorial/test_configure_swagger_ui/test_tutorial001.py b/tests/test_tutorial/test_configure_swagger_ui/test_tutorial001.py index 72db54bd2..a04dba219 100644 --- a/tests/test_tutorial/test_configure_swagger_ui/test_tutorial001.py +++ b/tests/test_tutorial/test_configure_swagger_ui/test_tutorial001.py @@ -8,31 +8,31 @@ client = TestClient(app) def test_swagger_ui(): response = client.get("/docs") assert response.status_code == 200, response.text - assert ( - '"syntaxHighlight": false' in response.text - ), "syntaxHighlight should be included and converted to JSON" - assert ( - '"dom_id": "#swagger-ui"' in response.text - ), "default configs should be preserved" + assert '"syntaxHighlight": false' in response.text, ( + "syntaxHighlight should be included and converted to JSON" + ) + assert '"dom_id": "#swagger-ui"' in response.text, ( + "default configs should be preserved" + ) assert "presets: [" in response.text, "default configs should be preserved" - assert ( - "SwaggerUIBundle.presets.apis," in response.text - ), "default configs should be preserved" - assert ( - "SwaggerUIBundle.SwaggerUIStandalonePreset" in response.text - ), "default configs should be preserved" - assert ( - '"layout": "BaseLayout",' in response.text - ), "default configs should be preserved" - assert ( - '"deepLinking": true,' in response.text - ), "default configs should be preserved" - assert ( - '"showExtensions": true,' in response.text - ), "default configs should be preserved" - assert ( - '"showCommonExtensions": true,' in response.text - ), "default configs should be preserved" + assert "SwaggerUIBundle.presets.apis," in response.text, ( + "default configs should be preserved" + ) + assert "SwaggerUIBundle.SwaggerUIStandalonePreset" in response.text, ( + "default configs should be preserved" + ) + assert '"layout": "BaseLayout",' in response.text, ( + "default configs should be preserved" + ) + assert '"deepLinking": true,' in response.text, ( + "default configs should be preserved" + ) + assert '"showExtensions": true,' in response.text, ( + "default configs should be preserved" + ) + assert '"showCommonExtensions": true,' in response.text, ( + "default configs should be preserved" + ) def test_get_users(): diff --git a/tests/test_tutorial/test_configure_swagger_ui/test_tutorial002.py b/tests/test_tutorial/test_configure_swagger_ui/test_tutorial002.py index 166901188..ea56b6f21 100644 --- a/tests/test_tutorial/test_configure_swagger_ui/test_tutorial002.py +++ b/tests/test_tutorial/test_configure_swagger_ui/test_tutorial002.py @@ -8,34 +8,34 @@ client = TestClient(app) def test_swagger_ui(): response = client.get("/docs") assert response.status_code == 200, response.text - assert ( - '"syntaxHighlight": false' not in response.text - ), "not used parameters should not be included" - assert ( - '"syntaxHighlight.theme": "obsidian"' in response.text - ), "parameters with middle dots should be included in a JSON compatible way" - assert ( - '"dom_id": "#swagger-ui"' in response.text - ), "default configs should be preserved" + assert '"syntaxHighlight": false' not in response.text, ( + "not used parameters should not be included" + ) + assert '"syntaxHighlight": {"theme": "obsidian"}' in response.text, ( + "parameters with middle dots should be included in a JSON compatible way" + ) + assert '"dom_id": "#swagger-ui"' in response.text, ( + "default configs should be preserved" + ) assert "presets: [" in response.text, "default configs should be preserved" - assert ( - "SwaggerUIBundle.presets.apis," in response.text - ), "default configs should be preserved" - assert ( - "SwaggerUIBundle.SwaggerUIStandalonePreset" in response.text - ), "default configs should be preserved" - assert ( - '"layout": "BaseLayout",' in response.text - ), "default configs should be preserved" - assert ( - '"deepLinking": true,' in response.text - ), "default configs should be preserved" - assert ( - '"showExtensions": true,' in response.text - ), "default configs should be preserved" - assert ( - '"showCommonExtensions": true,' in response.text - ), "default configs should be preserved" + assert "SwaggerUIBundle.presets.apis," in response.text, ( + "default configs should be preserved" + ) + assert "SwaggerUIBundle.SwaggerUIStandalonePreset" in response.text, ( + "default configs should be preserved" + ) + assert '"layout": "BaseLayout",' in response.text, ( + "default configs should be preserved" + ) + assert '"deepLinking": true,' in response.text, ( + "default configs should be preserved" + ) + assert '"showExtensions": true,' in response.text, ( + "default configs should be preserved" + ) + assert '"showCommonExtensions": true,' in response.text, ( + "default configs should be preserved" + ) def test_get_users(): diff --git a/tests/test_tutorial/test_configure_swagger_ui/test_tutorial003.py b/tests/test_tutorial/test_configure_swagger_ui/test_tutorial003.py index 187e89ace..926bbb14f 100644 --- a/tests/test_tutorial/test_configure_swagger_ui/test_tutorial003.py +++ b/tests/test_tutorial/test_configure_swagger_ui/test_tutorial003.py @@ -8,34 +8,34 @@ client = TestClient(app) def test_swagger_ui(): response = client.get("/docs") assert response.status_code == 200, response.text - assert ( - '"deepLinking": false,' in response.text - ), "overridden configs should be preserved" - assert ( - '"deepLinking": true' not in response.text - ), "overridden configs should not include the old value" - assert ( - '"syntaxHighlight": false' not in response.text - ), "not used parameters should not be included" - assert ( - '"dom_id": "#swagger-ui"' in response.text - ), "default configs should be preserved" + assert '"deepLinking": false,' in response.text, ( + "overridden configs should be preserved" + ) + assert '"deepLinking": true' not in response.text, ( + "overridden configs should not include the old value" + ) + assert '"syntaxHighlight": false' not in response.text, ( + "not used parameters should not be included" + ) + assert '"dom_id": "#swagger-ui"' in response.text, ( + "default configs should be preserved" + ) assert "presets: [" in response.text, "default configs should be preserved" - assert ( - "SwaggerUIBundle.presets.apis," in response.text - ), "default configs should be preserved" - assert ( - "SwaggerUIBundle.SwaggerUIStandalonePreset" in response.text - ), "default configs should be preserved" - assert ( - '"layout": "BaseLayout",' in response.text - ), "default configs should be preserved" - assert ( - '"showExtensions": true,' in response.text - ), "default configs should be preserved" - assert ( - '"showCommonExtensions": true,' in response.text - ), "default configs should be preserved" + assert "SwaggerUIBundle.presets.apis," in response.text, ( + "default configs should be preserved" + ) + assert "SwaggerUIBundle.SwaggerUIStandalonePreset" in response.text, ( + "default configs should be preserved" + ) + assert '"layout": "BaseLayout",' in response.text, ( + "default configs should be preserved" + ) + assert '"showExtensions": true,' in response.text, ( + "default configs should be preserved" + ) + assert '"showCommonExtensions": true,' in response.text, ( + "default configs should be preserved" + ) def test_get_users(): diff --git a/tests/test_tutorial/test_cookie_param_models/test_tutorial002.py b/tests/test_tutorial/test_cookie_param_models/test_tutorial002.py index 30adadc8a..cef6f6630 100644 --- a/tests/test_tutorial/test_cookie_param_models/test_tutorial002.py +++ b/tests/test_tutorial/test_cookie_param_models/test_tutorial002.py @@ -5,7 +5,13 @@ from dirty_equals import IsDict from fastapi.testclient import TestClient from inline_snapshot import snapshot -from tests.utils import needs_py39, needs_py310, needs_pydanticv1, needs_pydanticv2 +from tests.utils import ( + needs_py39, + needs_py310, + needs_pydanticv1, + needs_pydanticv2, + pydantic_snapshot, +) @pytest.fixture( @@ -59,8 +65,8 @@ def test_cookie_param_model_defaults(client: TestClient): def test_cookie_param_model_invalid(client: TestClient): response = client.get("/items/") assert response.status_code == 422 - assert response.json() == snapshot( - IsDict( + assert response.json() == pydantic_snapshot( + v2=snapshot( { "detail": [ { @@ -71,9 +77,8 @@ def test_cookie_param_model_invalid(client: TestClient): } ] } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 + ), + v1=snapshot( { "detail": [ { @@ -83,7 +88,7 @@ def test_cookie_param_model_invalid(client: TestClient): } ] } - ) + ), ) @@ -144,18 +149,23 @@ def test_openapi_schema(client: TestClient): "name": "fatebook_tracker", "in": "cookie", "required": False, - "schema": IsDict( - { - "anyOf": [{"type": "string"}, {"type": "null"}], - "title": "Fatebook Tracker", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "type": "string", - "title": "Fatebook Tracker", - } + "schema": pydantic_snapshot( + v2=snapshot( + { + "anyOf": [ + {"type": "string"}, + {"type": "null"}, + ], + "title": "Fatebook Tracker", + } + ), + v1=snapshot( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "title": "Fatebook Tracker", + } + ), ), }, { diff --git a/tests/test_tutorial/test_custom_docs_ui/test_tutorial001.py b/tests/test_tutorial/test_custom_docs_ui/test_tutorial001.py index aff070d74..cb8e8c224 100644 --- a/tests/test_tutorial/test_custom_docs_ui/test_tutorial001.py +++ b/tests/test_tutorial/test_custom_docs_ui/test_tutorial001.py @@ -33,7 +33,7 @@ def test_swagger_ui_oauth2_redirect_html(client: TestClient): def test_redoc_html(client: TestClient): response = client.get("/redoc") assert response.status_code == 200, response.text - assert "https://unpkg.com/redoc@next/bundles/redoc.standalone.js" in response.text + assert "https://unpkg.com/redoc@2/bundles/redoc.standalone.js" in response.text def test_api(client: TestClient): diff --git a/tests/test_tutorial/test_header_param_models/test_tutorial001.py b/tests/test_tutorial/test_header_param_models/test_tutorial001.py index 06b2404cf..bc876897b 100644 --- a/tests/test_tutorial/test_header_param_models/test_tutorial001.py +++ b/tests/test_tutorial/test_header_param_models/test_tutorial001.py @@ -129,13 +129,13 @@ def test_openapi_schema(client: TestClient): "schema": {"type": "string", "title": "Host"}, }, { - "name": "save_data", + "name": "save-data", "in": "header", "required": True, "schema": {"type": "boolean", "title": "Save Data"}, }, { - "name": "if_modified_since", + "name": "if-modified-since", "in": "header", "required": False, "schema": IsDict( @@ -171,7 +171,7 @@ def test_openapi_schema(client: TestClient): ), }, { - "name": "x_tag", + "name": "x-tag", "in": "header", "required": False, "schema": { diff --git a/tests/test_tutorial/test_header_param_models/test_tutorial002.py b/tests/test_tutorial/test_header_param_models/test_tutorial002.py index e07655a0c..0615521c4 100644 --- a/tests/test_tutorial/test_header_param_models/test_tutorial002.py +++ b/tests/test_tutorial/test_header_param_models/test_tutorial002.py @@ -140,13 +140,13 @@ def test_openapi_schema(client: TestClient): "schema": {"type": "string", "title": "Host"}, }, { - "name": "save_data", + "name": "save-data", "in": "header", "required": True, "schema": {"type": "boolean", "title": "Save Data"}, }, { - "name": "if_modified_since", + "name": "if-modified-since", "in": "header", "required": False, "schema": IsDict( @@ -182,7 +182,7 @@ def test_openapi_schema(client: TestClient): ), }, { - "name": "x_tag", + "name": "x-tag", "in": "header", "required": False, "schema": { diff --git a/tests/test_tutorial/test_header_param_models/test_tutorial003.py b/tests/test_tutorial/test_header_param_models/test_tutorial003.py new file mode 100644 index 000000000..60940e1da --- /dev/null +++ b/tests/test_tutorial/test_header_param_models/test_tutorial003.py @@ -0,0 +1,285 @@ +import importlib + +import pytest +from dirty_equals import IsDict +from fastapi.testclient import TestClient +from inline_snapshot import snapshot + +from tests.utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial003", + pytest.param("tutorial003_py39", marks=needs_py39), + pytest.param("tutorial003_py310", marks=needs_py310), + "tutorial003_an", + pytest.param("tutorial003_an_py39", marks=needs_py39), + pytest.param("tutorial003_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module(f"docs_src.header_param_models.{request.param}") + + client = TestClient(mod.app) + return client + + +def test_header_param_model(client: TestClient): + response = client.get( + "/items/", + headers=[ + ("save_data", "true"), + ("if_modified_since", "yesterday"), + ("traceparent", "123"), + ("x_tag", "one"), + ("x_tag", "two"), + ], + ) + assert response.status_code == 200 + assert response.json() == { + "host": "testserver", + "save_data": True, + "if_modified_since": "yesterday", + "traceparent": "123", + "x_tag": ["one", "two"], + } + + +def test_header_param_model_no_underscore(client: TestClient): + response = client.get( + "/items/", + headers=[ + ("save-data", "true"), + ("if-modified-since", "yesterday"), + ("traceparent", "123"), + ("x-tag", "one"), + ("x-tag", "two"), + ], + ) + assert response.status_code == 422 + assert response.json() == snapshot( + { + "detail": [ + IsDict( + { + "type": "missing", + "loc": ["header", "save_data"], + "msg": "Field required", + "input": { + "host": "testserver", + "traceparent": "123", + "x_tag": [], + "accept": "*/*", + "accept-encoding": "gzip, deflate", + "connection": "keep-alive", + "user-agent": "testclient", + "save-data": "true", + "if-modified-since": "yesterday", + "x-tag": "two", + }, + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "value_error.missing", + "loc": ["header", "save_data"], + "msg": "field required", + } + ) + ] + } + ) + + +def test_header_param_model_defaults(client: TestClient): + response = client.get("/items/", headers=[("save_data", "true")]) + assert response.status_code == 200 + assert response.json() == { + "host": "testserver", + "save_data": True, + "if_modified_since": None, + "traceparent": None, + "x_tag": [], + } + + +def test_header_param_model_invalid(client: TestClient): + response = client.get("/items/") + assert response.status_code == 422 + assert response.json() == snapshot( + { + "detail": [ + IsDict( + { + "type": "missing", + "loc": ["header", "save_data"], + "msg": "Field required", + "input": { + "x_tag": [], + "host": "testserver", + "accept": "*/*", + "accept-encoding": "gzip, deflate", + "connection": "keep-alive", + "user-agent": "testclient", + }, + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "value_error.missing", + "loc": ["header", "save_data"], + "msg": "field required", + } + ) + ] + } + ) + + +def test_header_param_model_extra(client: TestClient): + response = client.get( + "/items/", headers=[("save_data", "true"), ("tool", "plumbus")] + ) + assert response.status_code == 200, response.text + assert response.json() == snapshot( + { + "host": "testserver", + "save_data": True, + "if_modified_since": None, + "traceparent": None, + "x_tag": [], + } + ) + + +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "parameters": [ + { + "name": "host", + "in": "header", + "required": True, + "schema": {"type": "string", "title": "Host"}, + }, + { + "name": "save_data", + "in": "header", + "required": True, + "schema": {"type": "boolean", "title": "Save Data"}, + }, + { + "name": "if_modified_since", + "in": "header", + "required": False, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "If Modified Since", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "title": "If Modified Since", + } + ), + }, + { + "name": "traceparent", + "in": "header", + "required": False, + "schema": IsDict( + { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Traceparent", + } + ) + | IsDict( + # TODO: remove when deprecating Pydantic v1 + { + "type": "string", + "title": "Traceparent", + } + ), + }, + { + "name": "x_tag", + "in": "header", + "required": False, + "schema": { + "type": "array", + "items": {"type": "string"}, + "default": [], + "title": "X Tag", + }, + }, + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": { + "$ref": "#/components/schemas/ValidationError" + }, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } + ) diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010.py index 4f52d6ff7..e08e16963 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010.py @@ -1,14 +1,29 @@ +import importlib + import pytest from dirty_equals import IsDict from fastapi._compat import PYDANTIC_VERSION_MINOR_TUPLE from fastapi.testclient import TestClient +from ...utils import needs_py39, needs_py310 + -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial010 import app +@pytest.fixture( + name="client", + params=[ + "tutorial010", + pytest.param("tutorial010_py310", marks=needs_py310), + "tutorial010_an", + pytest.param("tutorial010_an_py39", marks=needs_py39), + pytest.param("tutorial010_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module( + f"docs_src.query_params_str_validations.{request.param}" + ) - client = TestClient(app) + client = TestClient(mod.app) return client diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an.py deleted file mode 100644 index 5daca1e70..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an.py +++ /dev/null @@ -1,168 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi._compat import PYDANTIC_VERSION_MINOR_TUPLE -from fastapi.testclient import TestClient - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial010_an import app - - client = TestClient(app) - return client - - -def test_query_params_str_validations_no_query(client: TestClient): - response = client.get("/items/") - assert response.status_code == 200 - assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - - -def test_query_params_str_validations_item_query_fixedquery(client: TestClient): - response = client.get("/items/", params={"item-query": "fixedquery"}) - assert response.status_code == 200 - assert response.json() == { - "items": [{"item_id": "Foo"}, {"item_id": "Bar"}], - "q": "fixedquery", - } - - -def test_query_params_str_validations_q_fixedquery(client: TestClient): - response = client.get("/items/", params={"q": "fixedquery"}) - assert response.status_code == 200 - assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - - -def test_query_params_str_validations_item_query_nonregexquery(client: TestClient): - response = client.get("/items/", params={"item-query": "nonregexquery"}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "string_pattern_mismatch", - "loc": ["query", "item-query"], - "msg": "String should match pattern '^fixedquery$'", - "input": "nonregexquery", - "ctx": {"pattern": "^fixedquery$"}, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "ctx": {"pattern": "^fixedquery$"}, - "loc": ["query", "item-query"], - "msg": 'string does not match regex "^fixedquery$"', - "type": "value_error.str.regex", - } - ] - } - ) - - -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "description": "Query string for the items to search in the database that have a good match", - "required": False, - "deprecated": True, - "schema": IsDict( - { - "anyOf": [ - { - "type": "string", - "minLength": 3, - "maxLength": 50, - "pattern": "^fixedquery$", - }, - {"type": "null"}, - ], - "title": "Query string", - "description": "Query string for the items to search in the database that have a good match", - # See https://github.com/pydantic/pydantic/blob/80353c29a824c55dea4667b328ba8f329879ac9f/tests/test_fastapi.sh#L25-L34. - **( - {"deprecated": True} - if PYDANTIC_VERSION_MINOR_TUPLE >= (2, 10) - else {} - ), - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Query string", - "maxLength": 50, - "minLength": 3, - "pattern": "^fixedquery$", - "type": "string", - "description": "Query string for the items to search in the database that have a good match", - } - ), - "name": "item-query", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py310.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py310.py deleted file mode 100644 index 89da4d82e..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py310.py +++ /dev/null @@ -1,175 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi._compat import PYDANTIC_VERSION_MINOR_TUPLE -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial010_an_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_query_params_str_validations_no_query(client: TestClient): - response = client.get("/items/") - assert response.status_code == 200 - assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - - -@needs_py310 -def test_query_params_str_validations_item_query_fixedquery(client: TestClient): - response = client.get("/items/", params={"item-query": "fixedquery"}) - assert response.status_code == 200 - assert response.json() == { - "items": [{"item_id": "Foo"}, {"item_id": "Bar"}], - "q": "fixedquery", - } - - -@needs_py310 -def test_query_params_str_validations_q_fixedquery(client: TestClient): - response = client.get("/items/", params={"q": "fixedquery"}) - assert response.status_code == 200 - assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - - -@needs_py310 -def test_query_params_str_validations_item_query_nonregexquery(client: TestClient): - response = client.get("/items/", params={"item-query": "nonregexquery"}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "string_pattern_mismatch", - "loc": ["query", "item-query"], - "msg": "String should match pattern '^fixedquery$'", - "input": "nonregexquery", - "ctx": {"pattern": "^fixedquery$"}, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "ctx": {"pattern": "^fixedquery$"}, - "loc": ["query", "item-query"], - "msg": 'string does not match regex "^fixedquery$"', - "type": "value_error.str.regex", - } - ] - } - ) - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "description": "Query string for the items to search in the database that have a good match", - "required": False, - "deprecated": True, - "schema": IsDict( - { - "anyOf": [ - { - "type": "string", - "minLength": 3, - "maxLength": 50, - "pattern": "^fixedquery$", - }, - {"type": "null"}, - ], - "title": "Query string", - "description": "Query string for the items to search in the database that have a good match", - # See https://github.com/pydantic/pydantic/blob/80353c29a824c55dea4667b328ba8f329879ac9f/tests/test_fastapi.sh#L25-L34. - **( - {"deprecated": True} - if PYDANTIC_VERSION_MINOR_TUPLE >= (2, 10) - else {} - ), - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Query string", - "maxLength": 50, - "minLength": 3, - "pattern": "^fixedquery$", - "type": "string", - "description": "Query string for the items to search in the database that have a good match", - } - ), - "name": "item-query", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py39.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py39.py deleted file mode 100644 index f5f692b06..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_an_py39.py +++ /dev/null @@ -1,175 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi._compat import PYDANTIC_VERSION_MINOR_TUPLE -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial010_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_query_params_str_validations_no_query(client: TestClient): - response = client.get("/items/") - assert response.status_code == 200 - assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - - -@needs_py39 -def test_query_params_str_validations_item_query_fixedquery(client: TestClient): - response = client.get("/items/", params={"item-query": "fixedquery"}) - assert response.status_code == 200 - assert response.json() == { - "items": [{"item_id": "Foo"}, {"item_id": "Bar"}], - "q": "fixedquery", - } - - -@needs_py39 -def test_query_params_str_validations_q_fixedquery(client: TestClient): - response = client.get("/items/", params={"q": "fixedquery"}) - assert response.status_code == 200 - assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - - -@needs_py39 -def test_query_params_str_validations_item_query_nonregexquery(client: TestClient): - response = client.get("/items/", params={"item-query": "nonregexquery"}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "string_pattern_mismatch", - "loc": ["query", "item-query"], - "msg": "String should match pattern '^fixedquery$'", - "input": "nonregexquery", - "ctx": {"pattern": "^fixedquery$"}, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "ctx": {"pattern": "^fixedquery$"}, - "loc": ["query", "item-query"], - "msg": 'string does not match regex "^fixedquery$"', - "type": "value_error.str.regex", - } - ] - } - ) - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "description": "Query string for the items to search in the database that have a good match", - "required": False, - "deprecated": True, - "schema": IsDict( - { - "anyOf": [ - { - "type": "string", - "minLength": 3, - "maxLength": 50, - "pattern": "^fixedquery$", - }, - {"type": "null"}, - ], - "title": "Query string", - "description": "Query string for the items to search in the database that have a good match", - # See https://github.com/pydantic/pydantic/blob/80353c29a824c55dea4667b328ba8f329879ac9f/tests/test_fastapi.sh#L25-L34. - **( - {"deprecated": True} - if PYDANTIC_VERSION_MINOR_TUPLE >= (2, 10) - else {} - ), - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Query string", - "maxLength": 50, - "minLength": 3, - "pattern": "^fixedquery$", - "type": "string", - "description": "Query string for the items to search in the database that have a good match", - } - ), - "name": "item-query", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_py310.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_py310.py deleted file mode 100644 index 5b62c969f..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial010_py310.py +++ /dev/null @@ -1,175 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi._compat import PYDANTIC_VERSION_MINOR_TUPLE -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial010_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_query_params_str_validations_no_query(client: TestClient): - response = client.get("/items/") - assert response.status_code == 200 - assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - - -@needs_py310 -def test_query_params_str_validations_item_query_fixedquery(client: TestClient): - response = client.get("/items/", params={"item-query": "fixedquery"}) - assert response.status_code == 200 - assert response.json() == { - "items": [{"item_id": "Foo"}, {"item_id": "Bar"}], - "q": "fixedquery", - } - - -@needs_py310 -def test_query_params_str_validations_q_fixedquery(client: TestClient): - response = client.get("/items/", params={"q": "fixedquery"}) - assert response.status_code == 200 - assert response.json() == {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} - - -@needs_py310 -def test_query_params_str_validations_item_query_nonregexquery(client: TestClient): - response = client.get("/items/", params={"item-query": "nonregexquery"}) - assert response.status_code == 422 - assert response.json() == IsDict( - { - "detail": [ - { - "type": "string_pattern_mismatch", - "loc": ["query", "item-query"], - "msg": "String should match pattern '^fixedquery$'", - "input": "nonregexquery", - "ctx": {"pattern": "^fixedquery$"}, - } - ] - } - ) | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "detail": [ - { - "ctx": {"pattern": "^fixedquery$"}, - "loc": ["query", "item-query"], - "msg": 'string does not match regex "^fixedquery$"', - "type": "value_error.str.regex", - } - ] - } - ) - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "description": "Query string for the items to search in the database that have a good match", - "required": False, - "deprecated": True, - "schema": IsDict( - { - "anyOf": [ - { - "type": "string", - "minLength": 3, - "maxLength": 50, - "pattern": "^fixedquery$", - }, - {"type": "null"}, - ], - "title": "Query string", - "description": "Query string for the items to search in the database that have a good match", - # See https://github.com/pydantic/pydantic/blob/80353c29a824c55dea4667b328ba8f329879ac9f/tests/test_fastapi.sh#L25-L34. - **( - {"deprecated": True} - if PYDANTIC_VERSION_MINOR_TUPLE >= (2, 10) - else {} - ), - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Query string", - "maxLength": 50, - "minLength": 3, - "pattern": "^fixedquery$", - "type": "string", - "description": "Query string for the items to search in the database that have a good match", - } - ), - "name": "item-query", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial011.py index 5ba39b05d..f4da25752 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial011.py @@ -1,26 +1,47 @@ +import importlib + +import pytest from dirty_equals import IsDict from fastapi.testclient import TestClient -from docs_src.query_params_str_validations.tutorial011 import app +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial011", + pytest.param("tutorial011_py39", marks=needs_py310), + pytest.param("tutorial011_py310", marks=needs_py310), + "tutorial011_an", + pytest.param("tutorial011_an_py39", marks=needs_py39), + pytest.param("tutorial011_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module( + f"docs_src.query_params_str_validations.{request.param}" + ) -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_multi_query_values(): +def test_multi_query_values(client: TestClient): url = "/items/?q=foo&q=bar" response = client.get(url) assert response.status_code == 200, response.text assert response.json() == {"q": ["foo", "bar"]} -def test_query_no_values(): +def test_query_no_values(client: TestClient): url = "/items/" response = client.get(url) assert response.status_code == 200, response.text assert response.json() == {"q": None} -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an.py deleted file mode 100644 index 3942ea77a..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an.py +++ /dev/null @@ -1,108 +0,0 @@ -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from docs_src.query_params_str_validations.tutorial011_an import app - -client = TestClient(app) - - -def test_multi_query_values(): - url = "/items/?q=foo&q=bar" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": ["foo", "bar"]} - - -def test_query_no_values(): - url = "/items/" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": None} - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [ - {"type": "array", "items": {"type": "string"}}, - {"type": "null"}, - ], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Q", - "type": "array", - "items": {"type": "string"}, - } - ), - "name": "q", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an_py310.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an_py310.py deleted file mode 100644 index f2ec38c95..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an_py310.py +++ /dev/null @@ -1,118 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial011_an_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_multi_query_values(client: TestClient): - url = "/items/?q=foo&q=bar" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": ["foo", "bar"]} - - -@needs_py310 -def test_query_no_values(client: TestClient): - url = "/items/" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": None} - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [ - {"type": "array", "items": {"type": "string"}}, - {"type": "null"}, - ], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Q", - "type": "array", - "items": {"type": "string"}, - } - ), - "name": "q", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an_py39.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an_py39.py deleted file mode 100644 index cd7b15679..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_an_py39.py +++ /dev/null @@ -1,118 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial011_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_multi_query_values(client: TestClient): - url = "/items/?q=foo&q=bar" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": ["foo", "bar"]} - - -@needs_py39 -def test_query_no_values(client: TestClient): - url = "/items/" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": None} - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [ - {"type": "array", "items": {"type": "string"}}, - {"type": "null"}, - ], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Q", - "type": "array", - "items": {"type": "string"}, - } - ), - "name": "q", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_py310.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_py310.py deleted file mode 100644 index bdc729516..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_py310.py +++ /dev/null @@ -1,118 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial011_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_multi_query_values(client: TestClient): - url = "/items/?q=foo&q=bar" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": ["foo", "bar"]} - - -@needs_py310 -def test_query_no_values(client: TestClient): - url = "/items/" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": None} - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [ - {"type": "array", "items": {"type": "string"}}, - {"type": "null"}, - ], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Q", - "type": "array", - "items": {"type": "string"}, - } - ), - "name": "q", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_py39.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_py39.py deleted file mode 100644 index 26ac56b2f..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial011_py39.py +++ /dev/null @@ -1,118 +0,0 @@ -import pytest -from dirty_equals import IsDict -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial011_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_multi_query_values(client: TestClient): - url = "/items/?q=foo&q=bar" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": ["foo", "bar"]} - - -@needs_py39 -def test_query_no_values(client: TestClient): - url = "/items/" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": None} - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": IsDict( - { - "anyOf": [ - {"type": "array", "items": {"type": "string"}}, - {"type": "null"}, - ], - "title": "Q", - } - ) - | IsDict( - # TODO: remove when deprecating Pydantic v1 - { - "title": "Q", - "type": "array", - "items": {"type": "string"}, - } - ), - "name": "q", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial012.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial012.py index 1436db384..549a90519 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial012.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial012.py @@ -1,25 +1,44 @@ +import importlib + +import pytest from fastapi.testclient import TestClient -from docs_src.query_params_str_validations.tutorial012 import app +from ...utils import needs_py39 + + +@pytest.fixture( + name="client", + params=[ + "tutorial012", + pytest.param("tutorial012_py39", marks=needs_py39), + "tutorial012_an", + pytest.param("tutorial012_an_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module( + f"docs_src.query_params_str_validations.{request.param}" + ) -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_default_query_values(): +def test_default_query_values(client: TestClient): url = "/items/" response = client.get(url) assert response.status_code == 200, response.text assert response.json() == {"q": ["foo", "bar"]} -def test_multi_query_values(): +def test_multi_query_values(client: TestClient): url = "/items/?q=baz&q=foobar" response = client.get(url) assert response.status_code == 200, response.text assert response.json() == {"q": ["baz", "foobar"]} -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial012_an.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial012_an.py deleted file mode 100644 index 270763f1d..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial012_an.py +++ /dev/null @@ -1,96 +0,0 @@ -from fastapi.testclient import TestClient - -from docs_src.query_params_str_validations.tutorial012_an import app - -client = TestClient(app) - - -def test_default_query_values(): - url = "/items/" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": ["foo", "bar"]} - - -def test_multi_query_values(): - url = "/items/?q=baz&q=foobar" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": ["baz", "foobar"]} - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Q", - "type": "array", - "items": {"type": "string"}, - "default": ["foo", "bar"], - }, - "name": "q", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial012_an_py39.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial012_an_py39.py deleted file mode 100644 index 548391683..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial012_an_py39.py +++ /dev/null @@ -1,106 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial012_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_default_query_values(client: TestClient): - url = "/items/" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": ["foo", "bar"]} - - -@needs_py39 -def test_multi_query_values(client: TestClient): - url = "/items/?q=baz&q=foobar" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": ["baz", "foobar"]} - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Q", - "type": "array", - "items": {"type": "string"}, - "default": ["foo", "bar"], - }, - "name": "q", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial012_py39.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial012_py39.py deleted file mode 100644 index e7d745154..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial012_py39.py +++ /dev/null @@ -1,106 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial012_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_default_query_values(client: TestClient): - url = "/items/" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": ["foo", "bar"]} - - -@needs_py39 -def test_multi_query_values(client: TestClient): - url = "/items/?q=baz&q=foobar" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": ["baz", "foobar"]} - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Q", - "type": "array", - "items": {"type": "string"}, - "default": ["foo", "bar"], - }, - "name": "q", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial013.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial013.py index 1ba1fdf61..f2f5f7a85 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial013.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial013.py @@ -1,25 +1,43 @@ +import importlib + +import pytest from fastapi.testclient import TestClient -from docs_src.query_params_str_validations.tutorial013 import app +from ...utils import needs_py39 + + +@pytest.fixture( + name="client", + params=[ + "tutorial013", + "tutorial013_an", + pytest.param("tutorial013_an_py39", marks=needs_py39), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module( + f"docs_src.query_params_str_validations.{request.param}" + ) -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_multi_query_values(): +def test_multi_query_values(client: TestClient): url = "/items/?q=foo&q=bar" response = client.get(url) assert response.status_code == 200, response.text assert response.json() == {"q": ["foo", "bar"]} -def test_query_no_values(): +def test_query_no_values(client: TestClient): url = "/items/" response = client.get(url) assert response.status_code == 200, response.text assert response.json() == {"q": []} -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial013_an.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial013_an.py deleted file mode 100644 index 343261748..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial013_an.py +++ /dev/null @@ -1,96 +0,0 @@ -from fastapi.testclient import TestClient - -from docs_src.query_params_str_validations.tutorial013_an import app - -client = TestClient(app) - - -def test_multi_query_values(): - url = "/items/?q=foo&q=bar" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": ["foo", "bar"]} - - -def test_query_no_values(): - url = "/items/" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": []} - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Q", - "type": "array", - "items": {}, - "default": [], - }, - "name": "q", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial013_an_py39.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial013_an_py39.py deleted file mode 100644 index 537d6325b..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial013_an_py39.py +++ /dev/null @@ -1,106 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py39 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial013_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py39 -def test_multi_query_values(client: TestClient): - url = "/items/?q=foo&q=bar" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": ["foo", "bar"]} - - -@needs_py39 -def test_query_no_values(client: TestClient): - url = "/items/" - response = client.get(url) - assert response.status_code == 200, response.text - assert response.json() == {"q": []} - - -@needs_py39 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - "summary": "Read Items", - "operationId": "read_items_items__get", - "parameters": [ - { - "required": False, - "schema": { - "title": "Q", - "type": "array", - "items": {}, - "default": [], - }, - "name": "q", - "in": "query", - } - ], - } - } - }, - "components": { - "schemas": { - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial014.py index 7bce7590c..edd40bb1a 100644 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014.py +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial014.py @@ -1,23 +1,43 @@ +import importlib + +import pytest from fastapi.testclient import TestClient -from docs_src.query_params_str_validations.tutorial014 import app +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="client", + params=[ + "tutorial014", + pytest.param("tutorial014_py310", marks=needs_py310), + "tutorial014_an", + pytest.param("tutorial014_an_py39", marks=needs_py39), + pytest.param("tutorial014_an_py310", marks=needs_py310), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module( + f"docs_src.query_params_str_validations.{request.param}" + ) -client = TestClient(app) + client = TestClient(mod.app) + return client -def test_hidden_query(): +def test_hidden_query(client: TestClient): response = client.get("/items?hidden_query=somevalue") assert response.status_code == 200, response.text assert response.json() == {"hidden_query": "somevalue"} -def test_no_hidden_query(): +def test_no_hidden_query(client: TestClient): response = client.get("/items") assert response.status_code == 200, response.text assert response.json() == {"hidden_query": "Not found"} -def test_openapi_schema(): +def test_openapi_schema(client: TestClient): response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == { diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an.py deleted file mode 100644 index 2182e87b7..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an.py +++ /dev/null @@ -1,81 +0,0 @@ -from fastapi.testclient import TestClient - -from docs_src.query_params_str_validations.tutorial014_an import app - -client = TestClient(app) - - -def test_hidden_query(): - response = client.get("/items?hidden_query=somevalue") - assert response.status_code == 200, response.text - assert response.json() == {"hidden_query": "somevalue"} - - -def test_no_hidden_query(): - response = client.get("/items") - assert response.status_code == 200, response.text - assert response.json() == {"hidden_query": "Not found"} - - -def test_openapi_schema(): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "summary": "Read Items", - "operationId": "read_items_items__get", - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an_py310.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an_py310.py deleted file mode 100644 index 344004d01..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an_py310.py +++ /dev/null @@ -1,91 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial014_an_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_hidden_query(client: TestClient): - response = client.get("/items?hidden_query=somevalue") - assert response.status_code == 200, response.text - assert response.json() == {"hidden_query": "somevalue"} - - -@needs_py310 -def test_no_hidden_query(client: TestClient): - response = client.get("/items") - assert response.status_code == 200, response.text - assert response.json() == {"hidden_query": "Not found"} - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "summary": "Read Items", - "operationId": "read_items_items__get", - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an_py39.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an_py39.py deleted file mode 100644 index 5d4f6df3d..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_an_py39.py +++ /dev/null @@ -1,91 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial014_an_py39 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_hidden_query(client: TestClient): - response = client.get("/items?hidden_query=somevalue") - assert response.status_code == 200, response.text - assert response.json() == {"hidden_query": "somevalue"} - - -@needs_py310 -def test_no_hidden_query(client: TestClient): - response = client.get("/items") - assert response.status_code == 200, response.text - assert response.json() == {"hidden_query": "Not found"} - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "summary": "Read Items", - "operationId": "read_items_items__get", - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_py310.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_py310.py deleted file mode 100644 index dad49fb12..000000000 --- a/tests/test_tutorial/test_query_params_str_validations/test_tutorial014_py310.py +++ /dev/null @@ -1,91 +0,0 @@ -import pytest -from fastapi.testclient import TestClient - -from ...utils import needs_py310 - - -@pytest.fixture(name="client") -def get_client(): - from docs_src.query_params_str_validations.tutorial014_py310 import app - - client = TestClient(app) - return client - - -@needs_py310 -def test_hidden_query(client: TestClient): - response = client.get("/items?hidden_query=somevalue") - assert response.status_code == 200, response.text - assert response.json() == {"hidden_query": "somevalue"} - - -@needs_py310 -def test_no_hidden_query(client: TestClient): - response = client.get("/items") - assert response.status_code == 200, response.text - assert response.json() == {"hidden_query": "Not found"} - - -@needs_py310 -def test_openapi_schema(client: TestClient): - response = client.get("/openapi.json") - assert response.status_code == 200, response.text - assert response.json() == { - "openapi": "3.1.0", - "info": {"title": "FastAPI", "version": "0.1.0"}, - "paths": { - "/items/": { - "get": { - "summary": "Read Items", - "operationId": "read_items_items__get", - "responses": { - "200": { - "description": "Successful Response", - "content": {"application/json": {"schema": {}}}, - }, - "422": { - "description": "Validation Error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - }, - }, - } - } - }, - "components": { - "schemas": { - "HTTPValidationError": { - "title": "HTTPValidationError", - "type": "object", - "properties": { - "detail": { - "title": "Detail", - "type": "array", - "items": {"$ref": "#/components/schemas/ValidationError"}, - } - }, - }, - "ValidationError": { - "title": "ValidationError", - "required": ["loc", "msg", "type"], - "type": "object", - "properties": { - "loc": { - "title": "Location", - "type": "array", - "items": { - "anyOf": [{"type": "string"}, {"type": "integer"}] - }, - }, - "msg": {"title": "Message", "type": "string"}, - "type": {"title": "Error Type", "type": "string"}, - }, - }, - } - }, - } diff --git a/tests/test_tutorial/test_query_params_str_validations/test_tutorial015.py b/tests/test_tutorial/test_query_params_str_validations/test_tutorial015.py new file mode 100644 index 000000000..ae1c40286 --- /dev/null +++ b/tests/test_tutorial/test_query_params_str_validations/test_tutorial015.py @@ -0,0 +1,143 @@ +import importlib + +import pytest +from dirty_equals import IsStr +from fastapi.testclient import TestClient +from inline_snapshot import snapshot + +from ...utils import needs_py39, needs_py310, needs_pydanticv2 + + +@pytest.fixture( + name="client", + params=[ + pytest.param("tutorial015_an", marks=needs_pydanticv2), + pytest.param("tutorial015_an_py310", marks=(needs_py310, needs_pydanticv2)), + pytest.param("tutorial015_an_py39", marks=(needs_py39, needs_pydanticv2)), + ], +) +def get_client(request: pytest.FixtureRequest): + mod = importlib.import_module( + f"docs_src.query_params_str_validations.{request.param}" + ) + + client = TestClient(mod.app) + return client + + +def test_get_random_item(client: TestClient): + response = client.get("/items") + assert response.status_code == 200, response.text + assert response.json() == {"id": IsStr(), "name": IsStr()} + + +def test_get_item(client: TestClient): + response = client.get("/items?id=isbn-9781529046137") + assert response.status_code == 200, response.text + assert response.json() == { + "id": "isbn-9781529046137", + "name": "The Hitchhiker's Guide to the Galaxy", + } + + +def test_get_item_does_not_exist(client: TestClient): + response = client.get("/items?id=isbn-nope") + assert response.status_code == 200, response.text + assert response.json() == {"id": "isbn-nope", "name": None} + + +def test_get_invalid_item(client: TestClient): + response = client.get("/items?id=wtf-yes") + assert response.status_code == 422, response.text + assert response.json() == snapshot( + { + "detail": [ + { + "type": "value_error", + "loc": ["query", "id"], + "msg": 'Value error, Invalid ID format, it must start with "isbn-" or "imdb-"', + "input": "wtf-yes", + "ctx": {"error": {}}, + } + ] + } + ) + + +def test_openapi_schema(client: TestClient): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == snapshot( + { + "openapi": "3.1.0", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/items/": { + "get": { + "summary": "Read Items", + "operationId": "read_items_items__get", + "parameters": [ + { + "name": "id", + "in": "query", + "required": False, + "schema": { + "anyOf": [{"type": "string"}, {"type": "null"}], + "title": "Id", + }, + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": { + "$ref": "#/components/schemas/ValidationError" + }, + "type": "array", + "title": "Detail", + } + }, + "type": "object", + "title": "HTTPValidationError", + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [{"type": "string"}, {"type": "integer"}] + }, + "type": "array", + "title": "Location", + }, + "msg": {"type": "string", "title": "Message"}, + "type": {"type": "string", "title": "Error Type"}, + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError", + }, + } + }, + } + ) diff --git a/tests/test_tutorial/test_sql_databases/test_tutorial002.py b/tests/test_tutorial/test_sql_databases/test_tutorial002.py index 68c1966f5..8a98f9a2d 100644 --- a/tests/test_tutorial/test_sql_databases/test_tutorial002.py +++ b/tests/test_tutorial/test_sql_databases/test_tutorial002.py @@ -4,7 +4,7 @@ import warnings import pytest from dirty_equals import IsDict, IsInt from fastapi.testclient import TestClient -from inline_snapshot import snapshot +from inline_snapshot import Is, snapshot from sqlalchemy import StaticPool from sqlmodel import SQLModel, create_engine from sqlmodel.main import default_registry @@ -71,9 +71,9 @@ def test_crud_app(client: TestClient): assert response.json() == snapshot( {"age": 30, "id": IsInt(), "name": "Dead Pond"} ) - assert ( - response.json()["id"] != 9000 - ), "The ID should be generated by the database" + assert response.json()["id"] != 9000, ( + "The ID should be generated by the database" + ) # Read a hero hero_id = response.json()["id"] @@ -117,14 +117,14 @@ def test_crud_app(client: TestClient): ) assert response.status_code == 200, response.text assert response.json() == snapshot( - {"name": "Dog Pond", "age": None, "id": hero_id} + {"name": "Dog Pond", "age": None, "id": Is(hero_id)} ) # Get updated hero response = client.get(f"/heroes/{hero_id}") assert response.status_code == 200, response.text assert response.json() == snapshot( - {"name": "Dog Pond", "age": None, "id": hero_id} + {"name": "Dog Pond", "age": None, "id": Is(hero_id)} ) # Delete a hero diff --git a/tests/test_tutorial/test_testing/test_main_b.py b/tests/test_tutorial/test_testing/test_main_b.py index 1e1836f5b..aa7f969c6 100644 --- a/tests/test_tutorial/test_testing/test_main_b.py +++ b/tests/test_tutorial/test_testing/test_main_b.py @@ -1,7 +1,28 @@ -from docs_src.app_testing.app_b import test_main +import importlib +from types import ModuleType +import pytest -def test_app(): +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="test_module", + params=[ + "app_b.test_main", + pytest.param("app_b_py310.test_main", marks=needs_py310), + "app_b_an.test_main", + pytest.param("app_b_an_py39.test_main", marks=needs_py39), + pytest.param("app_b_an_py310.test_main", marks=needs_py310), + ], +) +def get_test_module(request: pytest.FixtureRequest) -> ModuleType: + mod: ModuleType = importlib.import_module(f"docs_src.app_testing.{request.param}") + return mod + + +def test_app(test_module: ModuleType): + test_main = test_module test_main.test_create_existing_item() test_main.test_create_item() test_main.test_create_item_bad_token() diff --git a/tests/test_tutorial/test_testing/test_main_b_an.py b/tests/test_tutorial/test_testing/test_main_b_an.py deleted file mode 100644 index e53fc3224..000000000 --- a/tests/test_tutorial/test_testing/test_main_b_an.py +++ /dev/null @@ -1,10 +0,0 @@ -from docs_src.app_testing.app_b_an import test_main - - -def test_app(): - test_main.test_create_existing_item() - test_main.test_create_item() - test_main.test_create_item_bad_token() - test_main.test_read_nonexistent_item() - test_main.test_read_item() - test_main.test_read_item_bad_token() diff --git a/tests/test_tutorial/test_testing/test_main_b_an_py310.py b/tests/test_tutorial/test_testing/test_main_b_an_py310.py deleted file mode 100644 index c974e5dc1..000000000 --- a/tests/test_tutorial/test_testing/test_main_b_an_py310.py +++ /dev/null @@ -1,13 +0,0 @@ -from ...utils import needs_py310 - - -@needs_py310 -def test_app(): - from docs_src.app_testing.app_b_an_py310 import test_main - - test_main.test_create_existing_item() - test_main.test_create_item() - test_main.test_create_item_bad_token() - test_main.test_read_nonexistent_item() - test_main.test_read_item() - test_main.test_read_item_bad_token() diff --git a/tests/test_tutorial/test_testing/test_main_b_an_py39.py b/tests/test_tutorial/test_testing/test_main_b_an_py39.py deleted file mode 100644 index 71f99726c..000000000 --- a/tests/test_tutorial/test_testing/test_main_b_an_py39.py +++ /dev/null @@ -1,13 +0,0 @@ -from ...utils import needs_py39 - - -@needs_py39 -def test_app(): - from docs_src.app_testing.app_b_an_py39 import test_main - - test_main.test_create_existing_item() - test_main.test_create_item() - test_main.test_create_item_bad_token() - test_main.test_read_nonexistent_item() - test_main.test_read_item() - test_main.test_read_item_bad_token() diff --git a/tests/test_tutorial/test_testing/test_main_b_py310.py b/tests/test_tutorial/test_testing/test_main_b_py310.py deleted file mode 100644 index e30cdc073..000000000 --- a/tests/test_tutorial/test_testing/test_main_b_py310.py +++ /dev/null @@ -1,13 +0,0 @@ -from ...utils import needs_py310 - - -@needs_py310 -def test_app(): - from docs_src.app_testing.app_b_py310 import test_main - - test_main.test_create_existing_item() - test_main.test_create_item() - test_main.test_create_item_bad_token() - test_main.test_read_nonexistent_item() - test_main.test_read_item() - test_main.test_read_item_bad_token() diff --git a/tests/test_tutorial/test_testing_dependencies/test_tutorial001.py b/tests/test_tutorial/test_testing_dependencies/test_tutorial001.py index af26307f5..00ee6ab1e 100644 --- a/tests/test_tutorial/test_testing_dependencies/test_tutorial001.py +++ b/tests/test_tutorial/test_testing_dependencies/test_tutorial001.py @@ -1,25 +1,48 @@ -from docs_src.dependency_testing.tutorial001 import ( - app, - client, - test_override_in_items, - test_override_in_items_with_params, - test_override_in_items_with_q, +import importlib +from types import ModuleType + +import pytest + +from ...utils import needs_py39, needs_py310 + + +@pytest.fixture( + name="test_module", + params=[ + "tutorial001", + pytest.param("tutorial001_py310", marks=needs_py310), + "tutorial001_an", + pytest.param("tutorial001_an_py39", marks=needs_py39), + pytest.param("tutorial001_an_py310", marks=needs_py310), + ], ) +def get_test_module(request: pytest.FixtureRequest) -> ModuleType: + mod: ModuleType = importlib.import_module( + f"docs_src.dependency_testing.{request.param}" + ) + return mod -def test_override_in_items_run(): +def test_override_in_items_run(test_module: ModuleType): + test_override_in_items = test_module.test_override_in_items + test_override_in_items() -def test_override_in_items_with_q_run(): +def test_override_in_items_with_q_run(test_module: ModuleType): + test_override_in_items_with_q = test_module.test_override_in_items_with_q + test_override_in_items_with_q() -def test_override_in_items_with_params_run(): +def test_override_in_items_with_params_run(test_module: ModuleType): + test_override_in_items_with_params = test_module.test_override_in_items_with_params + test_override_in_items_with_params() -def test_override_in_users(): +def test_override_in_users(test_module: ModuleType): + client = test_module.client response = client.get("/users/") assert response.status_code == 200, response.text assert response.json() == { @@ -28,7 +51,8 @@ def test_override_in_users(): } -def test_override_in_users_with_q(): +def test_override_in_users_with_q(test_module: ModuleType): + client = test_module.client response = client.get("/users/?q=foo") assert response.status_code == 200, response.text assert response.json() == { @@ -37,7 +61,8 @@ def test_override_in_users_with_q(): } -def test_override_in_users_with_params(): +def test_override_in_users_with_params(test_module: ModuleType): + client = test_module.client response = client.get("/users/?q=foo&skip=100&limit=200") assert response.status_code == 200, response.text assert response.json() == { @@ -46,7 +71,9 @@ def test_override_in_users_with_params(): } -def test_normal_app(): +def test_normal_app(test_module: ModuleType): + app = test_module.app + client = test_module.client app.dependency_overrides = None response = client.get("/items/?q=foo&skip=100&limit=200") assert response.status_code == 200, response.text diff --git a/tests/test_tutorial/test_testing_dependencies/test_tutorial001_an.py b/tests/test_tutorial/test_testing_dependencies/test_tutorial001_an.py deleted file mode 100644 index fc1f9149a..000000000 --- a/tests/test_tutorial/test_testing_dependencies/test_tutorial001_an.py +++ /dev/null @@ -1,56 +0,0 @@ -from docs_src.dependency_testing.tutorial001_an import ( - app, - client, - test_override_in_items, - test_override_in_items_with_params, - test_override_in_items_with_q, -) - - -def test_override_in_items_run(): - test_override_in_items() - - -def test_override_in_items_with_q_run(): - test_override_in_items_with_q() - - -def test_override_in_items_with_params_run(): - test_override_in_items_with_params() - - -def test_override_in_users(): - response = client.get("/users/") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Users!", - "params": {"q": None, "skip": 5, "limit": 10}, - } - - -def test_override_in_users_with_q(): - response = client.get("/users/?q=foo") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Users!", - "params": {"q": "foo", "skip": 5, "limit": 10}, - } - - -def test_override_in_users_with_params(): - response = client.get("/users/?q=foo&skip=100&limit=200") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Users!", - "params": {"q": "foo", "skip": 5, "limit": 10}, - } - - -def test_normal_app(): - app.dependency_overrides = None - response = client.get("/items/?q=foo&skip=100&limit=200") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Items!", - "params": {"q": "foo", "skip": 100, "limit": 200}, - } diff --git a/tests/test_tutorial/test_testing_dependencies/test_tutorial001_an_py310.py b/tests/test_tutorial/test_testing_dependencies/test_tutorial001_an_py310.py deleted file mode 100644 index a3d27f47f..000000000 --- a/tests/test_tutorial/test_testing_dependencies/test_tutorial001_an_py310.py +++ /dev/null @@ -1,75 +0,0 @@ -from ...utils import needs_py310 - - -@needs_py310 -def test_override_in_items_run(): - from docs_src.dependency_testing.tutorial001_an_py310 import test_override_in_items - - test_override_in_items() - - -@needs_py310 -def test_override_in_items_with_q_run(): - from docs_src.dependency_testing.tutorial001_an_py310 import ( - test_override_in_items_with_q, - ) - - test_override_in_items_with_q() - - -@needs_py310 -def test_override_in_items_with_params_run(): - from docs_src.dependency_testing.tutorial001_an_py310 import ( - test_override_in_items_with_params, - ) - - test_override_in_items_with_params() - - -@needs_py310 -def test_override_in_users(): - from docs_src.dependency_testing.tutorial001_an_py310 import client - - response = client.get("/users/") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Users!", - "params": {"q": None, "skip": 5, "limit": 10}, - } - - -@needs_py310 -def test_override_in_users_with_q(): - from docs_src.dependency_testing.tutorial001_an_py310 import client - - response = client.get("/users/?q=foo") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Users!", - "params": {"q": "foo", "skip": 5, "limit": 10}, - } - - -@needs_py310 -def test_override_in_users_with_params(): - from docs_src.dependency_testing.tutorial001_an_py310 import client - - response = client.get("/users/?q=foo&skip=100&limit=200") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Users!", - "params": {"q": "foo", "skip": 5, "limit": 10}, - } - - -@needs_py310 -def test_normal_app(): - from docs_src.dependency_testing.tutorial001_an_py310 import app, client - - app.dependency_overrides = None - response = client.get("/items/?q=foo&skip=100&limit=200") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Items!", - "params": {"q": "foo", "skip": 100, "limit": 200}, - } diff --git a/tests/test_tutorial/test_testing_dependencies/test_tutorial001_an_py39.py b/tests/test_tutorial/test_testing_dependencies/test_tutorial001_an_py39.py deleted file mode 100644 index f03ed5e07..000000000 --- a/tests/test_tutorial/test_testing_dependencies/test_tutorial001_an_py39.py +++ /dev/null @@ -1,75 +0,0 @@ -from ...utils import needs_py39 - - -@needs_py39 -def test_override_in_items_run(): - from docs_src.dependency_testing.tutorial001_an_py39 import test_override_in_items - - test_override_in_items() - - -@needs_py39 -def test_override_in_items_with_q_run(): - from docs_src.dependency_testing.tutorial001_an_py39 import ( - test_override_in_items_with_q, - ) - - test_override_in_items_with_q() - - -@needs_py39 -def test_override_in_items_with_params_run(): - from docs_src.dependency_testing.tutorial001_an_py39 import ( - test_override_in_items_with_params, - ) - - test_override_in_items_with_params() - - -@needs_py39 -def test_override_in_users(): - from docs_src.dependency_testing.tutorial001_an_py39 import client - - response = client.get("/users/") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Users!", - "params": {"q": None, "skip": 5, "limit": 10}, - } - - -@needs_py39 -def test_override_in_users_with_q(): - from docs_src.dependency_testing.tutorial001_an_py39 import client - - response = client.get("/users/?q=foo") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Users!", - "params": {"q": "foo", "skip": 5, "limit": 10}, - } - - -@needs_py39 -def test_override_in_users_with_params(): - from docs_src.dependency_testing.tutorial001_an_py39 import client - - response = client.get("/users/?q=foo&skip=100&limit=200") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Users!", - "params": {"q": "foo", "skip": 5, "limit": 10}, - } - - -@needs_py39 -def test_normal_app(): - from docs_src.dependency_testing.tutorial001_an_py39 import app, client - - app.dependency_overrides = None - response = client.get("/items/?q=foo&skip=100&limit=200") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Items!", - "params": {"q": "foo", "skip": 100, "limit": 200}, - } diff --git a/tests/test_tutorial/test_testing_dependencies/test_tutorial001_py310.py b/tests/test_tutorial/test_testing_dependencies/test_tutorial001_py310.py deleted file mode 100644 index 776b916ff..000000000 --- a/tests/test_tutorial/test_testing_dependencies/test_tutorial001_py310.py +++ /dev/null @@ -1,75 +0,0 @@ -from ...utils import needs_py310 - - -@needs_py310 -def test_override_in_items_run(): - from docs_src.dependency_testing.tutorial001_py310 import test_override_in_items - - test_override_in_items() - - -@needs_py310 -def test_override_in_items_with_q_run(): - from docs_src.dependency_testing.tutorial001_py310 import ( - test_override_in_items_with_q, - ) - - test_override_in_items_with_q() - - -@needs_py310 -def test_override_in_items_with_params_run(): - from docs_src.dependency_testing.tutorial001_py310 import ( - test_override_in_items_with_params, - ) - - test_override_in_items_with_params() - - -@needs_py310 -def test_override_in_users(): - from docs_src.dependency_testing.tutorial001_py310 import client - - response = client.get("/users/") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Users!", - "params": {"q": None, "skip": 5, "limit": 10}, - } - - -@needs_py310 -def test_override_in_users_with_q(): - from docs_src.dependency_testing.tutorial001_py310 import client - - response = client.get("/users/?q=foo") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Users!", - "params": {"q": "foo", "skip": 5, "limit": 10}, - } - - -@needs_py310 -def test_override_in_users_with_params(): - from docs_src.dependency_testing.tutorial001_py310 import client - - response = client.get("/users/?q=foo&skip=100&limit=200") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Users!", - "params": {"q": "foo", "skip": 5, "limit": 10}, - } - - -@needs_py310 -def test_normal_app(): - from docs_src.dependency_testing.tutorial001_py310 import app, client - - app.dependency_overrides = None - response = client.get("/items/?q=foo&skip=100&limit=200") - assert response.status_code == 200, response.text - assert response.json() == { - "message": "Hello Items!", - "params": {"q": "foo", "skip": 100, "limit": 200}, - } diff --git a/tests/utils.py b/tests/utils.py index 460c028f7..ae9543e3b 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -2,6 +2,7 @@ import sys import pytest from fastapi._compat import PYDANTIC_V2 +from inline_snapshot import Snapshot needs_py39 = pytest.mark.skipif(sys.version_info < (3, 9), reason="requires python3.9+") needs_py310 = pytest.mark.skipif( @@ -9,3 +10,25 @@ needs_py310 = pytest.mark.skipif( ) needs_pydanticv2 = pytest.mark.skipif(not PYDANTIC_V2, reason="requires Pydantic v2") needs_pydanticv1 = pytest.mark.skipif(PYDANTIC_V2, reason="requires Pydantic v1") + + +def pydantic_snapshot( + *, + v2: Snapshot, + v1: Snapshot, # TODO: remove v1 argument when deprecating Pydantic v1 +): + """ + This function should be used like this: + + >>> assert value == pydantic_snapshot(v2=snapshot(),v1=snapshot()) + + inline-snapshot will create the snapshots when pytest is executed for each versions of pydantic. + + It is also possible to use the function inside snapshots for version-specific values. + + >>> assert value == snapshot({ + "data": "some data", + "version_specific": pydantic_snapshot(v2=snapshot(),v1=snapshot()), + }) + """ + return v2 if PYDANTIC_V2 else v1