From 7ff5da8bf2b8bfe895e4621f630e9fc3f2c434f4 Mon Sep 17 00:00:00 2001 From: Dom Date: Tue, 6 Aug 2024 14:46:39 +0100 Subject: [PATCH 01/88] edit middleware docs code sample to use perf_counter as a timer --- docs_src/middleware/tutorial001.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs_src/middleware/tutorial001.py b/docs_src/middleware/tutorial001.py index 6bab3410a..e65a7dade 100644 --- a/docs_src/middleware/tutorial001.py +++ b/docs_src/middleware/tutorial001.py @@ -7,8 +7,8 @@ app = FastAPI() @app.middleware("http") async def add_process_time_header(request: Request, call_next): - start_time = time.time() + start_time = time.perf_counter() response = await call_next(request) - process_time = time.time() - start_time + process_time = time.perf_counter() - start_time response.headers["X-Process-Time"] = str(process_time) return response From 9bfc48ad9fba044462eb9d0e1b556cf721f56ae4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 17 Aug 2024 16:20:31 -0500 Subject: [PATCH 02/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20FastAPI=20People,?= =?UTF-8?q?=20do=20not=20translate=20to=20have=20the=20most=20recent=20inf?= =?UTF-8?q?o=20(#12034)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/az/docs/fastapi-people.md | 185 --------------------- docs/de/docs/fastapi-people.md | 176 -------------------- docs/em/docs/fastapi-people.md | 183 --------------------- docs/en/data/members.yml | 12 +- docs/fr/docs/fastapi-people.md | 180 --------------------- docs/ja/docs/fastapi-people.md | 184 --------------------- docs/pl/docs/fastapi-people.md | 178 --------------------- docs/pt/docs/fastapi-people.md | 183 --------------------- docs/ru/docs/fastapi-people.md | 184 --------------------- docs/tr/docs/fastapi-people.md | 183 --------------------- docs/uk/docs/fastapi-people.md | 183 --------------------- docs/zh-hant/docs/fastapi-people.md | 239 ---------------------------- docs/zh/docs/fastapi-people.md | 239 ---------------------------- scripts/docs.py | 1 + scripts/mkdocs_hooks.py | 1 + 15 files changed, 8 insertions(+), 2303 deletions(-) delete mode 100644 docs/az/docs/fastapi-people.md delete mode 100644 docs/de/docs/fastapi-people.md delete mode 100644 docs/em/docs/fastapi-people.md delete mode 100644 docs/fr/docs/fastapi-people.md delete mode 100644 docs/ja/docs/fastapi-people.md delete mode 100644 docs/pl/docs/fastapi-people.md delete mode 100644 docs/pt/docs/fastapi-people.md delete mode 100644 docs/ru/docs/fastapi-people.md delete mode 100644 docs/tr/docs/fastapi-people.md delete mode 100644 docs/uk/docs/fastapi-people.md delete mode 100644 docs/zh-hant/docs/fastapi-people.md delete mode 100644 docs/zh/docs/fastapi-people.md diff --git a/docs/az/docs/fastapi-people.md b/docs/az/docs/fastapi-people.md deleted file mode 100644 index 9bb7ad6ea..000000000 --- a/docs/az/docs/fastapi-people.md +++ /dev/null @@ -1,185 +0,0 @@ ---- -hide: - - navigation ---- - -# FastAPI İnsanlar - -FastAPI-ın bütün mənşəli insanları qəbul edən heyrətamiz icması var. - - - -## Yaradıcı - İcraçı - -Salam! 👋 - -Bu mənəm: - -{% if people %} -
-{% for user in people.maintainers %} - -
@{{ user.login }}
Cavablar: {{ user.answers }}
Pull Request-lər: {{ user.prs }}
-{% endfor %} - -
-{% endif %} - -Mən **FastAPI**-ın yaradıcısı və icraçısıyam. Əlavə məlumat almaq üçün [Yardım FastAPI - Yardım alın - Müəlliflə əlaqə qurun](help-fastapi.md#connect-with-the-author){.internal-link target=_blank} səhifəsinə baxa bilərsiniz. - -...Burada isə sizə icmanı göstərmək istəyirəm. - ---- - -**FastAPI** icmadan çoxlu dəstək alır və mən onların əməyini vurğulamaq istəyirəm. - -Bu insanlar: - -* [GitHub-da başqalarının suallarına kömək edirlər](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. -* [Pull Request-lər yaradırlar](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. -* Pull Request-ləri ([xüsusilə tərcümələr üçün vacib olan](contributing.md#translations){.internal-link target=_blank}.) nəzərdən keçirirlər. - -Bu insanlara təşəkkür edirəm. 👏 🙇 - -## Keçən ayın ən fəal istifadəçiləri - -Bu istifadəçilər keçən ay [GitHub-da başqalarının suallarına](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} ən çox kömək edənlərdir. ☕ - -{% if people %} -
-{% for user in people.last_month_experts[:10] %} - -
@{{ user.login }}
Cavablandırılmış suallar: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Mütəxəssislər - -Burada **FastAPI Mütəxəssisləri** var. 🤓 - -Bu istifadəçilər indiyə qədər [GitHub-da başqalarının suallarına](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} ən çox kömək edənlərdir. - -Onlar bir çox insanlara kömək edərək mütəxəssis olduqlarını sübut ediblər. ✨ - -{% if people %} -
-{% for user in people.experts[:50] %} - -
@{{ user.login }}
Cavablandırılmış suallar: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Ən yaxşı əməkdaşlar - -Burada **Ən yaxşı əməkdaşlar** var. 👷 - -Bu istifadəçilərin ən çox *birləşdirilmiş* [Pull Request-ləri var](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. - -Onlar mənbə kodu, sənədləmə, tərcümələr və s. barədə əmək göstərmişlər. 📦 - -{% if people %} -
-{% for user in people.top_contributors[:50] %} - -
@{{ user.login }}
Pull Request-lər: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -Bundan başqa bir neçə (yüzdən çox) əməkdaş var ki, onları FastAPI GitHub Əməkdaşlar səhifəsində görə bilərsiniz. 👷 - -## Ən çox rəy verənlər - -Bu istifadəçilər **ən çox rəy verənlər**dir. - -### Tərcümələr üçün rəylər - -Mən yalnız bir neçə dildə danışıram (və çox da yaxşı deyil 😅). Bu səbəbdən, rəy verənlər sənədlərin [**tərcümələrini təsdiqləmək üçün gücə malik olanlar**](contributing.md#translations){.internal-link target=_blank}dır. Onlar olmadan, bir çox dilə tərcümə olunmuş sənədlər olmazdı. - ---- - -Başqalarının Pull Request-lərinə **Ən çox rəy verənlər** 🕵️ kodun, sənədlərin və xüsusilə də **tərcümələrin** keyfiyyətini təmin edirlər. - -{% if people %} -
-{% for user in people.top_translations_reviewers[:50] %} - -
@{{ user.login }}
Rəylər: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Sponsorlar - -Bunlar **Sponsorlar**dır. 😎 - -Onlar mənim **FastAPI** (və digər) işlərimi əsasən GitHub Sponsorlar vasitəsilə dəstəkləyirlər. - -{% if sponsors %} - -{% if sponsors.gold %} - -### Qızıl Sponsorlar - -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### Gümüş Sponsorlar - -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### Bürünc Sponsorlar - -{% for sponsor in sponsors.bronze -%} - -{% endfor %} -{% endif %} - -{% endif %} - -### Fərdi Sponsorlar - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -
- -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - - - -{% endif %} -{% endfor %} - -
- -{% endfor %} -{% endif %} - -## Məlumatlar haqqında - texniki detallar - -Bu səhifənin əsas məqsədi, icmanın başqalarına kömək etmək üçün göstərdiyi əməyi vurğulamaqdır. - -Xüsusilə də normalda daha az görünən və bir çox hallarda daha çətin olan, başqalarının suallarına kömək etmək və tərcümələrlə bağlı Pull Request-lərə rəy vermək kimi səy göstərmək. - -Bu səhifənin məlumatları hər ay hesablanır və siz buradan mənbə kodunu oxuya bilərsiniz. - -Burada sponsorların əməyini də vurğulamaq istəyirəm. - -Mən həmçinin alqoritmi, bölmələri, eşikləri və s. yeniləmək hüququnu da qoruyuram (hər ehtimala qarşı 🤷). diff --git a/docs/de/docs/fastapi-people.md b/docs/de/docs/fastapi-people.md deleted file mode 100644 index deaecf214..000000000 --- a/docs/de/docs/fastapi-people.md +++ /dev/null @@ -1,176 +0,0 @@ ---- -hide: - - navigation ---- - -# FastAPI Leute - -FastAPI hat eine großartige Gemeinschaft, die Menschen mit unterschiedlichstem Hintergrund willkommen heißt. - -## Erfinder - Betreuer - -Hey! 👋 - -Das bin ich: - -{% if people %} -
-{% for user in people.maintainers %} - -
@{{ user.login }}
Answers: {{ user.answers }}
Pull Requests: {{ user.prs }}
-{% endfor %} - -
-{% endif %} - -Ich bin der Erfinder und Betreuer von **FastAPI**. Sie können mehr darüber in [FastAPI helfen – Hilfe erhalten – Mit dem Autor vernetzen](help-fastapi.md#mit-dem-autor-vernetzen){.internal-link target=_blank} erfahren. - -... Aber hier möchte ich Ihnen die Gemeinschaft vorstellen. - ---- - -**FastAPI** erhält eine Menge Unterstützung aus der Gemeinschaft. Und ich möchte ihre Beiträge hervorheben. - -Das sind die Menschen, die: - -* [Anderen bei Fragen auf GitHub helfen](help-fastapi.md#anderen-bei-fragen-auf-github-helfen){.internal-link target=_blank}. -* [Pull Requests erstellen](help-fastapi.md#einen-pull-request-erstellen){.internal-link target=_blank}. -* Pull Requests überprüfen (Review), [besonders wichtig für Übersetzungen](contributing.md#ubersetzungen){.internal-link target=_blank}. - -Eine Runde Applaus für sie. 👏 🙇 - -## Aktivste Benutzer im letzten Monat - -Hier die Benutzer, die im letzten Monat am meisten [anderen mit Fragen auf Github](help-fastapi.md#anderen-bei-fragen-auf-github-helfen){.internal-link target=_blank} geholfen haben. ☕ - -{% if people %} -
-{% for user in people.last_month_active %} - -
@{{ user.login }}
Fragen beantwortet: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Experten - -Hier die **FastAPI-Experten**. 🤓 - -Das sind die Benutzer, die *insgesamt* [anderen am meisten mit Fragen auf GitHub geholfen haben](help-fastapi.md#anderen-bei-fragen-auf-github-helfen){.internal-link target=_blank}. - -Sie haben bewiesen, dass sie Experten sind, weil sie vielen anderen geholfen haben. ✨ - -{% if people %} -
-{% for user in people.experts %} - -
@{{ user.login }}
Fragen beantwortet: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Top-Mitwirkende - -Hier sind die **Top-Mitwirkenden**. 👷 - -Diese Benutzer haben [die meisten Pull Requests erstellt](help-fastapi.md#einen-pull-request-erstellen){.internal-link target=_blank} welche *gemerged* wurden. - -Sie haben Quellcode, Dokumentation, Übersetzungen, usw. beigesteuert. 📦 - -{% if people %} -
-{% for user in people.top_contributors %} - -
@{{ user.login }}
Pull Requests: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -Es gibt viele andere Mitwirkende (mehr als hundert), Sie können sie alle auf der FastAPI GitHub Contributors-Seite sehen. 👷 - -## Top-Rezensenten - -Diese Benutzer sind die **Top-Rezensenten**. 🕵️ - -### Rezensionen für Übersetzungen - -Ich spreche nur ein paar Sprachen (und nicht sehr gut 😅). Daher bestätigen Reviewer [**Übersetzungen der Dokumentation**](contributing.md#ubersetzungen){.internal-link target=_blank}. Ohne sie gäbe es keine Dokumentation in mehreren anderen Sprachen. - ---- - -Die **Top-Reviewer** 🕵️ haben die meisten Pull Requests von anderen überprüft und stellen die Qualität des Codes, der Dokumentation und insbesondere der **Übersetzungen** sicher. - -{% if people %} -
-{% for user in people.top_reviewers %} - -
@{{ user.login }}
Reviews: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Sponsoren - -Dies sind die **Sponsoren**. 😎 - -Sie unterstützen meine Arbeit an **FastAPI** (und andere), hauptsächlich durch GitHub-Sponsoren. - -### Gold Sponsoren - -{% if sponsors %} -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -### Silber Sponsoren - -{% if sponsors %} -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if people %} -{% if people.sponsors_50 %} - -### Bronze Sponsoren - -
-{% for user in people.sponsors_50 %} - - -{% endfor %} - -
- -{% endif %} -{% endif %} - -### Individuelle Sponsoren - -{% if people %} -
-{% for user in people.sponsors %} - - -{% endfor %} - -
-{% endif %} - -## Über diese Daten - technische Details - -Der Hauptzweck dieser Seite ist es zu zeigen, wie die Gemeinschaft anderen hilft. - -Das beinhaltet auch Hilfe, die normalerweise weniger sichtbar und in vielen Fällen mühsamer ist, wie, anderen bei Problemen zu helfen und Pull Requests mit Übersetzungen zu überprüfen. - -Diese Daten werden jeden Monat berechnet, Sie können den Quellcode hier lesen. - -Hier weise ich auch auf Beiträge von Sponsoren hin. - -Ich behalte mir auch das Recht vor, den Algorithmus, die Abschnitte, die Schwellenwerte usw. zu aktualisieren (nur für den Fall 🤷). diff --git a/docs/em/docs/fastapi-people.md b/docs/em/docs/fastapi-people.md deleted file mode 100644 index 75880e216..000000000 --- a/docs/em/docs/fastapi-people.md +++ /dev/null @@ -1,183 +0,0 @@ ---- -hide: - - navigation ---- - -# FastAPI 👫👫 - -FastAPI ✔️ 🎆 👪 👈 🙋 👫👫 ⚪️➡️ 🌐 🖥. - -## 👼 - 🐛 - -🙋 ❗ 👶 - -👉 👤: - -{% if people %} -
-{% for user in people.maintainers %} - -
@{{ user.login }}
❔: {{ user.answers }}
🚲 📨: {{ user.prs }}
-{% endfor %} - -
-{% endif %} - -👤 👼 & 🐛 **FastAPI**. 👆 💪 ✍ 🌅 🔃 👈 [ℹ FastAPI - 🤚 ℹ - 🔗 ⏮️ 📕](help-fastapi.md#_3){.internal-link target=_blank}. - -...✋️ 📥 👤 💚 🎦 👆 👪. - ---- - -**FastAPI** 📨 📚 🐕‍🦺 ⚪️➡️ 👪. & 👤 💚 🎦 👫 💰. - -👫 👫👫 👈: - -* [ℹ 🎏 ⏮️ ❔ 📂](help-fastapi.md#i){.internal-link target=_blank}. -* [✍ 🚲 📨](help-fastapi.md#_15){.internal-link target=_blank}. -* 📄 🚲 📨, [✴️ ⚠ ✍](contributing.md#_9){.internal-link target=_blank}. - -👏 👫. 👶 👶 - -## 🌅 🦁 👩‍💻 🏁 🗓️ - -👫 👩‍💻 👈 ✔️ [🤝 🎏 🏆 ⏮️ ❔ 📂](help-fastapi.md#i){.internal-link target=_blank} ⏮️ 🏁 🗓️. 👶 - -{% if people %} -
-{% for user in people.last_month_experts[:10] %} - -
@{{ user.login }}
❔ 📨: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## 🕴 - -📥 **FastAPI 🕴**. 👶 - -👫 👩‍💻 👈 ✔️ [ℹ 🎏 🏆 ⏮️ ❔ 📂](help-fastapi.md#i){.internal-link target=_blank} 🔘 *🌐 🕰*. - -👫 ✔️ 🎦 🕴 🤝 📚 🎏. 👶 - -{% if people %} -
-{% for user in people.experts[:50] %} - -
@{{ user.login }}
❔ 📨: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## 🔝 👨‍🔬 - -📥 **🔝 👨‍🔬**. 👶 - -👉 👩‍💻 ✔️ [✍ 🏆 🚲 📨](help-fastapi.md#_15){.internal-link target=_blank} 👈 ✔️ *🔗*. - -👫 ✔️ 📉 ℹ 📟, 🧾, ✍, ♒️. 👶 - -{% if people %} -
-{% for user in people.top_contributors[:50] %} - -
@{{ user.login }}
🚲 📨: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -📤 📚 🎏 👨‍🔬 (🌅 🌘 💯), 👆 💪 👀 👫 🌐 FastAPI 📂 👨‍🔬 📃. 👶 - -## 🔝 👨‍🔬 - -👫 👩‍💻 **🔝 👨‍🔬**. 👶 👶 - -### 📄 ✍ - -👤 🕴 💬 👩‍❤‍👨 🇪🇸 (& 🚫 📶 👍 👶). , 👨‍🔬 🕐 👈 ✔️ [**🏋️ ✔ ✍**](contributing.md#_9){.internal-link target=_blank} 🧾. 🍵 👫, 📤 🚫🔜 🧾 📚 🎏 🇪🇸. - ---- - -**🔝 👨‍🔬** 👶 👶 ✔️ 📄 🏆 🚲 📨 ⚪️➡️ 🎏, 🚚 🔆 📟, 🧾, & ✴️, **✍**. - -{% if people %} -
-{% for user in people.top_translations_reviewers[:50] %} - -
@{{ user.login }}
📄: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## 💰 - -👫 **💰**. 👶 - -👫 🔗 👇 👷 ⏮️ **FastAPI** (& 🎏), ✴️ 🔘 📂 💰. - -{% if sponsors %} - -{% if sponsors.gold %} - -### 🌟 💰 - -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### 🥇1st 💰 - -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### 🥈2nd 💰 - -{% for sponsor in sponsors.bronze -%} - -{% endfor %} -{% endif %} - -{% endif %} - -### 🎯 💰 - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -
- -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - - - -{% endif %} -{% endfor %} - -
- -{% endfor %} -{% endif %} - -## 🔃 📊 - 📡 ℹ - -👑 🎯 👉 📃 🎦 🎯 👪 ℹ 🎏. - -✴️ ✅ 🎯 👈 🛎 🌘 ⭐, & 📚 💼 🌅 😩, 💖 🤝 🎏 ⏮️ ❔ & ⚖ 🚲 📨 ⏮️ ✍. - -💽 ⚖ 🔠 🗓️, 👆 💪 ✍ ℹ 📟 📥. - -📥 👤 🎦 💰 ⚪️➡️ 💰. - -👤 🏦 ▶️️ ℹ 📊, 📄, ⚡, ♒️ (💼 🤷). diff --git a/docs/en/data/members.yml b/docs/en/data/members.yml index 0b9e7b94c..0069f8c75 100644 --- a/docs/en/data/members.yml +++ b/docs/en/data/members.yml @@ -1,19 +1,19 @@ members: - login: tiangolo - avatar_url: https://github.com/tiangolo.png + avatar_url: https://avatars.githubusercontent.com/u/1326112 url: https://github.com/tiangolo - login: Kludex - avatar_url: https://github.com/Kludex.png + avatar_url: https://avatars.githubusercontent.com/u/7353520 url: https://github.com/Kludex - login: alejsdev - avatar_url: https://github.com/alejsdev.png + avatar_url: https://avatars.githubusercontent.com/u/90076947 url: https://github.com/alejsdev - login: svlandeg - avatar_url: https://github.com/svlandeg.png + avatar_url: https://avatars.githubusercontent.com/u/8796347 url: https://github.com/svlandeg - login: estebanx64 - avatar_url: https://github.com/estebanx64.png + avatar_url: https://avatars.githubusercontent.com/u/10840422 url: https://github.com/estebanx64 - login: patrick91 - avatar_url: https://github.com/patrick91.png + avatar_url: https://avatars.githubusercontent.com/u/667029 url: https://github.com/patrick91 diff --git a/docs/fr/docs/fastapi-people.md b/docs/fr/docs/fastapi-people.md deleted file mode 100644 index 52a79032a..000000000 --- a/docs/fr/docs/fastapi-people.md +++ /dev/null @@ -1,180 +0,0 @@ ---- -hide: - - navigation ---- - -# La communauté FastAPI - -FastAPI a une communauté extraordinaire qui accueille des personnes de tous horizons. - -## Créateur - Mainteneur - -Salut! 👋 - -C'est moi : - -{% if people %} -
-{% for user in people.maintainers %} - -
@{{ user.login }}
Réponses: {{ user.answers }}
Pull Requests: {{ user.prs }}
-{% endfor %} - -
-{% endif %} - -Je suis le créateur et le responsable de **FastAPI**. Vous pouvez en lire plus à ce sujet dans [Aide FastAPI - Obtenir de l'aide - Se rapprocher de l'auteur](help-fastapi.md#se-rapprocher-de-lauteur){.internal-link target=_blank}. - -...Mais ici, je veux vous montrer la communauté. - ---- - -**FastAPI** reçoit beaucoup de soutien de la part de la communauté. Et je tiens à souligner leurs contributions. - -Ce sont ces personnes qui : - -* [Aident les autres à résoudre des problèmes (questions) dans GitHub](help-fastapi.md#aider-les-autres-a-resoudre-les-problemes-dans-github){.internal-link target=_blank}. -* [Créent des Pull Requests](help-fastapi.md#creer-une-pull-request){.internal-link target=_blank}. -* Review les Pull Requests, [particulièrement important pour les traductions](contributing.md#traductions){.internal-link target=_blank}. - -Une salve d'applaudissements pour eux. 👏 🙇 - -## Utilisateurs les plus actifs le mois dernier - -Ce sont les utilisateurs qui ont [aidé le plus les autres avec des problèmes (questions) dans GitHub](help-fastapi.md#aider-les-autres-a-resoudre-les-problemes-dans-github){.internal-link target=_blank} au cours du dernier mois. ☕ - -{% if people %} -
-{% for user in people.last_month_experts[:10] %} - -
@{{ user.login }}
Questions répondues: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Experts - -Voici les **Experts FastAPI**. 🤓 - -Ce sont les utilisateurs qui ont [aidé le plus les autres avec des problèmes (questions) dans GitHub](help-fastapi.md#aider-les-autres-a-resoudre-les-problemes-dans-github){.internal-link target=_blank} depuis *toujours*. - -Ils ont prouvé qu'ils étaient des experts en aidant beaucoup d'autres personnes. ✨ - -{% if people %} -
-{% for user in people.experts[:50] %} - -
@{{ user.login }}
Questions répondues: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Principaux contributeurs - -Ces utilisateurs sont les **Principaux contributeurs**. 👷 - -Ces utilisateurs ont [créé le plus grand nombre de demandes Pull Request](help-fastapi.md#creer-une-pull-request){.internal-link target=_blank} qui ont été *merged*. - -Ils ont contribué au code source, à la documentation, aux traductions, etc. 📦 - -{% if people %} -
-{% for user in people.top_contributors[:50] %} - -
@{{ user.login }}
Pull Requests: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -Il existe de nombreux autres contributeurs (plus d'une centaine), vous pouvez les voir tous dans la Page des contributeurs de FastAPI GitHub. 👷 - -## Principaux Reviewers - -Ces utilisateurs sont les **Principaux Reviewers**. 🕵️ - -### Reviewers des traductions - -Je ne parle que quelques langues (et pas très bien 😅). Ainsi, les reviewers sont ceux qui ont le [**pouvoir d'approuver les traductions**](contributing.md#traductions){.internal-link target=_blank} de la documentation. Sans eux, il n'y aurait pas de documentation dans plusieurs autres langues. - ---- - -Les **Principaux Reviewers** 🕵️ ont examiné le plus grand nombre de demandes Pull Request des autres, assurant la qualité du code, de la documentation, et surtout, des **traductions**. - -{% if people %} -
-{% for user in people.top_translations_reviewers[:50] %} - -
@{{ user.login }}
Reviews: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Sponsors - -Ce sont les **Sponsors**. 😎 - -Ils soutiennent mon travail avec **FastAPI** (et d'autres) avec GitHub Sponsors. - -{% if sponsors %} - -{% if sponsors.gold %} - -### Gold Sponsors - -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### Silver Sponsors - -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### Bronze Sponsors - -{% for sponsor in sponsors.bronze -%} - -{% endfor %} -{% endif %} - -{% endif %} -### Individual Sponsors - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -
- -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - - - -{% endif %} -{% endfor %} - -
- -{% endfor %} -{% endif %} - -## À propos des données - détails techniques - -L'intention de cette page est de souligner l'effort de la communauté pour aider les autres. - -Notamment en incluant des efforts qui sont normalement moins visibles, et, dans de nombreux cas, plus difficile, comme aider d'autres personnes à résoudre des problèmes et examiner les Pull Requests de traduction. - -Les données sont calculées chaque mois, vous pouvez lire le code source ici. - -Je me réserve également le droit de mettre à jour l'algorithme, les sections, les seuils, etc. (juste au cas où 🤷). diff --git a/docs/ja/docs/fastapi-people.md b/docs/ja/docs/fastapi-people.md deleted file mode 100644 index aaf76ba21..000000000 --- a/docs/ja/docs/fastapi-people.md +++ /dev/null @@ -1,184 +0,0 @@ ---- -hide: - - navigation ---- - -# FastAPI People - -FastAPIには、様々なバックグラウンドの人々を歓迎する素晴らしいコミュニティがあります。 - -## Creator - Maintainer - -こんにちは! 👋 - -これが私です: - -{% if people %} -
-{% for user in people.maintainers %} - -
@{{ user.login }}
Answers: {{ user.answers }}
Pull Requests: {{ user.prs }}
-{% endfor %} - -
- -{% endif %} - -私は **FastAPI** の作成者および Maintainer です。詳しくは [FastAPIを応援 - ヘルプの入手 - 開発者とつながる](help-fastapi.md#_1){.internal-link target=_blank} に記載しています。 - -...ところで、ここではコミュニティを紹介したいと思います。 - ---- - -**FastAPI** は、コミュニティから多くのサポートを受けています。そこで、彼らの貢献にスポットライトを当てたいと思います。 - -紹介するのは次のような人々です: - -* [GitHub issuesで他の人を助ける](help-fastapi.md#github-issues){.internal-link target=_blank}。 -* [プルリクエストをする](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}。 -* プルリクエストのレビューをする ([特に翻訳に重要](contributing.md#_8){.internal-link target=_blank})。 - -彼らに大きな拍手を。👏 🙇 - -## 先月最もアクティブだったユーザー - -彼らは、先月の[GitHub issuesで最も多くの人を助けた](help-fastapi.md#github-issues){.internal-link target=_blank}ユーザーです。☕ - -{% if people %} -
-{% for user in people.last_month_experts[:10] %} - -
@{{ user.login }}
Issues replied: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Experts - -**FastAPI experts** を紹介します。🤓 - -彼らは、*これまでに* [GitHub issuesで最も多くの人を助けた](help-fastapi.md#github-issues){.internal-link target=_blank}ユーザーです。 - -多くの人を助けることでexpertsであると示されています。✨ - -{% if people %} -
-{% for user in people.experts[:50] %} - -
@{{ user.login }}
Issues replied: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Top Contributors - -**Top Contributors** を紹介します。👷 - -彼らは、*マージされた* [最も多くのプルリクエストを作成した](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}ユーザーです。 - -ソースコード、ドキュメント、翻訳などに貢献してくれました。📦 - -{% if people %} -
-{% for user in people.top_contributors[:50] %} - -
@{{ user.login }}
Pull Requests: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -他にもたくさん (100人以上) の contributors がいます。FastAPI GitHub Contributors ページですべての contributors を確認できます。👷 - -## Top Reviewers - -以下のユーザーは **Top Reviewers** です。🕵️ - -### 翻訳のレビュー - -私は少しの言語しか話せません (もしくはあまり上手ではありません😅)。したがって、reviewers は、ドキュメントの[**翻訳を承認する権限**](contributing.md#_8){.internal-link target=_blank}を持っています。それらがなければ、いくつかの言語のドキュメントはなかったでしょう。 - ---- - -**Top Reviewers** 🕵️は、他の人からのプルリクエストのほとんどをレビューし、コード、ドキュメント、特に**翻訳**の品質を保証しています。 - -{% if people %} -
-{% for user in people.top_translations_reviewers[:50] %} - -
@{{ user.login }}
Reviews: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Sponsors - -**Sponsors** を紹介します。😎 - -彼らは、GitHub Sponsors を介して私の **FastAPI** などに関する活動を支援してくれています。 - -{% if sponsors %} - -{% if sponsors.gold %} - -### Gold Sponsors - -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### Silver Sponsors - -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### Bronze Sponsors - -{% for sponsor in sponsors.bronze -%} - -{% endfor %} -{% endif %} - -{% endif %} - -### Individual Sponsors - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -
- -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - - - -{% endif %} -{% endfor %} - -
- -{% endfor %} -{% endif %} - -## データについて - 技術詳細 - -このページの目的は、他の人を助けるためのコミュニティの努力にスポットライトを当てるためです。 - -特に、他の人の issues を支援したり、翻訳のプルリクエストを確認したりするなど、通常は目立たず、多くの場合、より困難な作業を含みます。 - -データは毎月集計されます。ソースコードはこちらで確認できます。 - -ここでは、スポンサーの貢献も強調しています。 - -アルゴリズム、セクション、閾値などは更新されるかもしれません (念のために 🤷)。 diff --git a/docs/pl/docs/fastapi-people.md b/docs/pl/docs/fastapi-people.md deleted file mode 100644 index 6c431b401..000000000 --- a/docs/pl/docs/fastapi-people.md +++ /dev/null @@ -1,178 +0,0 @@ -# Ludzie FastAPI - -FastAPI posiada wspaniałą społeczność, która jest otwarta dla ludzi z każdego środowiska. - -## Twórca - Opienik - -Cześć! 👋 - -To ja: - -{% if people %} -
-{% for user in people.maintainers %} - -
@{{ user.login }}
Liczba odpowiedzi: {{ user.answers }}
Pull Requesty: {{ user.prs }}
-{% endfor %} - -
-{% endif %} - -Jestem twórcą i opiekunem **FastAPI**. Możesz przeczytać więcej na ten temat w [Pomoc FastAPI - Uzyskaj pomoc - Skontaktuj się z autorem](help-fastapi.md#connect-with-the-author){.internal-link target=_blank}. - -...Ale tutaj chcę pokazać Ci społeczność. - ---- - -**FastAPI** otrzymuje wiele wsparcia od społeczności. Chciałbym podkreślić ich wkład. - -To są ludzie, którzy: - -* [Pomagają innym z pytaniami na GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. -* [Tworzą Pull Requesty](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. -* Oceniają Pull Requesty, [to szczególnie ważne dla tłumaczeń](contributing.md#translations){.internal-link target=_blank}. - -Proszę o brawa dla nich. 👏 🙇 - -## Najaktywniejsi użytkownicy w zeszłym miesiącu - -Oto niektórzy użytkownicy, którzy [pomagali innym w największej liczbie pytań na GitHubie](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} podczas ostatniego miesiąca. ☕ - -{% if people %} -
-{% for user in people.last_month_active %} - -
@{{ user.login }}
Udzielonych odpowiedzi: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Eksperci - -Oto **eksperci FastAPI**. 🤓 - -To użytkownicy, którzy [pomogli innym z największa liczbą pytań na GitHubie](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} od *samego początku*. - -Poprzez pomoc wielu innym, udowodnili, że są ekspertami. ✨ - -{% if people %} -
-{% for user in people.experts %} - -
@{{ user.login }}
Udzielonych odpowiedzi: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Najlepsi Kontrybutorzy - -Oto **Najlepsi Kontrybutorzy**. 👷 - -Ci użytkownicy [stworzyli najwięcej Pull Requestów](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}, które zostały *wcalone*. - -Współtworzyli kod źródłowy, dokumentację, tłumaczenia itp. 📦 - -{% if people %} -
-{% for user in people.top_contributors %} - -
@{{ user.login }}
Pull Requesty: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -Jest wielu więcej kontrybutorów (ponad setka), możesz zobaczyć ich wszystkich na stronie Kontrybutorzy FastAPI na GitHub. 👷 - -## Najlepsi Oceniajacy - -Ci uzytkownicy są **Najlepszymi oceniającymi**. 🕵️ - -### Oceny Tłumaczeń - -Ja mówię tylko kilkoma językami (i to niezbyt dobrze 😅). Zatem oceniający są tymi, którzy mają [**moc zatwierdzania tłumaczeń**](contributing.md#translations){.internal-link target=_blank} dokumentacji. Bez nich nie byłoby dokumentacji w kilku innych językach. - ---- - -**Najlepsi Oceniający** 🕵️ przejrzeli więcej Pull Requestów, niż inni, zapewniając jakość kodu, dokumentacji, a zwłaszcza **tłumaczeń**. - -{% if people %} -
-{% for user in people.top_reviewers %} - -
@{{ user.login }}
Liczba ocen: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Sponsorzy - -Oto **Sponsorzy**. 😎 - -Wspierają moją pracę nad **FastAPI** (i innymi), głównie poprzez GitHub Sponsors. - -{% if sponsors %} - -{% if sponsors.gold %} - -### Złoci Sponsorzy - -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### Srebrni Sponsorzy - -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### Brązowi Sponsorzy - -{% for sponsor in sponsors.bronze -%} - -{% endfor %} -{% endif %} - -{% endif %} - -### Indywidualni Sponsorzy - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -
- -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - - - -{% endif %} -{% endfor %} - -
- -{% endfor %} -{% endif %} - -## Techniczne szczegóły danych - -Głównym celem tej strony jest podkreślenie wysiłku społeczności w pomaganiu innym. - -Szczególnie włączając wysiłki, które są zwykle mniej widoczne, a w wielu przypadkach bardziej żmudne, tak jak pomaganie innym z pytaniami i ocenianie Pull Requestów z tłumaczeniami. - -Dane są obliczane każdego miesiąca, możesz przeczytać kod źródłowy tutaj. - -Tutaj również podkreślam wkład od sponsorów. - -Zastrzegam sobie prawo do aktualizacji algorytmu, sekcji, progów itp. (na wszelki wypadek 🤷). diff --git a/docs/pt/docs/fastapi-people.md b/docs/pt/docs/fastapi-people.md deleted file mode 100644 index d67ae0d33..000000000 --- a/docs/pt/docs/fastapi-people.md +++ /dev/null @@ -1,183 +0,0 @@ ---- -hide: - - navigation ---- - -# Pessoas do FastAPI - -FastAPI possue uma comunidade incrível que recebe pessoas de todos os níveis. - -## Criador - Mantenedor - -Ei! 👋 - -Este sou eu: - -{% if people %} -
-{% for user in people.maintainers %} - -
@{{ user.login }}
Respostas: {{ user.answers }}
Pull Requests: {{ user.prs }}
-{% endfor %} - -
-{% endif %} - -Eu sou o criador e mantenedor do **FastAPI**. Você pode ler mais sobre isso em [Help FastAPI - Get Help - Connect with the author](help-fastapi.md#conect-se-com-o-autor){.internal-link target=_blank}. - -...Mas aqui eu quero mostrar a você a comunidade. - ---- - -**FastAPI** recebe muito suporte da comunidade. E quero destacar suas contribuições. - -Estas são as pessoas que: - -* [Help others with issues (questions) in GitHub](help-fastapi.md#responda-perguntas-no-github){.internal-link target=_blank}. -* [Create Pull Requests](help-fastapi.md#crie-um-pull-request){.internal-link target=_blank}. -* Revisar Pull Requests, [especially important for translations](contributing.md#traducoes){.internal-link target=_blank}. - -Uma salva de palmas para eles. 👏 🙇 - -## Usuários mais ativos do ultimo mês - -Estes são os usuários que estão [helping others the most with issues (questions) in GitHub](help-fastapi.md#responda-perguntas-no-github){.internal-link target=_blank} durante o ultimo mês. ☕ - -{% if people %} -
-{% for user in people.last_month_experts[:10] %} - -
@{{ user.login }}
Issues respondidas: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Especialistas - -Aqui está os **Especialistas do FastAPI**. 🤓 - - -Estes são os usuários que [helped others the most with issues (questions) in GitHub](help-fastapi.md#responda-perguntas-no-github){.internal-link target=_blank} em *todo o tempo*. - -Eles provaram ser especialistas ajudando muitos outros. ✨ - -{% if people %} -
-{% for user in people.experts[:50] %} - -
@{{ user.login }}
Issues respondidas: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Top Contribuidores - -Aqui está os **Top Contribuidores**. 👷 - -Esses usuários têm [created the most Pull Requests](help-fastapi.md#crie-um-pull-request){.internal-link target=_blank} que tem sido *mergeado*. - -Eles contribuíram com o código-fonte, documentação, traduções, etc. 📦 - -{% if people %} -
-{% for user in people.top_contributors[:50] %} - -
@{{ user.login }}
Pull Requests: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -Existem muitos outros contribuidores (mais de uma centena), você pode ver todos eles em Página de Contribuidores do FastAPI no GitHub. 👷 - -## Top Revisores - -Esses usuários são os **Top Revisores**. 🕵️ - -### Revisões para Traduções - -Eu só falo algumas línguas (e não muito bem 😅). Então, os revisores são aqueles que têm o [**poder de aprovar traduções**](contributing.md#traducoes){.internal-link target=_blank} da documentação. Sem eles, não haveria documentação em vários outros idiomas. - ---- - -Os **Top Revisores** 🕵️ revisaram a maior parte de Pull Requests de outros, garantindo a qualidade do código, documentação, e especialmente, as **traduções**. - -{% if people %} -
-{% for user in people.top_translations_reviewers[:50] %} - -
@{{ user.login }}
Revisões: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Patrocinadores - -Esses são os **Patrocinadores**. 😎 - -Eles estão apoiando meu trabalho **FastAPI** (e outros), principalmente através de GitHub Sponsors. - -{% if sponsors %} -{% if sponsors.gold %} - -### Patrocinadores Ouro - -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### Patrocinadores Prata - -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### Patrocinadores Bronze - -{% for sponsor in sponsors.bronze -%} - -{% endfor %} -{% endif %} - -### Patrocinadores Individuais - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -
- -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - - - -{% endif %} -{% endfor %} - -
- -{% endfor %} -{% endif %} - -{% endif %} - -## Sobre os dados - detalhes técnicos - -A principal intenção desta página é destacar o esforço da comunidade para ajudar os outros. - -Especialmente incluindo esforços que normalmente são menos visíveis, e em muitos casos mais árduo, como ajudar os outros com issues e revisando Pull Requests com traduções. - -Os dados são calculados todo mês, você pode ler o código fonte aqui. - -Aqui também estou destacando contribuições de patrocinadores. - -Eu também me reservo o direito de atualizar o algoritmo, seções, limites, etc (só para prevenir 🤷). diff --git a/docs/ru/docs/fastapi-people.md b/docs/ru/docs/fastapi-people.md deleted file mode 100644 index 31bb2798e..000000000 --- a/docs/ru/docs/fastapi-people.md +++ /dev/null @@ -1,184 +0,0 @@ ---- -hide: - - navigation ---- - -# Люди, поддерживающие FastAPI - -У FastAPI замечательное сообщество, которое доброжелательно к людям с любым уровнем знаний. - -## Создатель и хранитель - -Хай! 👋 - -Это я: - -{% if people %} -
-{% for user in people.maintainers %} - -
@{{ user.login }}
Answers: {{ user.answers }}
Pull Requests: {{ user.prs }}
-{% endfor %} - -
-{% endif %} - -Я создал и продолжаю поддерживать **FastAPI**. Узнать обо мне больше можно тут [Помочь FastAPI - Получить помощь - Связаться с автором](help-fastapi.md#_2){.internal-link target=_blank}. - -... но на этой странице я хочу показать вам наше сообщество. - ---- - -**FastAPI** получает огромную поддержку от своего сообщества. И я хочу отметить вклад его участников. - -Это люди, которые: - -* [Помогают другим с их проблемами (вопросами) на GitHub](help-fastapi.md#github_1){.internal-link target=_blank}. -* [Создают пул-реквесты](help-fastapi.md#-_1){.internal-link target=_blank}. -* Делают ревью пул-реквестов, [что особенно важно для переводов на другие языки](contributing.md#_8){.internal-link target=_blank}. - -Поаплодируем им! 👏 🙇 - -## Самые активные участники за прошедший месяц - -Эти участники [оказали наибольшую помощь другим с решением их проблем (вопросов) на GitHub](help-fastapi.md#github_1){.internal-link target=_blank} в течение последнего месяца. ☕ - -{% if people %} -
-{% for user in people.last_month_experts[:10] %} - -
@{{ user.login }}
Issues replied: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Эксперты - -Здесь представлены **Эксперты FastAPI**. 🤓 - -Эти участники [оказали наибольшую помощь другим с решением их проблем (вопросов) на GitHub](help-fastapi.md#github_1){.internal-link target=_blank} за *всё время*. - -Оказывая помощь многим другим, они подтвердили свой уровень знаний. ✨ - -{% if people %} -
-{% for user in people.experts[:50] %} - -
@{{ user.login }}
Issues replied: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Рейтинг участников, внёсших вклад в код - -Здесь представлен **Рейтинг участников, внёсших вклад в код**. 👷 - -Эти люди [сделали наибольшее количество пул-реквестов](help-fastapi.md#-_1){.internal-link target=_blank}, *включённых в основной код*. - -Они сделали наибольший вклад в исходный код, документацию, переводы и т.п. 📦 - -{% if people %} -
-{% for user in people.top_contributors[:50] %} - -
@{{ user.login }}
Pull Requests: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -На самом деле таких людей довольно много (более сотни), вы можете увидеть всех на этой странице FastAPI GitHub Contributors page. 👷 - -## Рейтинг ревьюеров - -Здесь представлен **Рейтинг ревьюеров**. 🕵️ - -### Проверки переводов на другие языки - -Я знаю не очень много языков (и не очень хорошо 😅). -Итак, ревьюеры - это люди, которые могут [**подтвердить предложенный вами перевод** документации](contributing.md#_8){.internal-link target=_blank}. Без них не было бы документации на многих языках. - ---- - -В **Рейтинге ревьюеров** 🕵️ представлены те, кто проверил наибольшее количество пул-реквестов других участников, обеспечивая качество кода, документации и, особенно, **переводов на другие языки**. - -{% if people %} -
-{% for user in people.top_translations_reviewers[:50] %} - -
@{{ user.login }}
Reviews: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Спонсоры - -Здесь представлены **Спонсоры**. 😎 - -Спонсоры поддерживают мою работу над **FastAPI** (и другими проектами) главным образом через GitHub Sponsors. - -{% if sponsors %} - -{% if sponsors.gold %} - -### Золотые спонсоры - -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### Серебрянные спонсоры - -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### Бронзовые спонсоры - -{% for sponsor in sponsors.bronze -%} - -{% endfor %} -{% endif %} - -{% endif %} - -### Индивидуальные спонсоры - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -
- -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - - - -{% endif %} -{% endfor %} - -
- -{% endfor %} -{% endif %} - -## О данных - технические детали - -Основная цель этой страницы - подчеркнуть усилия сообщества по оказанию помощи другим. - -Особенно это касается усилий, которые обычно менее заметны и во многих случаях более трудоемки, таких как помощь другим в решении проблем и проверка пул-реквестов с переводами. - -Данные рейтинги подсчитываются каждый месяц, ознакомиться с тем, как это работает можно тут. - -Кроме того, я также подчеркиваю вклад спонсоров. - -И я оставляю за собой право обновлять алгоритмы подсчёта, виды рейтингов, пороговые значения и т.д. (так, на всякий случай 🤷). diff --git a/docs/tr/docs/fastapi-people.md b/docs/tr/docs/fastapi-people.md deleted file mode 100644 index de62c57c4..000000000 --- a/docs/tr/docs/fastapi-people.md +++ /dev/null @@ -1,183 +0,0 @@ ---- -hide: - - navigation ---- - -# FastAPI Topluluğu - -FastAPI, her kökenden insanı ağırlayan harika bir topluluğa sahip. - -## Yazan - Geliştiren - -Merhaba! 👋 - -İşte bu benim: - -{% if people %} -
-{% for user in people.maintainers %} - -
@{{ user.login }}
Cevaplar: {{ user.answers }}
Pull Request'ler: {{ user.prs }}
-{% endfor %} - -
-{% endif %} - -Ben **FastAPI**'ın geliştiricisiyim. Bununla ilgili daha fazla bilgiyi şurada okuyabilirsiniz: [FastAPI yardım - yardım al - benimle iletişime geç](help-fastapi.md#connect-with-the-author){.internal-link target=_blank}. - -...burada size harika FastAPI topluluğunu göstermek istiyorum. - ---- - -**FastAPI**, topluluğundan çok destek alıyor. Ben de onların katkılarını vurgulamak istiyorum. - -Bu insanlar: - -* [GitHubdaki soruları cevaplayarak diğerlerine yardım ediyor](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. -* [Pull Request'ler oluşturuyor](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. -* Pull Request'leri gözden geçiriyorlar, [özellikle çeviriler için bu çok önemli](contributing.md#translations){.internal-link target=_blank}. - -Onları bir alkışlayalım. 👏 🙇 - -## Geçen Ayın En Aktif Kullanıcıları - -Geçtiğimiz ay boyunca [GitHub'da diğerlerine en çok yardımcı olan](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} kullanıcılar. ☕ - -{% if people %} -
-{% for user in people.last_month_experts[:10] %} - -
@{{ user.login }}
Cevaplanan soru sayısı: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Uzmanlar - -İşte **FastAPI Uzmanları**. 🤓 - -Uzmanlarımız ise *tüm zamanlar boyunca* [GitHub'da insanların sorularına en çok yardımcı olan](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} insanlar. - -Bir çok kullanıcıya yardım ederek uzman olduklarını kanıtladılar! ✨ - -{% if people %} -
-{% for user in people.experts[:50] %} - -
@{{ user.login }}
Cevaplanan soru sayısı: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## En Fazla Katkıda Bulunanlar - -Şimdi ise sıra **en fazla katkıda bulunanlar**da. 👷 - -Bu kullanıcılar en fazla [kaynak koduyla birleştirilen Pull Request'lere](help-fastapi.md#create-a-pull-request){.internal-link target=_blank} sahip! - -Kaynak koduna, dökümantasyona, çevirilere ve bir sürü şeye katkıda bulundular. 📦 - -{% if people %} -
-{% for user in people.top_contributors[:50] %} - -
@{{ user.login }}
Pull Request sayısı: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -Bunlar dışında katkıda bulunan, yüzden fazla, bir sürü insan var. Hepsini FastAPI GitHub Katkıda Bulunanlar sayfasında görebilirsin. 👷 - -## En Fazla Değerlendirme Yapanlar - -İşte **en çok değerlendirme yapanlar**. 🕵️ - -### Çeviri Değerlendirmeleri - -Yalnızca birkaç dil konuşabiliyorum (ve çok da iyi değilim 😅). Bu yüzden değerlendirme yapanların da döküman çevirilerini [**onaylama yetkisi**](contributing.md#translations){.internal-link target=_blank} var. Onlar olmasaydı çeşitli dillerde dökümantasyon da olmazdı. - ---- - -**En fazla değerlendirme yapanlar** 🕵️ kodun, dökümantasyonun ve özellikle **çevirilerin** Pull Request'lerini inceleyerek kalitesinden emin oldular. - -{% if people %} -
-{% for user in people.top_translations_reviewers[:50] %} - -
@{{ user.login }}
Değerlendirme sayısı: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Sponsorlar - -işte **Sponsorlarımız**. 😎 - -Çoğunlukla GitHub Sponsorları aracılığıyla olmak üzere, **FastAPI** ve diğer projelerdeki çalışmalarımı destekliyorlar. - -{% if sponsors %} - -{% if sponsors.gold %} - -### Altın Sponsorlar - -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### Gümüş Sponsorlar - -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### Bronz Sponsorlar - -{% for sponsor in sponsors.bronze -%} - -{% endfor %} -{% endif %} - -{% endif %} - -### Bireysel Sponsorlar - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -
- -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - - - -{% endif %} -{% endfor %} - -
- -{% endfor %} -{% endif %} - -## Veriler - Teknik detaylar - -Bu sayfanın temel amacı, topluluğun başkalarına yardım etme çabasını vurgulamaktır. - -Özellikle normalde daha az görünür olan ve çoğu durumda daha zahmetli olan, diğerlerine sorularında yardımcı olmak, çevirileri ve Pull Request'leri gözden geçirmek gibi çabalar dahil. - -Veriler ayda bir hesaplanır, kaynak kodu buradan okuyabilirsin. - -Burada sponsorların katkılarını da vurguluyorum. - -Ayrıca algoritmayı, bölümleri, eşikleri vb. güncelleme hakkımı da saklı tutuyorum (her ihtimale karşı 🤷). diff --git a/docs/uk/docs/fastapi-people.md b/docs/uk/docs/fastapi-people.md deleted file mode 100644 index c6a6451d8..000000000 --- a/docs/uk/docs/fastapi-people.md +++ /dev/null @@ -1,183 +0,0 @@ ---- -hide: - - navigation ---- - -# Люди FastAPI - -FastAPI має дивовижну спільноту, яка вітає людей різного походження. - -## Творець – Супроводжувач - -Привіт! 👋 - -Це я: - -{% if people %} -
-{% for user in people.maintainers %} - -
@{{ user.login }}
Answers: {{ user.answers }}
Pull Requests: {{ user.prs }}
-{% endfor %} - -
-{% endif %} - -Я - творець і супроводжувач **FastAPI**. Детальніше про це можна прочитати в [Довідка FastAPI - Отримати довідку - Зв'язатися з автором](help-fastapi.md#connect-with-the-author){.internal-link target=_blank}. - -...Але тут я хочу показати вам спільноту. - ---- - -**FastAPI** отримує велику підтримку від спільноти. І я хочу відзначити їхній внесок. - -Це люди, які: - -* [Допомагають іншим із проблемами (запитаннями) у GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}. -* [Створюють пул реквести](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}. -* Переглядають пул реквести, [особливо важливо для перекладів](contributing.md#translations){.internal-link target=_blank}. - -Оплески їм. 👏 🙇 - -## Найбільш активні користувачі минулого місяця - -Це користувачі, які [найбільше допомагали іншим із проблемами (запитаннями) у GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} протягом минулого місяця. ☕ - -{% if people %} -
-{% for user in people.last_month_experts[:10] %} - -
@{{ user.login }}
Issues replied: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Експерти - -Ось **експерти FastAPI**. 🤓 - -Це користувачі, які [найбільше допомагали іншим із проблемами (запитаннями) у GitHub](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank} протягом *всього часу*. - -Вони зарекомендували себе як експерти, допомагаючи багатьом іншим. ✨ - -{% if people %} -
-{% for user in people.experts[:50] %} - -
@{{ user.login }}
Issues replied: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Найкращі контрибютори - -Ось **Найкращі контрибютори**. 👷 - -Ці користувачі [створили найбільшу кількість пул реквестів](help-fastapi.md#create-a-pull-request){.internal-link target=_blank} які були *змержені*. - -Вони надали програмний код, документацію, переклади тощо. 📦 - -{% if people %} -
-{% for user in people.top_contributors[:50] %} - -
@{{ user.login }}
Pull Requests: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -Є багато інших контрибюторів (більше сотні), їх усіх можна побачити на сторінці FastAPI GitHub Contributors. 👷 - -## Найкращі рецензенти - -Ці користувачі є **Найкращими рецензентами**. 🕵️ - -### Рецензенти на переклади - -Я розмовляю лише кількома мовами (і не дуже добре 😅). Отже, рецензенти – це ті, хто має [**повноваження схвалювати переклади**](contributing.md#translations){.internal-link target=_blank} документації. Без них не було б документації кількома іншими мовами. - ---- - -**Найкращі рецензенти** 🕵️ переглянули більшість пул реквестів від інших, забезпечуючи якість коду, документації і особливо **перекладів**. - -{% if people %} -
-{% for user in people.top_translations_reviewers[:50] %} - -
@{{ user.login }}
Reviews: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## Спонсори - -Це **Спонсори**. 😎 - -Вони підтримують мою роботу з **FastAPI** (та іншими), переважно через GitHub Sponsors. - -{% if sponsors %} - -{% if sponsors.gold %} - -### Золоті спонсори - -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### Срібні спонсори - -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### Бронзові спонсори - -{% for sponsor in sponsors.bronze -%} - -{% endfor %} -{% endif %} - -{% endif %} - -### Індивідуальні спонсори - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -
- -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - - - -{% endif %} -{% endfor %} - -
- -{% endfor %} -{% endif %} - -## Про дані - технічні деталі - -Основна мета цієї сторінки – висвітлити зусилля спільноти, щоб допомогти іншим. - -Особливо враховуючи зусилля, які зазвичай менш помітні, а в багатьох випадках більш важкі, як-от допомога іншим із проблемами та перегляд пул реквестів перекладів. - -Дані розраховуються щомісяця, ви можете ознайомитися з вихідним кодом тут. - -Тут я також підкреслюю внески спонсорів. - -Я також залишаю за собою право оновлювати алгоритми підрахунку, види рейтингів, порогові значення тощо (про всяк випадок 🤷). diff --git a/docs/zh-hant/docs/fastapi-people.md b/docs/zh-hant/docs/fastapi-people.md deleted file mode 100644 index 99277b419..000000000 --- a/docs/zh-hant/docs/fastapi-people.md +++ /dev/null @@ -1,239 +0,0 @@ ---- -hide: - - navigation ---- - -# FastAPI 社群 - -FastAPI 有一個非常棒的社群,歡迎來自不同背景的朋友參與。 - -## 作者 - -嘿! 👋 - -關於我: - -{% if people %} -
-{% for user in people.maintainers %} - -
@{{ user.login }}
解答問題: {{ user.answers }}
Pull Requests: {{ user.prs }}
-{% endfor %} - -
-{% endif %} - -我是 **FastAPI** 的作者。你可以在[幫助 FastAPI - 獲得幫助 - 與作者聯繫](help-fastapi.md#connect-with-the-author){.internal-link target=_blank} 中閱讀更多相關資訊。 - -...但在這裡,我想向你介紹這個社群。 - ---- - -**FastAPI** 獲得了許多社群的大力支持。我想特別表揚他們的貢獻。 - -這些人包括: - -* [在 GitHub 中幫助他人解答問題](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}。 -* [建立 Pull Requests](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}。 -* 審查 Pull Requests,[尤其是翻譯方面的貢獻](contributing.md#translations){.internal-link target=_blank}。 - -讓我們為他們熱烈鼓掌。 👏 🙇 - -## FastAPI 專家 - -這些是在 [GitHub 中幫助其他人解決問題最多的用戶](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}。 🙇 - -他們透過幫助其他人,證明了自己是 **FastAPI 專家**。 ✨ - -/// 提示 - -你也可以成為官方的 FastAPI 專家! - -只需要在 [GitHub 中幫助他人解答問題](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}。 🤓 - -/// - -你可以查看這些期間的 **FastAPI 專家**: - -* [上個月](#fastapi-experts-last-month) 🤓 -* [過去 3 個月](#fastapi-experts-3-months) 😎 -* [過去 6 個月](#fastapi-experts-6-months) 🧐 -* [過去 1 年](#fastapi-experts-1-year) 🧑‍🔬 -* [**所有時間**](#fastapi-experts-all-time) 🧙 - -### FastAPI 專家 - 上個月 - -上個月在 [GitHub 中幫助他人解決問題最多的](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}用戶。 🤓 - -{% if people %} -
-{% for user in people.last_month_experts[:10] %} - -
@{{ user.login }}
回答問題數: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -### FastAPI 專家 - 過去 3 個月 - -過去三個月在 [GitHub 中幫助他人解決問題最多的](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}用戶。 😎 - -{% if people %} -
-{% for user in people.three_months_experts[:10] %} - -
@{{ user.login }}
回答問題數: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -### FastAPI 專家 - 過去 6 個月 - -過去六個月在 [GitHub 中幫助他人解決問題最多的](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}用戶。 🧐 - -{% if people %} -
-{% for user in people.six_months_experts[:10] %} - -
@{{ user.login }}
回答問題數: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -### FastAPI 專家 - 過去一年 - -過去一年在 [GitHub 中幫助他人解決最多問題的](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}用戶。 🧑‍🔬 - -{% if people %} -
-{% for user in people.one_year_experts[:20] %} - -
@{{ user.login }}
回答問題數: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -### FastAPI 專家 - 全部時間 - -以下是全部時間的 **FastAPI 專家**。 🤓🤯 - -過去在 [GitHub 中幫助他人解決問題最多的](help-fastapi.md#help-others-with-questions-in-github){.internal-link target=_blank}用戶。 🧙 - -{% if people %} -
-{% for user in people.experts[:50] %} - -
@{{ user.login }}
回答問題數: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## 主要貢獻者 - -以下是**主要貢獻者**。 👷 - -這些用戶[建立了最多已被**合併**的 Pull Requests](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}。 - -他們貢獻了原始碼、文件和翻譯等。 📦 - -{% if people %} -
-{% for user in people.top_contributors[:50] %} - -
@{{ user.login }}
Pull Requests: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -還有許多其他的貢獻者(超過一百位),你可以在 FastAPI GitHub 貢獻者頁面查看。 👷 - -## 主要翻譯審核者 - -以下是 **主要翻譯審核者**。 🕵️ - -我只會講幾種語言(而且不是很流利 😅),所以審核者[**擁有批准翻譯**](contributing.md#translations){.internal-link target=_blank}文件的權限。沒有他們,就不會有多語言版本的文件。 - -{% if people %} -
-{% for user in people.top_translations_reviewers[:50] %} - -
@{{ user.login }}
Reviews: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## 贊助者 - -以下是**贊助者**。 😎 - -他們主要透過 GitHub Sponsors 支持我在 **FastAPI**(以及其他項目)上的工作。 - -{% if sponsors %} - -{% if sponsors.gold %} - -### 金牌贊助商 - -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### 銀牌贊助商 - -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### 銅牌贊助商 - -{% for sponsor in sponsors.bronze -%} - -{% endfor %} -{% endif %} - -{% endif %} - -### 個人贊助商 - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -
- -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - - - -{% endif %} -{% endfor %} - -
- -{% endfor %} -{% endif %} - -## 關於數據 - 技術細節 - -這個頁面的主要目的是突顯社群幫助他人所做的努力 - -特別是那些通常不太顯眼但往往更加艱辛的工作,例如幫助他人解答問題和審查包含翻譯的 Pull Requests。 - -這些數據每月計算一次,你可以在這查看原始碼。 - -此外,我也特別表揚贊助者的貢獻。 - -我也保留更新演算法、章節、門檻值等的權利(以防萬一 🤷)。 diff --git a/docs/zh/docs/fastapi-people.md b/docs/zh/docs/fastapi-people.md deleted file mode 100644 index 30a75240c..000000000 --- a/docs/zh/docs/fastapi-people.md +++ /dev/null @@ -1,239 +0,0 @@ ---- -hide: - - navigation ---- - -# FastAPI 社区 - -FastAPI 有一个非常棒的社区,它欢迎来自各个领域和背景的朋友。 - -## 创建者 & 维护者 - -嘿! 👋 - -这就是我: - -{% if people %} -
-{% for user in people.maintainers %} - -
@{{ user.login }}
Answers: {{ user.answers }}
Pull Requests: {{ user.prs }}
-{% endfor %} - -
-{% endif %} - -我是 **FastAPI** 的创建者和维护者. 你能在 [帮助 FastAPI - 获取帮助 - 与作者联系](help-fastapi.md#_2){.internal-link target=_blank} 阅读有关此内容的更多信息。 - -...但是在这里我想向您展示社区。 - ---- - -**FastAPI** 得到了社区的大力支持。因此我想突出他们的贡献。 - -这些人: - -* [帮助他人解决 GitHub 上的问题](help-fastapi.md#github_1){.internal-link target=_blank}。 -* [创建 Pull Requests](help-fastapi.md#pr){.internal-link target=_blank}。 -* 审核 Pull Requests, 对于 [翻译](contributing.md#_8){.internal-link target=_blank} 尤为重要。 - -向他们致以掌声。 👏 🙇 - -## FastAPI 专家 - -这些用户一直以来致力于 [帮助他人解决 GitHub 上的问题](help-fastapi.md#github_1){.internal-link target=_blank}。 🙇 - -他们通过帮助许多人而被证明是 **FastAPI 专家**。 ✨ - -/// 小提示 - -你也可以成为认可的 FastAPI 专家! - -只需要 [帮助他人解决 GitHub 上的问题](help-fastapi.md#github_1){.internal-link target=_blank}。 🤓 - -/// - -你可以查看不同时期的 **FastAPI 专家**: - -* [上个月](#fastapi-experts-last-month) 🤓 -* [三个月](#fastapi-experts-3-months) 😎 -* [六个月](#fastapi-experts-6-months) 🧐 -* [一年](#fastapi-experts-1-year) 🧑‍🔬 -* [**全部时间**](#fastapi-experts-all-time) 🧙 - -## FastAPI 专家 - 上个月 - -这些是在过去一个月中 [在 GitHub 上帮助他人解答最多问题](help-fastapi.md#github_1){.internal-link target=_blank} 的用户。 🤓 - -{% if people %} -
-{% for user in people.last_month_experts[:10] %} - -
@{{ user.login }}
回答问题数: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -### FastAPI 专家 - 三个月 - -这些是在过去三个月中 [在 GitHub 上帮助他人解答最多问题](help-fastapi.md#github_1){.internal-link target=_blank} 的用户。 😎 - -{% if people %} -
-{% for user in people.three_months_experts[:10] %} - -
@{{ user.login }}
回答问题数: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -### FastAPI 专家 - 六个月 - -这些是在过去六个月中 [在 GitHub 上帮助他人解答最多问题](help-fastapi.md#github_1){.internal-link target=_blank} 的用户。 🧐 - -{% if people %} -
-{% for user in people.six_months_experts[:10] %} - -
@{{ user.login }}
回答问题数: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -### FastAPI 专家 - 一年 - -这些是在过去一年中 [在 GitHub 上帮助他人解答最多问题](help-fastapi.md#github_1){.internal-link target=_blank} 的用户。 🧑‍🔬 - -{% if people %} -
-{% for user in people.one_year_experts[:20] %} - -
@{{ user.login }}
回答问题数: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## FastAPI 专家 - 全部时间 - -以下是全部时间的 **FastAPI 专家**。 🤓🤯 - -这些用户一直以来致力于 [帮助他人解决 GitHub 的 上的问题](help-fastapi.md#github_1){.internal-link target=_blank}。 🧙 - -{% if people %} -
-{% for user in people.experts[:50] %} - -
@{{ user.login }}
回答问题数: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## 杰出贡献者 - -以下是 **杰出的贡献者**。 👷 - -这些用户 [创建了最多已被合并的 Pull Requests](help-fastapi.md#pr){.internal-link target=_blank}。 - -他们贡献了源代码,文档,翻译等。 📦 - -{% if people %} -
-{% for user in people.top_contributors[:50] %} - -
@{{ user.login }}
Pull Requests: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -还有很多别的贡献者(超过100个),你可以在 FastAPI GitHub 贡献者页面 中看到他们。👷 - -## 杰出翻译审核者 - -以下用户是 **杰出的评审者**。 🕵️ - -我只会说少数几种语言(而且还不是很流利 😅)。所以这些评审者们具备[能力去批准文档翻译](contributing.md#_8){.internal-link target=_blank}。如果没有他们,就不会有多语言文档。 - -{% if people %} -
-{% for user in people.top_translations_reviewers[:50] %} - -
@{{ user.login }}
审核数: {{ user.count }}
-{% endfor %} - -
-{% endif %} - -## 赞助商 - -以下是 **赞助商** 。😎 - -他们主要通过GitHub Sponsors支持我在 **FastAPI** (和其他项目)的工作。 - -{% if sponsors %} - -{% if sponsors.gold %} - -### 金牌赞助商 - -{% for sponsor in sponsors.gold -%} - -{% endfor %} -{% endif %} - -{% if sponsors.silver %} - -### 银牌赞助商 - -{% for sponsor in sponsors.silver -%} - -{% endfor %} -{% endif %} - -{% if sponsors.bronze %} - -### 铜牌赞助商 - -{% for sponsor in sponsors.bronze -%} - -{% endfor %} -{% endif %} - -{% endif %} - -### 个人赞助 - -{% if github_sponsors %} -{% for group in github_sponsors.sponsors %} - -
- -{% for user in group %} -{% if user.login not in sponsors_badge.logins %} - - - -{% endif %} -{% endfor %} - -
- -{% endfor %} -{% endif %} - -## 关于数据 - 技术细节 - -该页面的目的是突出社区为帮助他人而付出的努力。 - -尤其是那些不引人注目且涉及更困难的任务,例如帮助他人解决问题或者评审翻译 Pull Requests。 - -该数据每月计算一次,您可以阅读 源代码。 - -这里也强调了赞助商的贡献。 - -我也保留更新算法,栏目,统计阈值等的权利(以防万一🤷)。 diff --git a/scripts/docs.py b/scripts/docs.py index 1dba4aa0a..f0c51f7a6 100644 --- a/scripts/docs.py +++ b/scripts/docs.py @@ -29,6 +29,7 @@ missing_translation_snippet = """ non_translated_sections = [ "reference/", "release-notes.md", + "fastapi-people.md", "external-links.md", "newsletter.md", "management-tasks.md", diff --git a/scripts/mkdocs_hooks.py b/scripts/mkdocs_hooks.py index 10e8dc153..0bc4929a4 100644 --- a/scripts/mkdocs_hooks.py +++ b/scripts/mkdocs_hooks.py @@ -11,6 +11,7 @@ from mkdocs.structure.pages import Page non_translated_sections = [ "reference/", "release-notes.md", + "fastapi-people.md", "external-links.md", "newsletter.md", "management-tasks.md", From 0da0814d8a2029b7d2e19043a606c7faea6b02fa Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 17 Aug 2024 21:20:52 +0000 Subject: [PATCH 03/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 17a24a984..91bbb2adc 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -29,6 +29,7 @@ hide: ### Translations +* 📝 Update FastAPI People, do not translate to have the most recent info. PR [#12034](https://github.com/fastapi/fastapi/pull/12034) by [@tiangolo](https://github.com/tiangolo). * 🌐 Update Urdu translation for `docs/ur/docs/benchmarks.md`. PR [#10046](https://github.com/fastapi/fastapi/pull/10046) by [@AhsanSheraz](https://github.com/AhsanSheraz). ### Internal From 4f1eb0cd9e571a68fab19eecbdc59cc27aa7e6f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sun, 18 Aug 2024 16:07:03 -0500 Subject: [PATCH 04/88] =?UTF-8?q?=F0=9F=94=A7=20Update=20coverage=20config?= =?UTF-8?q?=20files=20(#12035)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/test.yml | 2 +- pyproject.toml | 8 ++++++++ scripts/test-cov-html.sh | 4 ++-- 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index a33b6a68a..0458f83ff 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -117,7 +117,7 @@ jobs: - run: ls -la coverage - run: coverage combine coverage - run: coverage report - - run: coverage html --show-contexts --title "Coverage for ${{ github.sha }}" + - run: coverage html --title "Coverage for ${{ github.sha }}" - name: Store coverage HTML uses: actions/upload-artifact@v4 with: diff --git a/pyproject.toml b/pyproject.toml index 8db2d2b2d..bb87be470 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -165,6 +165,7 @@ filterwarnings = [ [tool.coverage.run] parallel = true +data_file = "coverage/.coverage" source = [ "docs_src", "tests", @@ -177,6 +178,13 @@ omit = [ "docs_src/response_model/tutorial003_04_py310.py", ] +[tool.coverage.report] +show_missing = true +sort = "-Cover" + +[tool.coverage.html] +show_contexts = true + [tool.ruff.lint] select = [ "E", # pycodestyle errors diff --git a/scripts/test-cov-html.sh b/scripts/test-cov-html.sh index 85aef9601..517ac6422 100755 --- a/scripts/test-cov-html.sh +++ b/scripts/test-cov-html.sh @@ -5,5 +5,5 @@ set -x bash scripts/test.sh ${@} coverage combine -coverage report --show-missing -coverage html --show-contexts +coverage report +coverage html From 6ebaf0efcb38efc6f06f302fe30142071cfd53e1 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 18 Aug 2024 21:08:39 +0000 Subject: [PATCH 05/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 91bbb2adc..cb3e8628e 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -34,6 +34,7 @@ hide: ### Internal +* 🔧 Update coverage config files. PR [#12035](https://github.com/fastapi/fastapi/pull/12035) by [@tiangolo](https://github.com/tiangolo). * 🔨 Standardize shebang across shell scripts. PR [#11942](https://github.com/fastapi/fastapi/pull/11942) by [@gitworkflows](https://github.com/gitworkflows). * ⬆ Update sqlalchemy requirement from <1.4.43,>=1.3.18 to >=1.3.18,<2.0.33. PR [#11979](https://github.com/fastapi/fastapi/pull/11979) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔊 Remove old ignore warnings. PR [#11950](https://github.com/fastapi/fastapi/pull/11950) by [@tiangolo](https://github.com/tiangolo). From 0e77481acfc5f548cd053ee36dbd2879651d73c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sun, 18 Aug 2024 18:16:56 -0500 Subject: [PATCH 06/88] =?UTF-8?q?=F0=9F=93=9D=20Move=20the=20Features=20do?= =?UTF-8?q?cs=20to=20the=20top=20level=20to=20improve=20the=20main=20page?= =?UTF-8?q?=20menu=20(#12036)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/mkdocs.yml | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index d23ddd42f..d0527ca3c 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -102,9 +102,8 @@ plugins: show_symbol_type_toc: true nav: -- FastAPI: - - index.md - - features.md +- FastAPI: index.md +- features.md - Learn: - learn/index.md - python-types.md From 98712b9e09429e0dd514d39c5064cde4f6ae657b Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 18 Aug 2024 23:17:21 +0000 Subject: [PATCH 07/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index cb3e8628e..bd8580271 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,7 @@ hide: ### Docs +* 📝 Move the Features docs to the top level to improve the main page menu. PR [#12036](https://github.com/fastapi/fastapi/pull/12036) by [@tiangolo](https://github.com/tiangolo). * ✏️ Fix import typo in reference example for `Security`. PR [#11168](https://github.com/fastapi/fastapi/pull/11168) by [@0shah0](https://github.com/0shah0). * 📝 Highlight correct line in tutorial `docs/en/docs/tutorial/body-multiple-params.md`. PR [#11978](https://github.com/fastapi/fastapi/pull/11978) by [@svlandeg](https://github.com/svlandeg). * 🔥 Remove Sentry link from Advanced Middleware docs. PR [#12031](https://github.com/fastapi/fastapi/pull/12031) by [@alejsdev](https://github.com/alejsdev). From bcd737de33dfb1c1871f86320b12c86158393b15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sun, 18 Aug 2024 18:26:14 -0500 Subject: [PATCH 08/88] =?UTF-8?q?=F0=9F=93=9D=20Add=20Asyncer=20mention=20?= =?UTF-8?q?in=20async=20docs=20(#12037)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/async.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/en/docs/async.md b/docs/en/docs/async.md index 43fd8e70d..7cf4af627 100644 --- a/docs/en/docs/async.md +++ b/docs/en/docs/async.md @@ -369,6 +369,8 @@ In particular, you can directly use AnyIO to be highly compatible and get its benefits (e.g. *structured concurrency*). +I created another library on top of AnyIO, as a thin layer on top, to improve a bit the type annotations and get better **autocompletion**, **inline errors**, etc. It also has a friendly introduction and tutorial to help you **understand** and write **your own async code**: Asyncer. It would be particularly useful if you need to **combine async code with regular** (blocking/synchronous) code. + ### Other forms of asynchronous code This style of using `async` and `await` is relatively new in the language. From ae97785ded0dfb5128cbd6bb9542eaf0fc44f903 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 18 Aug 2024 23:26:36 +0000 Subject: [PATCH 09/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index bd8580271..570e7e9db 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,7 @@ hide: ### Docs +* 📝 Add Asyncer mention in async docs. PR [#12037](https://github.com/fastapi/fastapi/pull/12037) by [@tiangolo](https://github.com/tiangolo). * 📝 Move the Features docs to the top level to improve the main page menu. PR [#12036](https://github.com/fastapi/fastapi/pull/12036) by [@tiangolo](https://github.com/tiangolo). * ✏️ Fix import typo in reference example for `Security`. PR [#11168](https://github.com/fastapi/fastapi/pull/11168) by [@0shah0](https://github.com/0shah0). * 📝 Highlight correct line in tutorial `docs/en/docs/tutorial/body-multiple-params.md`. PR [#11978](https://github.com/fastapi/fastapi/pull/11978) by [@svlandeg](https://github.com/svlandeg). From f0866bc2050552621566ca0c0fd111936ac36918 Mon Sep 17 00:00:00 2001 From: xuvjso Date: Tue, 20 Aug 2024 01:35:03 +0800 Subject: [PATCH 10/88] =?UTF-8?q?=F0=9F=8C=90=20Update=20docs=20about=20de?= =?UTF-8?q?pendencies=20with=20yield=20(#12028)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dependencies/dependencies-with-yield.md | 269 +++++++++++++----- 1 file changed, 197 insertions(+), 72 deletions(-) diff --git a/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md index beca95d45..6058f7878 100644 --- a/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md +++ b/docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md @@ -1,12 +1,12 @@ # 使用yield的依赖项 -FastAPI支持在完成后执行一些额外步骤的依赖项. +FastAPI支持在完成后执行一些额外步骤的依赖项. -为此,请使用 `yield` 而不是 `return`,然后再编写额外的步骤(代码)。 +为此,你需要使用 `yield` 而不是 `return`,然后再编写这些额外的步骤(代码)。 -/// tip | "提示" +/// tip | 提示 -确保只使用一次 `yield` 。 +确保在每个依赖中只使用一次 `yield`。 /// @@ -25,7 +25,7 @@ FastAPI支持在完成后执行一些> tasks: Send background tasks end opt Raise other exception - tasks -->> dep: Raise other exception - end - Note over dep: After yield - opt Handle other exception - dep -->> dep: Handle exception, can't change response. E.g. close DB session. + tasks -->> tasks: Handle exceptions in the background task code end ``` -/// info +/// info | 说明 -只会向客户端发送**一次响应**,可能是一个错误响应之一,也可能是来自*路径操作*的响应。 +只会向客户端发送 **一次响应** ,可能是一个错误响应,也可能是来自 *路由函数* 的响应。 在发送了其中一个响应之后,就无法再发送其他响应了。 /// -/// tip +/// tip | 提示 + +这个时序图展示了 `HTTPException`,除此之外你也可以抛出任何你在使用 `yield` 的依赖项中或者[自定义异常处理器](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}中捕获的异常。 + +如果你引发任何异常,它将传递给使用 `yield` 的依赖项,包括 `HTTPException`。在大多数情况下你应当从使用 `yield` 的依赖项中重新抛出捕获的异常或者一个新的异常来确保它会被正确的处理。 + +/// + +## 包含 `yield`, `HTTPException`, `except` 的依赖项和后台任务 + +/// warning | 注意 + +你大概率不需要了解这些技术细节,可以跳过这一章节继续阅读后续的内容。 + +如果你使用的FastAPI的版本早于0.106.0,并且在使用后台任务中使用了包含 `yield` 的依赖项中的资源,那么这些细节会对你有一些用处。 + +/// + +### 包含 `yield` 和 `except` 的依赖项的技术细节 + +在FastAPI 0.110.0版本之前,如果使用了一个包含 `yield` 的依赖项,你在依赖项中使用 `except` 捕获了一个异常,但是你没有再次抛出该异常,这个异常会被自动抛出/转发到异常处理器或者内部服务错误处理器。 + +### 后台任务和使用 `yield` 的依赖项的技术细节 + +在FastAPI 0.106.0版本之前,在 `yield` 后面抛出异常是不可行的,因为 `yield` 之后的退出代码是在响应被发送之后再执行,这个时候异常处理器已经执行过了。 -这个图表展示了`HTTPException`,但你也可以引发任何其他你创建了[自定义异常处理程序](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}的异常。 +这样设计的目的主要是为了允许在后台任务中使用被依赖项`yield`的对象,因为退出代码会在后台任务结束后再执行。 -如果你引发任何异常,它将传递给带有`yield`的依赖,包括`HTTPException`,然后**再次**传递给异常处理程序。如果没有针对该异常的异常处理程序,那么它将被默认的内部`ServerErrorMiddleware`处理,返回500 HTTP状态码,告知客户端服务器发生了错误。 +然而这也意味着在等待响应通过网络传输的同时,非必要的持有一个 `yield` 依赖项中的资源(例如数据库连接),这一行为在FastAPI 0.106.0被改变了。 + +/// tip | 提示 + +除此之外,后台任务通常是一组独立的逻辑,应该被单独处理,并且使用它自己的资源(例如它自己的数据库连接)。 + +这样也会让你的代码更加简洁。 /// +如果你之前依赖于这一行为,那么现在你应该在后台任务中创建并使用它自己的资源,不要在内部使用属于 `yield` 依赖项的资源。 + +例如,你应该在后台任务中创建一个新的数据库会话用于查询数据,而不是使用相同的会话。你应该将对象的ID作为参数传递给后台任务函数,然后在该函数中重新获取该对象,而不是直接将数据库对象作为参数。 + ## 上下文管理器 -### 什么是“上下文管理器” +### 什么是"上下文管理器" -“上下文管理器”是您可以在`with`语句中使用的任何Python对象。 +"上下文管理器"是你可以在 `with` 语句中使用的任何Python对象。 -例如,您可以使用`with`读取文件: +例如,你可以使用`with`读取文件: ```Python with open("./somefile.txt") as f: @@ -254,38 +379,38 @@ with open("./somefile.txt") as f: print(contents) ``` -在底层,`open("./somefile.txt")`创建了一个被称为“上下文管理器”的对象。 +在底层,`open("./somefile.txt")`创建了一个被称为"上下文管理器"的对象。 -当`with`块结束时,它会确保关闭文件,即使发生了异常也是如此。 +当 `with` 代码块结束时,它会确保关闭文件,即使发生了异常也是如此。 -当你使用`yield`创建一个依赖项时,**FastAPI**会在内部将其转换为上下文管理器,并与其他相关工具结合使用。 +当你使用 `yield` 创建一个依赖项时,**FastAPI** 会在内部将其转换为上下文管理器,并与其他相关工具结合使用。 -### 在依赖项中使用带有`yield`的上下文管理器 +### 在使用 `yield` 的依赖项中使用上下文管理器 -/// warning +/// warning | 注意 -这是一个更为“高级”的想法。 +这是一个更为"高级"的想法。 -如果您刚开始使用**FastAPI**,您可能暂时可以跳过它。 +如果你刚开始使用 **FastAPI** ,你可以暂时可以跳过它。 /// 在Python中,你可以通过创建一个带有`__enter__()`和`__exit__()`方法的类来创建上下文管理器。 -你也可以在**FastAPI**的依赖项中使用带有`yield`的`with`或`async with`语句,通过在依赖函数内部使用它们。 +你也可以在 **FastAPI** 的 `yield` 依赖项中通过 `with` 或者 `async with` 语句来使用它们: ```Python hl_lines="1-9 13" {!../../../docs_src/dependencies/tutorial010.py!} ``` -/// tip +/// tip | 提示 另一种创建上下文管理器的方法是: * `@contextlib.contextmanager`或者 * `@contextlib.asynccontextmanager` -使用上下文管理器装饰一个只有单个`yield`的函数。这就是**FastAPI**在内部用于带有`yield`的依赖项的方式。 +使用它们装饰一个只有单个 `yield` 的函数。这就是 **FastAPI** 内部对于 `yield` 依赖项的处理方式。 但是你不需要为FastAPI的依赖项使用这些装饰器(而且也不应该)。FastAPI会在内部为你处理这些。 From 63ae0f1070ba1df314b55e2454ec5e356725bd16 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 19 Aug 2024 17:35:25 +0000 Subject: [PATCH 11/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 570e7e9db..3b41fa2ad 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -31,6 +31,7 @@ hide: ### Translations +* 🌐 Update docs about dependencies with yield. PR [#12028](https://github.com/fastapi/fastapi/pull/12028) by [@xuvjso](https://github.com/xuvjso). * 📝 Update FastAPI People, do not translate to have the most recent info. PR [#12034](https://github.com/fastapi/fastapi/pull/12034) by [@tiangolo](https://github.com/tiangolo). * 🌐 Update Urdu translation for `docs/ur/docs/benchmarks.md`. PR [#10046](https://github.com/fastapi/fastapi/pull/10046) by [@AhsanSheraz](https://github.com/AhsanSheraz). From 6ba8407ff3acc0e2b8792c35a363803f08c78971 Mon Sep 17 00:00:00 2001 From: Alejandra <90076947+alejsdev@users.noreply.github.com> Date: Mon, 19 Aug 2024 13:15:21 -0500 Subject: [PATCH 12/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20Spanish=20transla?= =?UTF-8?q?tion=20docs=20for=20consistency=20(#12044)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/es/docs/advanced/additional-status-codes.md | 4 ++-- docs/es/docs/advanced/index.md | 2 +- .../path-operation-advanced-configuration.md | 4 ++-- docs/es/docs/advanced/response-directly.md | 4 ++-- docs/es/docs/advanced/response-headers.md | 2 +- docs/es/docs/advanced/security/index.md | 2 +- docs/es/docs/async.md | 8 ++++---- docs/es/docs/deployment/versions.md | 4 ++-- docs/es/docs/features.md | 2 +- docs/es/docs/how-to/graphql.md | 4 ++-- docs/es/docs/python-types.md | 6 +++--- docs/es/docs/tutorial/cookie-params.md | 16 ++++++++-------- docs/es/docs/tutorial/first-steps.md | 12 ++++++------ docs/es/docs/tutorial/path-params.md | 16 ++++++++-------- docs/es/docs/tutorial/query-params.md | 6 +++--- 15 files changed, 46 insertions(+), 46 deletions(-) diff --git a/docs/es/docs/advanced/additional-status-codes.md b/docs/es/docs/advanced/additional-status-codes.md index f40fad03c..664604c59 100644 --- a/docs/es/docs/advanced/additional-status-codes.md +++ b/docs/es/docs/advanced/additional-status-codes.md @@ -18,7 +18,7 @@ Para conseguir esto importa `JSONResponse` y devuelve ahí directamente tu conte {!../../../docs_src/additional_status_codes/tutorial001.py!} ``` -/// warning | "Advertencia" +/// warning | Advertencia Cuando devuelves directamente una `Response`, como en los ejemplos anteriores, será devuelta directamente. @@ -28,7 +28,7 @@ Asegúrate de que la respuesta tenga los datos que quieras, y que los valores se /// -/// note | "Detalles Técnicos" +/// note | Detalles Técnicos También podrías utilizar `from starlette.responses import JSONResponse`. diff --git a/docs/es/docs/advanced/index.md b/docs/es/docs/advanced/index.md index 88ef8e19f..10a1ff0d5 100644 --- a/docs/es/docs/advanced/index.md +++ b/docs/es/docs/advanced/index.md @@ -6,7 +6,7 @@ El [Tutorial - Guía de Usuario](../tutorial/index.md){.internal-link target=_bl En las secciones siguientes verás otras opciones, configuraciones, y características adicionales. -/// tip +/// tip | Consejo Las próximas secciones **no son necesariamente "avanzadas"**. diff --git a/docs/es/docs/advanced/path-operation-advanced-configuration.md b/docs/es/docs/advanced/path-operation-advanced-configuration.md index 9e8714fe4..18f96213f 100644 --- a/docs/es/docs/advanced/path-operation-advanced-configuration.md +++ b/docs/es/docs/advanced/path-operation-advanced-configuration.md @@ -26,13 +26,13 @@ Deberías hacerlo después de adicionar todas tus *operaciones de path*. {!../../../docs_src/path_operation_advanced_configuration/tutorial002.py!} ``` -/// tip | "Consejo" +/// tip | Consejo Si llamas manualmente a `app.openapi()`, debes actualizar el `operationId`s antes de hacerlo. /// -/// warning | "Advertencia" +/// warning | Advertencia Si haces esto, debes asegurarte de que cada una de tus *funciones de las operaciones de path* tenga un nombre único. diff --git a/docs/es/docs/advanced/response-directly.md b/docs/es/docs/advanced/response-directly.md index 7ce5bddca..4eeab3fd0 100644 --- a/docs/es/docs/advanced/response-directly.md +++ b/docs/es/docs/advanced/response-directly.md @@ -14,7 +14,7 @@ Esto puede ser útil, por ejemplo, para devolver cookies o headers personalizado De hecho, puedes devolver cualquier `Response` o cualquier subclase de la misma. -/// tip | "Consejo" +/// tip | Consejo `JSONResponse` en sí misma es una subclase de `Response`. @@ -38,7 +38,7 @@ Para esos casos, puedes usar el `jsonable_encoder` para convertir tus datos ante {!../../../docs_src/response_directly/tutorial001.py!} ``` -/// note | "Detalles Técnicos" +/// note | Detalles Técnicos También puedes usar `from starlette.responses import JSONResponse`. diff --git a/docs/es/docs/advanced/response-headers.md b/docs/es/docs/advanced/response-headers.md index 414b145fc..c3aa20993 100644 --- a/docs/es/docs/advanced/response-headers.md +++ b/docs/es/docs/advanced/response-headers.md @@ -29,7 +29,7 @@ Crea un response tal como se describe en [Retornar una respuesta directamente](r {!../../../docs_src/response_headers/tutorial001.py!} ``` -/// note | "Detalles Técnicos" +/// note | Detalles Técnicos También podrías utilizar `from starlette.responses import Response` o `from starlette.responses import JSONResponse`. diff --git a/docs/es/docs/advanced/security/index.md b/docs/es/docs/advanced/security/index.md index 7fa8047e9..92de67d6a 100644 --- a/docs/es/docs/advanced/security/index.md +++ b/docs/es/docs/advanced/security/index.md @@ -4,7 +4,7 @@ Hay algunas características adicionales para manejar la seguridad además de las que se tratan en el [Tutorial - Guía de Usuario: Seguridad](../../tutorial/security/index.md){.internal-link target=_blank}. -/// tip +/// tip | Consejo Las siguientes secciones **no necesariamente son "avanzadas"**. diff --git a/docs/es/docs/async.md b/docs/es/docs/async.md index 193d24270..5ab2ff9a4 100644 --- a/docs/es/docs/async.md +++ b/docs/es/docs/async.md @@ -21,7 +21,7 @@ async def read_results(): return results ``` -/// note | "Nota" +/// note | Nota Solo puedes usar `await` dentro de funciones creadas con `async def`. @@ -138,7 +138,7 @@ Tú y esa persona 😍 se comen las hamburguesas 🍔 y la pasan genial ✨. illustration -/// info +/// info | Información Las ilustraciones fueron creados por Ketrina Thompson. 🎨 @@ -204,7 +204,7 @@ Sólo las comes y listo 🍔 ⏹. No has hablado ni coqueteado mucho, ya que has pasado la mayor parte del tiempo esperando 🕙 frente al mostrador 😞. -/// info +/// info | Información Las ilustraciones fueron creados por Ketrina Thompson. 🎨 @@ -396,7 +396,7 @@ Todo eso es lo que impulsa FastAPI (a través de Starlette) y lo que hace que te ## Detalles muy técnicos -/// warning | "Advertencia" +/// warning | Advertencia Probablemente puedas saltarte esto. diff --git a/docs/es/docs/deployment/versions.md b/docs/es/docs/deployment/versions.md index 7d09a2739..74243da89 100644 --- a/docs/es/docs/deployment/versions.md +++ b/docs/es/docs/deployment/versions.md @@ -42,7 +42,7 @@ Siguiendo las convenciones de *Semantic Versioning*, cualquier versión por deba FastAPI también sigue la convención de que cualquier cambio hecho en una "PATCH" version es para solucionar errores y *non-breaking changes*. -/// tip +/// tip | Consejo El "PATCH" es el último número, por ejemplo, en `0.2.3`, la PATCH version es `3`. @@ -56,7 +56,7 @@ fastapi>=0.45.0,<0.46.0 En versiones "MINOR" son añadidas nuevas características y posibles breaking changes. -/// tip +/// tip | Consejo La versión "MINOR" es el número en el medio, por ejemplo, en `0.2.3`, la "MINOR" version es `2`. diff --git a/docs/es/docs/features.md b/docs/es/docs/features.md index 3c610f8f1..b75918dff 100644 --- a/docs/es/docs/features.md +++ b/docs/es/docs/features.md @@ -63,7 +63,7 @@ second_user_data = { my_second_user: User = User(**second_user_data) ``` -/// info +/// info | Información `**second_user_data` significa: diff --git a/docs/es/docs/how-to/graphql.md b/docs/es/docs/how-to/graphql.md index d75af7d81..590c2e828 100644 --- a/docs/es/docs/how-to/graphql.md +++ b/docs/es/docs/how-to/graphql.md @@ -4,7 +4,7 @@ Como **FastAPI** está basado en el estándar **ASGI**, es muy fácil integrar c Puedes combinar *operaciones de path* regulares de la library de FastAPI con GraphQL en la misma aplicación. -/// tip +/// tip | Consejo **GraphQL** resuelve algunos casos de uso específicos. @@ -49,7 +49,7 @@ Versiones anteriores de Starlette incluyen la clase `GraphQLApp` para integrarlo Esto fue marcado como obsoleto en Starlette, pero si aún tienes código que lo usa, puedes fácilmente **migrar** a starlette-graphene3, la cual cubre el mismo caso de uso y tiene una **interfaz casi idéntica.** -/// tip +/// tip | Consejo Si necesitas GraphQL, te recomendaría revisar Strawberry, que es basada en anotaciones de tipo en vez de clases y tipos personalizados. diff --git a/docs/es/docs/python-types.md b/docs/es/docs/python-types.md index fce434483..4015dbb05 100644 --- a/docs/es/docs/python-types.md +++ b/docs/es/docs/python-types.md @@ -12,7 +12,7 @@ Todo **FastAPI** está basado en estos type hints, lo que le da muchas ventajas Pero, así nunca uses **FastAPI** te beneficiarás de aprender un poco sobre los type hints. -/// note | "Nota" +/// note | Nota Si eres un experto en Python y ya lo sabes todo sobre los type hints, salta al siguiente capítulo. @@ -256,7 +256,7 @@ Tomado de la documentación oficial de Pydantic: {!../../../docs_src/python_types/tutorial010.py!} ``` -/// info | "Información" +/// info | Información Para aprender más sobre Pydantic mira su documentación. @@ -288,7 +288,7 @@ Puede que todo esto suene abstracto. Pero no te preocupes que todo lo verás en Lo importante es que usando los tipos de Python estándar en un único lugar (en vez de añadir más clases, decorator, etc.) **FastAPI** hará mucho del trabajo por ti. -/// info | "Información" +/// info | Información Si ya pasaste por todo el tutorial y volviste a la sección de los tipos, una buena referencia es la "cheat sheet" de `mypy`. diff --git a/docs/es/docs/tutorial/cookie-params.md b/docs/es/docs/tutorial/cookie-params.md index 27ba8ed57..3eaea31f9 100644 --- a/docs/es/docs/tutorial/cookie-params.md +++ b/docs/es/docs/tutorial/cookie-params.md @@ -32,9 +32,9 @@ Primero importa `Cookie`: //// tab | Python 3.10+ non-Annotated -/// tip +/// tip | Consejo -Prefer to use the `Annotated` version if possible. +Es preferible utilizar la versión `Annotated` si es posible. /// @@ -46,9 +46,9 @@ Prefer to use the `Annotated` version if possible. //// tab | Python 3.8+ non-Annotated -/// tip +/// tip | Consejo -Prefer to use the `Annotated` version if possible. +Es preferible utilizar la versión `Annotated` si es posible. /// @@ -90,9 +90,9 @@ El primer valor es el valor por defecto, puedes pasar todos los parámetros adic //// tab | Python 3.10+ non-Annotated -/// tip +/// tip | Consejo -Prefer to use the `Annotated` version if possible. +Es preferible utilizar la versión `Annotated` si es posible. /// @@ -104,9 +104,9 @@ Prefer to use the `Annotated` version if possible. //// tab | Python 3.8+ non-Annotated -/// tip +/// tip | Consejo -Prefer to use the `Annotated` version if possible. +Es preferible utilizar la versión `Annotated` si es posible. /// diff --git a/docs/es/docs/tutorial/first-steps.md b/docs/es/docs/tutorial/first-steps.md index affdfebff..8d8909b97 100644 --- a/docs/es/docs/tutorial/first-steps.md +++ b/docs/es/docs/tutorial/first-steps.md @@ -24,7 +24,7 @@ $ uvicorn main:app --reload -/// note | "Nota" +/// note | Nota El comando `uvicorn main:app` se refiere a: @@ -139,7 +139,7 @@ También podrías usarlo para generar código automáticamente, para los cliente `FastAPI` es una clase de Python que provee toda la funcionalidad para tu API. -/// note | "Detalles Técnicos" +/// note | Detalles Técnicos `FastAPI` es una clase que hereda directamente de `Starlette`. @@ -205,7 +205,7 @@ https://example.com/items/foo /items/foo ``` -/// info | "Información" +/// info | Información Un "path" también se conoce habitualmente como "endpoint", "route" o "ruta". @@ -259,7 +259,7 @@ El `@app.get("/")` le dice a **FastAPI** que la función que tiene justo debajo * el path `/` * usando una operación get -/// info | "Información sobre `@decorator`" +/// info | Información sobre `@decorator` Esa sintaxis `@algo` se llama un "decorador" en Python. @@ -286,7 +286,7 @@ y las más exóticas: * `@app.patch()` * `@app.trace()` -/// tip | "Consejo" +/// tip | Consejo Tienes la libertad de usar cada operación (método de HTTP) como quieras. @@ -324,7 +324,7 @@ También podrías definirla como una función estándar en lugar de `async def`: {!../../../docs_src/first_steps/tutorial003.py!} ``` -/// note | "Nota" +/// note | Nota Si no sabes la diferencia, revisa el [Async: *"¿Tienes prisa?"*](../async.md#tienes-prisa){.internal-link target=_blank}. diff --git a/docs/es/docs/tutorial/path-params.md b/docs/es/docs/tutorial/path-params.md index 73bd586f1..e09e0381f 100644 --- a/docs/es/docs/tutorial/path-params.md +++ b/docs/es/docs/tutorial/path-params.md @@ -24,7 +24,7 @@ Puedes declarar el tipo de un parámetro de path en la función usando las anota En este caso, `item_id` es declarado como un `int`. -/// check | "Revisa" +/// check | Revisa Esto te dará soporte en el editor dentro de tu función, con chequeo de errores, auto-completado, etc. @@ -38,7 +38,7 @@ Si corres este ejemplo y abres tu navegador en http://127.0.0.1:8000/items/4.2 -/// check | "Revisa" +/// check | Revisa Así, con la misma declaración de tipo de Python, **FastAPI** te da validación de datos. @@ -85,7 +85,7 @@ Cuando abras tu navegador en -/// check | "Revisa" +/// check | Revisa Nuevamente, con la misma declaración de tipo de Python, **FastAPI** te da documentación automática e interactiva (integrándose con Swagger UI) @@ -143,13 +143,13 @@ Luego crea atributos de clase con valores fijos, que serán los valores disponib {!../../../docs_src/path_params/tutorial005.py!} ``` -/// info | "Información" +/// info | Información Las Enumerations (o enums) están disponibles en Python desde la versión 3.4. /// -/// tip | "Consejo" +/// tip | Consejo Si lo estás dudando, "AlexNet", "ResNet", y "LeNet" son solo nombres de modelos de Machine Learning. @@ -189,7 +189,7 @@ Puedes obtener el valor exacto (un `str` en este caso) usando `model_name.value` {!../../../docs_src/path_params/tutorial005.py!} ``` -/// tip | "Consejo" +/// tip | Consejo También podrías obtener el valor `"lenet"` con `ModelName.lenet.value`. @@ -246,7 +246,7 @@ Entonces lo puedes usar con: {!../../../docs_src/path_params/tutorial004.py!} ``` -/// tip | "Consejo" +/// tip | Consejo Podrías necesitar que el parámetro contenga `/home/johndoe/myfile.txt` con un slash inicial (`/`). diff --git a/docs/es/docs/tutorial/query-params.md b/docs/es/docs/tutorial/query-params.md index 52a3e66a4..6f88fd617 100644 --- a/docs/es/docs/tutorial/query-params.md +++ b/docs/es/docs/tutorial/query-params.md @@ -69,13 +69,13 @@ Del mismo modo puedes declarar parámetros de query opcionales definiendo el val En este caso el parámetro de la función `q` será opcional y será `None` por defecto. -/// check | "Revisa" +/// check | Revisa También puedes notar que **FastAPI** es lo suficientemente inteligente para darse cuenta de que el parámetro de path `item_id` es un parámetro de path y que `q` no lo es, y por lo tanto es un parámetro de query. /// -/// note | "Nota" +/// note | Nota FastAPI sabrá que `q` es opcional por el `= None`. @@ -199,7 +199,7 @@ En este caso hay 3 parámetros de query: * `skip`, un `int` con un valor por defecto de `0`. * `limit`, un `int` opcional. -/// tip | "Consejo" +/// tip | Consejo También podrías usar los `Enum`s de la misma manera que con los [Parámetros de path](path-params.md#valores-predefinidos){.internal-link target=_blank}. From e8322228b42c11299d1df75bf3586a3a675f72d1 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 19 Aug 2024 18:15:49 +0000 Subject: [PATCH 13/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 3b41fa2ad..646060fea 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -31,6 +31,7 @@ hide: ### Translations +* 📝 Update Spanish translation docs for consistency. PR [#12044](https://github.com/fastapi/fastapi/pull/12044) by [@alejsdev](https://github.com/alejsdev). * 🌐 Update docs about dependencies with yield. PR [#12028](https://github.com/fastapi/fastapi/pull/12028) by [@xuvjso](https://github.com/xuvjso). * 📝 Update FastAPI People, do not translate to have the most recent info. PR [#12034](https://github.com/fastapi/fastapi/pull/12034) by [@tiangolo](https://github.com/tiangolo). * 🌐 Update Urdu translation for `docs/ur/docs/benchmarks.md`. PR [#10046](https://github.com/fastapi/fastapi/pull/10046) by [@AhsanSheraz](https://github.com/AhsanSheraz). From f4dfbae90396c1eed349fa96e1770874fe482ae1 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 19 Aug 2024 19:40:31 -0500 Subject: [PATCH 14/88] =?UTF-8?q?=E2=AC=86=20[pre-commit.ci]=20pre-commit?= =?UTF-8?q?=20autoupdate=20(#12046)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit updates: - [github.com/pre-commit/pre-commit-hooks: v4.4.0 → v4.6.0](https://github.com/pre-commit/pre-commit-hooks/compare/v4.4.0...v4.6.0) - https://github.com/charliermarsh/ruff-pre-commit → https://github.com/astral-sh/ruff-pre-commit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- .pre-commit-config.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 1ed005657..7532f21b5 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -4,7 +4,7 @@ default_language_version: python: python3.10 repos: - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.4.0 + rev: v4.6.0 hooks: - id: check-added-large-files - id: check-toml @@ -13,7 +13,7 @@ repos: - --unsafe - id: end-of-file-fixer - id: trailing-whitespace -- repo: https://github.com/charliermarsh/ruff-pre-commit +- repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.6.1 hooks: - id: ruff From 2d34086b70a1026aeb4974ffcf92041cd69e1ece Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 20 Aug 2024 00:40:55 +0000 Subject: [PATCH 15/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 646060fea..f562ba06e 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -38,6 +38,7 @@ hide: ### Internal +* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12046](https://github.com/fastapi/fastapi/pull/12046) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). * 🔧 Update coverage config files. PR [#12035](https://github.com/fastapi/fastapi/pull/12035) by [@tiangolo](https://github.com/tiangolo). * 🔨 Standardize shebang across shell scripts. PR [#11942](https://github.com/fastapi/fastapi/pull/11942) by [@gitworkflows](https://github.com/gitworkflows). * ⬆ Update sqlalchemy requirement from <1.4.43,>=1.3.18 to >=1.3.18,<2.0.33. PR [#11979](https://github.com/fastapi/fastapi/pull/11979) by [@dependabot[bot]](https://github.com/apps/dependabot). From 34e6e63fb2ca05a5929bc2d151b4e45194ed87a0 Mon Sep 17 00:00:00 2001 From: Yuki Watanabe Date: Thu, 22 Aug 2024 01:55:16 +0900 Subject: [PATCH 16/88] =?UTF-8?q?=F0=9F=8C=90=20Add=20Japanese=20translati?= =?UTF-8?q?on=20for=20`docs/ja/docs/learn/index.md`=20(#11592)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ja/docs/learn/index.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 docs/ja/docs/learn/index.md diff --git a/docs/ja/docs/learn/index.md b/docs/ja/docs/learn/index.md new file mode 100644 index 000000000..2f24c670a --- /dev/null +++ b/docs/ja/docs/learn/index.md @@ -0,0 +1,5 @@ +# 学習 + +ここでは、**FastAPI** を学習するための入門セクションとチュートリアルを紹介します。 + +これは、FastAPIを学習するにあたっての**書籍**や**コース**であり、**公式**かつ推奨される方法とみなすことができます 😎 From 2fe05762b2672959d754ee869a11efbf9cdd6e97 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 21 Aug 2024 16:55:38 +0000 Subject: [PATCH 17/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index f562ba06e..a9fcd1383 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -31,6 +31,7 @@ hide: ### Translations +* 🌐 Add Japanese translation for `docs/ja/docs/learn/index.md`. PR [#11592](https://github.com/fastapi/fastapi/pull/11592) by [@ukwhatn](https://github.com/ukwhatn). * 📝 Update Spanish translation docs for consistency. PR [#12044](https://github.com/fastapi/fastapi/pull/12044) by [@alejsdev](https://github.com/alejsdev). * 🌐 Update docs about dependencies with yield. PR [#12028](https://github.com/fastapi/fastapi/pull/12028) by [@xuvjso](https://github.com/xuvjso). * 📝 Update FastAPI People, do not translate to have the most recent info. PR [#12034](https://github.com/fastapi/fastapi/pull/12034) by [@tiangolo](https://github.com/tiangolo). From 38ff43b690df0d5a8ce7e4069750696eca323c23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Pedro=20Pereira=20Holanda?= Date: Wed, 21 Aug 2024 13:56:50 -0300 Subject: [PATCH 18/88] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20transla?= =?UTF-8?q?tion=20for=20`docs/pt/docs/tutorial/request=5Ffile.md`=20(#1201?= =?UTF-8?q?8)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/tutorial/request_files.md | 418 +++++++++++++++++++++++++ 1 file changed, 418 insertions(+) create mode 100644 docs/pt/docs/tutorial/request_files.md diff --git a/docs/pt/docs/tutorial/request_files.md b/docs/pt/docs/tutorial/request_files.md new file mode 100644 index 000000000..60e4ecb26 --- /dev/null +++ b/docs/pt/docs/tutorial/request_files.md @@ -0,0 +1,418 @@ +# Arquivos de Requisição + +Você pode definir arquivos para serem enviados para o cliente utilizando `File`. + +/// info + +Para receber arquivos compartilhados, primeiro instale `python-multipart`. + +E.g. `pip install python-multipart`. + +Isso se deve por que arquivos enviados são enviados como "dados de formulário". + +/// + +## Importe `File` + +Importe `File` e `UploadFile` do `fastapi`: + +//// tab | Python 3.9+ + +```Python hl_lines="3" +{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="1" +{!> ../../../docs_src/request_files/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="1" +{!> ../../../docs_src/request_files/tutorial001.py!} +``` + +//// + +## Defina os parâmetros de `File` + +Cria os parâmetros do arquivo da mesma forma que você faria para `Body` ou `Form`: + +//// tab | Python 3.9+ + +```Python hl_lines="9" +{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8" +{!> ../../../docs_src/request_files/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="7" +{!> ../../../docs_src/request_files/tutorial001.py!} +``` + +//// + +/// info | Informação + +`File` é uma classe que herda diretamente de `Form`. + +Mas lembre-se que quando você importa `Query`,`Path`, `File`, entre outros, do `fastapi`, essas são na verdade funções que retornam classes especiais. + +/// + +/// tip | Dica + +Para declarar o corpo de arquivos, você precisa utilizar `File`, do contrário os parâmetros seriam interpretados como parâmetros de consulta ou corpo (JSON) da requisição. + +/// + +Os arquivos serão enviados como "form data". + +Se você declarar o tipo do seu parâmetro na sua *função de operação de rota* como `bytes`, o **FastAPI** irá ler o arquivo para você e você receberá o conteúdo como `bytes`. + +Lembre-se que isso significa que o conteúdo inteiro será armazenado em memória. Isso funciona bem para arquivos pequenos. + +Mas existem vários casos em que você pode se beneficiar ao usar `UploadFile`. + +## Parâmetros de arquivo com `UploadFile` + +Defina um parâmetro de arquivo com o tipo `UploadFile` + +//// tab | Python 3.9+ + +```Python hl_lines="14" +{!> ../../../docs_src/request_files/tutorial001_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="13" +{!> ../../../docs_src/request_files/tutorial001_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="12" +{!> ../../../docs_src/request_files/tutorial001.py!} +``` + +//// + +Utilizando `UploadFile` tem várias vantagens sobre `bytes`: + +* Você não precisa utilizar `File()` como o valor padrão do parâmetro. +* A classe utiliza um arquivo em "spool": + * Um arquivo guardado em memória até um tamanho máximo, depois desse limite ele é guardado em disco. +* Isso significa que a classe funciona bem com arquivos grandes como imagens, vídeos, binários extensos, etc. Sem consumir toda a memória. +* Você pode obter metadados do arquivo enviado. +* Ela possui uma interface semelhante a arquivos `async`. +* Ela expõe um objeto python `SpooledTemporaryFile` que você pode repassar para bibliotecas que esperam um objeto com comportamento de arquivo. + +### `UploadFile` + +`UploadFile` tem os seguintes atributos: + +* `filename`: Uma string (`str`) com o nome original do arquivo enviado (e.g. `myimage.jpg`). +* `content-type`: Uma `str` com o tipo do conteúdo (tipo MIME / media) (e.g. `image/jpeg`). +* `file`: Um objeto do tipo `SpooledTemporaryFile` (um objeto file-like). O arquivo propriamente dito que você pode passar diretamente para outras funções ou bibliotecas que esperam um objeto "file-like". + +`UploadFile` tem os seguintes métodos `async`. Todos eles chamam os métodos de arquivos por baixo dos panos (usando o objeto `SpooledTemporaryFile` interno). + +* `write(data)`: escreve dados (`data`) em `str` ou `bytes` no arquivo. +* `read(size)`: Lê um número de bytes/caracteres de acordo com a quantidade `size` (`int`). +* `seek(offset)`: Navega para o byte na posição `offset` (`int`) do arquivo. + * E.g., `await myfile.seek(0)` navegaria para o ínicio do arquivo. + * Isso é especialmente útil se você executar `await myfile.read()` uma vez e depois precisar ler os conteúdos do arquivo de novo. +* `close()`: Fecha o arquivo. + +Como todos esses métodos são assíncronos (`async`) você precisa esperar ("await") por eles. + +Por exemplo, dentro de uma *função de operação de rota* assíncrona você pode obter os conteúdos com: + +```Python +contents = await myfile.read() +``` + +Se você estiver dentro de uma *função de operação de rota* definida normalmente com `def`, você pode acessar `UploadFile.file` diretamente, por exemplo: + +```Python +contents = myfile.file.read() +``` + +/// note | Detalhes técnicos do `async` + +Quando você utiliza métodos assíncronos, o **FastAPI** executa os métodos do arquivo em uma threadpool e espera por eles. + +/// + +/// note | Detalhes técnicos do Starlette + +O `UploadFile` do **FastAPI** herda diretamente do `UploadFile` do **Starlette**, mas adiciona algumas funcionalidades necessárias para ser compatível com o **Pydantic** + +/// + +## O que é "Form Data" + +A forma como formulários HTML(`
`) enviam dados para o servidor normalmente utilizam uma codificação "especial" para esses dados, que é diferente do JSON. + +O **FastAPI** garante que os dados serão lidos da forma correta, em vez do JSON. + +/// note | Detalhes Técnicos + +Dados vindos de formulários geralmente tem a codificação com o "media type" `application/x-www-form-urlencoded` quando estes não incluem arquivos. + +Mas quando os dados incluem arquivos, eles são codificados como `multipart/form-data`. Se você utilizar `File`, **FastAPI** saberá que deve receber os arquivos da parte correta do corpo da requisição. + +Se você quer ler mais sobre essas codificações e campos de formulário, veja a documentação online da MDN sobre POST . + +/// + +/// warning | Aviso + +Você pode declarar múltiplos parâmetros `File` e `Form` em uma *operação de rota*, mas você não pode declarar campos `Body`que seriam recebidos como JSON junto desses parâmetros, por que a codificação do corpo da requisição será `multipart/form-data` em vez de `application/json`. + +Isso não é uma limitação do **FastAPI**, é uma parte do protocolo HTTP. + +/// + +## Arquivo de upload opcional + +Você pode definir um arquivo como opcional utilizando as anotações de tipo padrão e definindo o valor padrão como `None`: + +//// tab | Python 3.10+ + +```Python hl_lines="9 17" +{!> ../../../docs_src/request_files/tutorial001_02_an_py310.py!} +``` + +//// + +//// tab | Python 3.9+ + +```Python hl_lines="9 17" +{!> ../../../docs_src/request_files/tutorial001_02_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="10 18" +{!> ../../../docs_src/request_files/tutorial001_02_an.py!} +``` + +//// + +//// tab | Python 3.10+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated`, se possível + +/// + +```Python hl_lines="7 15" +{!> ../../../docs_src/request_files/tutorial001_02_py310.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated`, se possível + +/// + +```Python hl_lines="9 17" +{!> ../../../docs_src/request_files/tutorial001_02.py!} +``` + +//// + +## `UploadFile` com Metadados Adicionais + +Você também pode utilizar `File()` com `UploadFile`, por exemplo, para definir metadados adicionais: + +//// tab | Python 3.9+ + +```Python hl_lines="9 15" +{!> ../../../docs_src/request_files/tutorial001_03_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="8 14" +{!> ../../../docs_src/request_files/tutorial001_03_an.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível + +/// + +```Python hl_lines="7 13" +{!> ../../../docs_src/request_files/tutorial001_03.py!} +``` + +//// + +## Envio de Múltiplos Arquivos + +É possível enviar múltiplos arquivos ao mesmo tmepo. + +Ele ficam associados ao mesmo "campo do formulário" enviado com "form data". + +Para usar isso, declare uma lista de `bytes` ou `UploadFile`: + +//// tab | Python 3.9+ + +```Python hl_lines="10 15" +{!> ../../../docs_src/request_files/tutorial002_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="11 16" +{!> ../../../docs_src/request_files/tutorial002_an.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível + +/// + +```Python hl_lines="8 13" +{!> ../../../docs_src/request_files/tutorial002_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível + +/// + +```Python hl_lines="10 15" +{!> ../../../docs_src/request_files/tutorial002.py!} +``` + +//// + +Você irá receber, como delcarado uma lista (`list`) de `bytes` ou `UploadFile`s, + +/// note | Detalhes Técnicos + +Você também poderia utilizar `from starlette.responses import HTMLResponse`. + +O **FastAPI** fornece as mesmas `starlette.responses` como `fastapi.responses` apenas como um facilitador para você, desenvolvedor. Mas a maior parte das respostas vem diretamente do Starlette. + +/// + +### Enviando Múltiplos Arquivos com Metadados Adicionais + +E da mesma forma que antes, você pode utilizar `File()` para definir parâmetros adicionais, até mesmo para `UploadFile`: + +//// tab | Python 3.9+ + +```Python hl_lines="11 18-20" +{!> ../../../docs_src/request_files/tutorial003_an_py39.py!} +``` + +//// + +//// tab | Python 3.8+ + +```Python hl_lines="12 19-21" +{!> ../../../docs_src/request_files/tutorial003_an.py!} +``` + +//// + +//// tab | Python 3.9+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="9 16" +{!> ../../../docs_src/request_files/tutorial003_py39.py!} +``` + +//// + +//// tab | Python 3.8+ non-Annotated + +/// tip | Dica + +Utilize a versão com `Annotated` se possível. + +/// + +```Python hl_lines="11 18" +{!> ../../../docs_src/request_files/tutorial003.py!} +``` + +//// + +## Recapitulando + +Use `File`, `bytes` e `UploadFile` para declarar arquivos que serão enviados na requisição, enviados como dados do formulário. From 4f3381a95eee1c1a76630d0a232cdd4553166d2b Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 21 Aug 2024 16:58:20 +0000 Subject: [PATCH 19/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a9fcd1383..12f1f50cd 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -31,6 +31,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/request_file.md`. PR [#12018](https://github.com/fastapi/fastapi/pull/12018) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Add Japanese translation for `docs/ja/docs/learn/index.md`. PR [#11592](https://github.com/fastapi/fastapi/pull/11592) by [@ukwhatn](https://github.com/ukwhatn). * 📝 Update Spanish translation docs for consistency. PR [#12044](https://github.com/fastapi/fastapi/pull/12044) by [@alejsdev](https://github.com/alejsdev). * 🌐 Update docs about dependencies with yield. PR [#12028](https://github.com/fastapi/fastapi/pull/12028) by [@xuvjso](https://github.com/xuvjso). From 705659bb2277633e75269de9bac9d84cc3c15ae4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Wed, 21 Aug 2024 19:47:31 -0500 Subject: [PATCH 20/88] =?UTF-8?q?=F0=9F=93=9D=20Add=20docs=20about=20Envir?= =?UTF-8?q?onment=20Variables=20and=20Virtual=20Environments=20(#12054)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 + docs/en/docs/advanced/settings.md | 126 +-- docs/en/docs/advanced/templates.md | 2 +- docs/en/docs/advanced/websockets.md | 2 +- docs/en/docs/contributing.md | 138 +-- docs/en/docs/deployment/manually.md | 4 +- docs/en/docs/deployment/server-workers.md | 2 + docs/en/docs/environment-variables.md | 300 +++++++ docs/en/docs/index.md | 2 + docs/en/docs/tutorial/index.md | 8 +- docs/en/docs/tutorial/request-files.md | 6 +- .../docs/tutorial/request-forms-and-files.md | 6 +- docs/en/docs/tutorial/request-forms.md | 6 +- docs/en/docs/tutorial/response-model.md | 13 +- docs/en/docs/tutorial/security/first-steps.md | 8 +- docs/en/docs/tutorial/security/oauth2-jwt.md | 6 +- docs/en/docs/tutorial/sql-databases.md | 4 +- docs/en/docs/tutorial/testing.md | 10 +- docs/en/docs/virtual-environments.md | 844 ++++++++++++++++++ docs/en/mkdocs.yml | 2 + 20 files changed, 1228 insertions(+), 263 deletions(-) create mode 100644 docs/en/docs/environment-variables.md create mode 100644 docs/en/docs/virtual-environments.md diff --git a/README.md b/README.md index b00ef6ba9..889a89ed7 100644 --- a/README.md +++ b/README.md @@ -132,6 +132,8 @@ FastAPI stands on the shoulders of giants: ## Installation +Create and activate a virtual environment and then install FastAPI: +
```console diff --git a/docs/en/docs/advanced/settings.md b/docs/en/docs/advanced/settings.md index b78f83953..22bf7de20 100644 --- a/docs/en/docs/advanced/settings.md +++ b/docs/en/docs/advanced/settings.md @@ -6,135 +6,17 @@ Most of these settings are variable (can change), like database URLs. And many c For this reason it's common to provide them in environment variables that are read by the application. -## Environment Variables - -/// tip - -If you already know what "environment variables" are and how to use them, feel free to skip to the next section below. - -/// - -An environment variable (also known as "env var") is a variable that lives outside of the Python code, in the operating system, and could be read by your Python code (or by other programs as well). - -You can create and use environment variables in the shell, without needing Python: - -//// tab | Linux, macOS, Windows Bash - -
- -```console -// You could create an env var MY_NAME with -$ export MY_NAME="Wade Wilson" - -// Then you could use it with other programs, like -$ echo "Hello $MY_NAME" - -Hello Wade Wilson -``` - -
- -//// - -//// tab | Windows PowerShell - -
- -```console -// Create an env var MY_NAME -$ $Env:MY_NAME = "Wade Wilson" - -// Use it with other programs, like -$ echo "Hello $Env:MY_NAME" - -Hello Wade Wilson -``` - -
- -//// - -### Read env vars in Python - -You could also create environment variables outside of Python, in the terminal (or with any other method), and then read them in Python. - -For example you could have a file `main.py` with: - -```Python hl_lines="3" -import os - -name = os.getenv("MY_NAME", "World") -print(f"Hello {name} from Python") -``` - -/// tip - -The second argument to `os.getenv()` is the default value to return. - -If not provided, it's `None` by default, here we provide `"World"` as the default value to use. - -/// - -Then you could call that Python program: - -
- -```console -// Here we don't set the env var yet -$ python main.py - -// As we didn't set the env var, we get the default value - -Hello World from Python - -// But if we create an environment variable first -$ export MY_NAME="Wade Wilson" - -// And then call the program again -$ python main.py - -// Now it can read the environment variable - -Hello Wade Wilson from Python -``` - -
- -As environment variables can be set outside of the code, but can be read by the code, and don't have to be stored (committed to `git`) with the rest of the files, it's common to use them for configurations or settings. - -You can also create an environment variable only for a specific program invocation, that is only available to that program, and only for its duration. - -To do that, create it right before the program itself, on the same line: - -
- -```console -// Create an env var MY_NAME in line for this program call -$ MY_NAME="Wade Wilson" python main.py - -// Now it can read the environment variable - -Hello Wade Wilson from Python - -// The env var no longer exists afterwards -$ python main.py - -Hello World from Python -``` - -
- /// tip -You can read more about it at The Twelve-Factor App: Config. +To understand environment variables you can read [Environment Variables](../environment-variables.md){.internal-link target=_blank}. /// -### Types and validation +## Types and validation These environment variables can only handle text strings, as they are external to Python and have to be compatible with other programs and the rest of the system (and even with different operating systems, as Linux, Windows, macOS). -That means that any value read in Python from an environment variable will be a `str`, and any conversion to a different type or validation has to be done in code. +That means that any value read in Python from an environment variable will be a `str`, and any conversion to a different type or any validation has to be done in code. ## Pydantic `Settings` @@ -142,7 +24,7 @@ Fortunately, Pydantic provides a great utility to handle these settings coming f ### Install `pydantic-settings` -First, install the `pydantic-settings` package: +First, make sure you create your [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install the `pydantic-settings` package:
diff --git a/docs/en/docs/advanced/templates.md b/docs/en/docs/advanced/templates.md index 43731ec36..416540ba4 100644 --- a/docs/en/docs/advanced/templates.md +++ b/docs/en/docs/advanced/templates.md @@ -8,7 +8,7 @@ There are utilities to configure it easily that you can use directly in your **F ## Install dependencies -Install `jinja2`: +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and install `jinja2`:
diff --git a/docs/en/docs/advanced/websockets.md b/docs/en/docs/advanced/websockets.md index 9655714b0..44c6c7428 100644 --- a/docs/en/docs/advanced/websockets.md +++ b/docs/en/docs/advanced/websockets.md @@ -4,7 +4,7 @@ You can use diff --git a/docs/en/docs/contributing.md b/docs/en/docs/contributing.md index 63e1f359a..91d5724a8 100644 --- a/docs/en/docs/contributing.md +++ b/docs/en/docs/contributing.md @@ -6,117 +6,13 @@ First, you might want to see the basic ways to [help FastAPI and get help](help- If you already cloned the fastapi repository and you want to deep dive in the code, here are some guidelines to set up your environment. -### Virtual environment with `venv` +### Virtual environment -You can create an isolated virtual local environment in a directory using Python's `venv` module. Let's do this in the cloned repository (where the `requirements.txt` is): - -
- -```console -$ python -m venv env -``` - -
- -That will create a directory `./env/` with the Python binaries, and then you will be able to install packages for that local environment. - -### Activate the environment - -Activate the new environment with: - -//// tab | Linux, macOS - -
- -```console -$ source ./env/bin/activate -``` - -
- -//// - -//// tab | Windows PowerShell - -
- -```console -$ .\env\Scripts\Activate.ps1 -``` - -
- -//// - -//// tab | Windows Bash - -Or if you use Bash for Windows (e.g. Git Bash): - -
- -```console -$ source ./env/Scripts/activate -``` - -
- -//// - -To check it worked, use: - -//// tab | Linux, macOS, Windows Bash - -
- -```console -$ which pip - -some/directory/fastapi/env/bin/pip -``` - -
- -//// - -//// tab | Windows PowerShell - -
- -```console -$ Get-Command pip - -some/directory/fastapi/env/bin/pip -``` - -
- -//// - -If it shows the `pip` binary at `env/bin/pip` then it worked. 🎉 - -Make sure you have the latest pip version on your local environment to avoid errors on the next steps: - -
- -```console -$ python -m pip install --upgrade pip - ----> 100% -``` - -
- -/// tip - -Every time you install a new package with `pip` under that environment, activate the environment again. - -This makes sure that if you use a terminal program installed by that package, you use the one from your local environment and not any other that could be installed globally. - -/// +Follow the instructions to create and activate a [virtual environment](virtual-environments.md){.internal-link target=_blank} for the internal code of `fastapi`. ### Install requirements using pip -After activating the environment as described above: +After activating the environment, install the required packages:
@@ -160,7 +56,19 @@ $ bash scripts/format.sh It will also auto-sort all your imports. -For it to sort them correctly, you need to have FastAPI installed locally in your environment, with the command in the section above using `-e`. +## Tests + +There is a script that you can run locally to test all the code and generate coverage reports in HTML: + +
+ +```console +$ bash scripts/test-cov-html.sh +``` + +
+ +This command generates a directory `./htmlcov/`, if you open the file `./htmlcov/index.html` in your browser, you can explore interactively the regions of code that are covered by the tests, and notice if there is any region missing. ## Docs @@ -482,17 +390,3 @@ Serving at: http://127.0.0.1:8008 * Search for such links in the translated document using the regex `#[^# ]`. * Search in all documents already translated into your language for `your-translated-document.md`. For example VS Code has an option "Edit" -> "Find in Files". * When translating a document, do not "pre-translate" `#hash-parts` that link to headings in untranslated documents. - -## Tests - -There is a script that you can run locally to test all the code and generate coverage reports in HTML: - -
- -```console -$ bash scripts/test-cov-html.sh -``` - -
- -This command generates a directory `./htmlcov/`, if you open the file `./htmlcov/index.html` in your browser, you can explore interactively the regions of code that are covered by the tests, and notice if there is any region missing. diff --git a/docs/en/docs/deployment/manually.md b/docs/en/docs/deployment/manually.md index d70c5e48b..3324a7503 100644 --- a/docs/en/docs/deployment/manually.md +++ b/docs/en/docs/deployment/manually.md @@ -82,7 +82,9 @@ When referring to the remote machine, it's common to call it **server**, but als When you install FastAPI, it comes with a production server, Uvicorn, and you can start it with the `fastapi run` command. -But you can also install an ASGI server manually: +But you can also install an ASGI server manually. + +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then you can install the server: //// tab | Uvicorn diff --git a/docs/en/docs/deployment/server-workers.md b/docs/en/docs/deployment/server-workers.md index 433371b9d..efde5f3a1 100644 --- a/docs/en/docs/deployment/server-workers.md +++ b/docs/en/docs/deployment/server-workers.md @@ -39,6 +39,8 @@ And then the Gunicorn-compatible **Uvicorn worker** class would be in charge of ## Install Gunicorn and Uvicorn +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install `gunicorn`: +
```console diff --git a/docs/en/docs/environment-variables.md b/docs/en/docs/environment-variables.md new file mode 100644 index 000000000..78e82d5af --- /dev/null +++ b/docs/en/docs/environment-variables.md @@ -0,0 +1,300 @@ +# Environment Variables + +/// tip + +If you already know what "environment variables" are and how to use them, feel free to skip this. + +/// + +An environment variable (also known as "**env var**") is a variable that lives **outside** of the Python code, in the **operating system**, and could be read by your Python code (or by other programs as well). + +Environment variables could be useful for handling application **settings**, as part of the **installation** of Python, etc. + +## Create and Use Env Vars + +You can **create** and use environment variables in the **shell (terminal)**, without needing Python: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// You could create an env var MY_NAME with +$ export MY_NAME="Wade Wilson" + +// Then you could use it with other programs, like +$ echo "Hello $MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// Create an env var MY_NAME +$ $Env:MY_NAME = "Wade Wilson" + +// Use it with other programs, like +$ echo "Hello $Env:MY_NAME" + +Hello Wade Wilson +``` + +
+ +//// + +## Read env vars in Python + +You could also create environment variables **outside** of Python, in the terminal (or with any other method), and then **read them in Python**. + +For example you could have a file `main.py` with: + +```Python hl_lines="3" +import os + +name = os.getenv("MY_NAME", "World") +print(f"Hello {name} from Python") +``` + +/// tip + +The second argument to `os.getenv()` is the default value to return. + +If not provided, it's `None` by default, here we provide `"World"` as the default value to use. + +/// + +Then you could call that Python program: + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +// Here we don't set the env var yet +$ python main.py + +// As we didn't set the env var, we get the default value + +Hello World from Python + +// But if we create an environment variable first +$ export MY_NAME="Wade Wilson" + +// And then call the program again +$ python main.py + +// Now it can read the environment variable + +Hello Wade Wilson from Python +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +// Here we don't set the env var yet +$ python main.py + +// As we didn't set the env var, we get the default value + +Hello World from Python + +// But if we create an environment variable first +$ $Env:MY_NAME = "Wade Wilson" + +// And then call the program again +$ python main.py + +// Now it can read the environment variable + +Hello Wade Wilson from Python +``` + +
+ +//// + +As environment variables can be set outside of the code, but can be read by the code, and don't have to be stored (committed to `git`) with the rest of the files, it's common to use them for configurations or **settings**. + +You can also create an environment variable only for a **specific program invocation**, that is only available to that program, and only for its duration. + +To do that, create it right before the program itself, on the same line: + +
+ +```console +// Create an env var MY_NAME in line for this program call +$ MY_NAME="Wade Wilson" python main.py + +// Now it can read the environment variable + +Hello Wade Wilson from Python + +// The env var no longer exists afterwards +$ python main.py + +Hello World from Python +``` + +
+ +/// tip + +You can read more about it at The Twelve-Factor App: Config. + +/// + +## Types and Validation + +These environment variables can only handle **text strings**, as they are external to Python and have to be compatible with other programs and the rest of the system (and even with different operating systems, as Linux, Windows, macOS). + +That means that **any value** read in Python from an environment variable **will be a `str`**, and any conversion to a different type or any validation has to be done in code. + +You will learn more about using environment variables for handling **application settings** in the [Advanced User Guide - Settings and Environment Variables](./advanced/settings.md){.internal-link target=_blank}. + +## `PATH` Environment Variable + +There is a **special** environment variable called **`PATH`** that is used by the operating systems (Linux, macOS, Windows) to find programs to run. + +The value of the variable `PATH` is a long string that is made of directories separated by a colon `:` on Linux and macOS, and by a semicolon `;` on Windows. + +For example, the `PATH` environment variable could look like this: + +//// tab | Linux, macOS + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin +``` + +This means that the system should look for programs in the directories: + +* `/usr/local/bin` +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32 +``` + +This means that the system should look for programs in the directories: + +* `C:\Program Files\Python312\Scripts` +* `C:\Program Files\Python312` +* `C:\Windows\System32` + +//// + +When you type a **command** in the terminal, the operating system **looks for** the program in **each of those directories** listed in the `PATH` environment variable. + +For example, when you type `python` in the terminal, the operating system looks for a program called `python` in the **first directory** in that list. + +If it finds it, then it will **use it**. Otherwise it keeps looking in the **other directories**. + +### Installing Python and Updating the `PATH` + +When you install Python, you might be asked if you want to update the `PATH` environment variable. + +//// tab | Linux, macOS + +Let's say you install Python and it ends up in a directory `/opt/custompython/bin`. + +If you say yes to update the `PATH` environment variable, then the installer will add `/opt/custompython/bin` to the `PATH` environment variable. + +It could look like this: + +```plaintext +/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin +``` + +This way, when you type `python` in the terminal, the system will find the Python program in `/opt/custompython/bin` (the last directory) and use that one. + +//// + +//// tab | Windows + +Let's say you install Python and it ends up in a directory `C:\opt\custompython\bin`. + +If you say yes to update the `PATH` environment variable, then the installer will add `C:\opt\custompython\bin` to the `PATH` environment variable. + +```plaintext +C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin +``` + +This way, when you type `python` in the terminal, the system will find the Python program in `C:\opt\custompython\bin` (the last directory) and use that one. + +//// + +This way, when you type `python` in the terminal, the system will find the Python program in `/opt/custompython/bin` (the last directory) and use that one. + +So, if you type: + +
+ +```console +$ python +``` + +
+ +//// tab | Linux, macOS + +The system will **find** the `python` program in `/opt/custompython/bin` and run it. + +It would be roughly equivalent to typing: + +
+ +```console +$ /opt/custompython/bin/python +``` + +
+ +//// + +//// tab | Windows + +The system will **find** the `python` program in `C:\opt\custompython\bin\python` and run it. + +It would be roughly equivalent to typing: + +
+ +```console +$ C:\opt\custompython\bin\python +``` + +
+ +//// + +This information will be useful when learning about [Virtual Environments](virtual-environments.md){.internal-link target=_blank}. + +## Conclusion + +With this you should have a basic understanding of what **environment variables** are and how to use them in Python. + +You can also read more about them in the Wikipedia for Environment Variable. + +In many cases it's not very obvious how environment variables would be useful and applicable right away. But they keep showing up in many different scenarios when you are developing, so it's good to know about them. + +For example, you will need this information in the next section, about [Virtual Environments](virtual-environments.md). diff --git a/docs/en/docs/index.md b/docs/en/docs/index.md index d76ef498b..ac4f4d00f 100644 --- a/docs/en/docs/index.md +++ b/docs/en/docs/index.md @@ -128,6 +128,8 @@ FastAPI stands on the shoulders of giants: ## Installation +Create and activate a virtual environment and then install FastAPI: +
```console diff --git a/docs/en/docs/tutorial/index.md b/docs/en/docs/tutorial/index.md index 5f8c51c4c..386fe5de9 100644 --- a/docs/en/docs/tutorial/index.md +++ b/docs/en/docs/tutorial/index.md @@ -4,9 +4,7 @@ This tutorial shows you how to use **FastAPI** with most of its features, step b Each section gradually builds on the previous ones, but it's structured to separate topics, so that you can go directly to any specific one to solve your specific API needs. -It is also built to work as a future reference. - -So you can come back and see exactly what you need. +It is also built to work as a future reference so you can come back and see exactly what you need. ## Run the code @@ -71,7 +69,9 @@ Using it in your editor is what really shows you the benefits of FastAPI, seeing ## Install FastAPI -The first step is to install FastAPI: +The first step is to install FastAPI. + +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then **install FastAPI**:
diff --git a/docs/en/docs/tutorial/request-files.md b/docs/en/docs/tutorial/request-files.md index 53d9eefde..9f19596a8 100644 --- a/docs/en/docs/tutorial/request-files.md +++ b/docs/en/docs/tutorial/request-files.md @@ -6,7 +6,11 @@ You can define files to be uploaded by the client using `File`. To receive uploaded files, first install `python-multipart`. -E.g. `pip install python-multipart`. +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it, for example: + +```console +$ pip install python-multipart +``` This is because uploaded files are sent as "form data". diff --git a/docs/en/docs/tutorial/request-forms-and-files.md b/docs/en/docs/tutorial/request-forms-and-files.md index 9b4342652..7830a2ba4 100644 --- a/docs/en/docs/tutorial/request-forms-and-files.md +++ b/docs/en/docs/tutorial/request-forms-and-files.md @@ -6,7 +6,11 @@ You can define files and form fields at the same time using `File` and `Form`. To receive uploaded files and/or form data, first install `python-multipart`. -E.g. `pip install python-multipart`. +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it, for example: + +```console +$ pip install python-multipart +``` /// diff --git a/docs/en/docs/tutorial/request-forms.md b/docs/en/docs/tutorial/request-forms.md index 88b5b86b6..87cfdefbc 100644 --- a/docs/en/docs/tutorial/request-forms.md +++ b/docs/en/docs/tutorial/request-forms.md @@ -6,7 +6,11 @@ When you need to receive form fields instead of JSON, you can use `Form`. To use forms, first install `python-multipart`. -E.g. `pip install python-multipart`. +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it, for example: + +```console +$ pip install python-multipart +``` /// diff --git a/docs/en/docs/tutorial/response-model.md b/docs/en/docs/tutorial/response-model.md index c17e32f90..6a2093e6d 100644 --- a/docs/en/docs/tutorial/response-model.md +++ b/docs/en/docs/tutorial/response-model.md @@ -133,8 +133,17 @@ Here we are declaring a `UserIn` model, it will contain a plaintext password: To use `EmailStr`, first install `email-validator`. -E.g. `pip install email-validator` -or `pip install pydantic[email]`. +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it, for example: + +```console +$ pip install email-validator +``` + +or with: + +```console +$ pip install "pydantic[email]" +``` /// diff --git a/docs/en/docs/tutorial/security/first-steps.md b/docs/en/docs/tutorial/security/first-steps.md index ed427a282..4bd026caf 100644 --- a/docs/en/docs/tutorial/security/first-steps.md +++ b/docs/en/docs/tutorial/security/first-steps.md @@ -56,9 +56,13 @@ Prefer to use the `Annotated` version if possible. The `python-multipart` package is automatically installed with **FastAPI** when you run the `pip install "fastapi[standard]"` command. -However, if you use the `pip install fastapi` command, the `python-multipart` package is not included by default. To install it manually, use the following command: +However, if you use the `pip install fastapi` command, the `python-multipart` package is not included by default. -`pip install python-multipart` +To install it manually, make sure you create a [virtual environment](../../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it with: + +```console +$ pip install python-multipart +``` This is because **OAuth2** uses "form data" for sending the `username` and `password`. diff --git a/docs/en/docs/tutorial/security/oauth2-jwt.md b/docs/en/docs/tutorial/security/oauth2-jwt.md index 52877b916..ba2bfef29 100644 --- a/docs/en/docs/tutorial/security/oauth2-jwt.md +++ b/docs/en/docs/tutorial/security/oauth2-jwt.md @@ -28,7 +28,9 @@ If you want to play with JWT tokens and see how they work, check @@ -70,7 +72,7 @@ It supports many secure hashing algorithms and utilities to work with them. The recommended algorithm is "Bcrypt". -So, install PassLib with Bcrypt: +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install PassLib with Bcrypt:
diff --git a/docs/en/docs/tutorial/sql-databases.md b/docs/en/docs/tutorial/sql-databases.md index 0645cc9f1..56971bf9d 100644 --- a/docs/en/docs/tutorial/sql-databases.md +++ b/docs/en/docs/tutorial/sql-databases.md @@ -101,7 +101,9 @@ Now let's see what each file/module does. ## Install `SQLAlchemy` -First you need to install `SQLAlchemy`: +First you need to install `SQLAlchemy`. + +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it, for example:
diff --git a/docs/en/docs/tutorial/testing.md b/docs/en/docs/tutorial/testing.md index 95c8c5bef..06a87e92e 100644 --- a/docs/en/docs/tutorial/testing.md +++ b/docs/en/docs/tutorial/testing.md @@ -12,7 +12,11 @@ With it, you can use `httpx`. -E.g. `pip install httpx`. +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it, for example: + +```console +$ pip install httpx +``` /// @@ -206,7 +210,9 @@ If you have a Pydantic model in your test and you want to send its data to the a ## Run it -After that, you just need to install `pytest`: +After that, you just need to install `pytest`. + +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install it, for example:
diff --git a/docs/en/docs/virtual-environments.md b/docs/en/docs/virtual-environments.md new file mode 100644 index 000000000..3c4aa49c1 --- /dev/null +++ b/docs/en/docs/virtual-environments.md @@ -0,0 +1,844 @@ +# Virtual Environments + +When you work in Python projects you probably should use a **virtual environment** (or a similar mechanism) to isolate the packages you install for each project. + +/// info + +If you already know about virtual environments, how to create them and use them, you might want to skip this section. 🤓 + +/// + +/// tip + +A **virtual environment** is different than an **environment variable**. + +An **environment variable** is a variable in the system that can be used by programs. + +A **virtual environment** is a directory with some files in it. + +/// + +/// info + +This page will teach you how to use **virtual environments** and how they work. + +If you are ready to adopt a **tool that manages everything** for you (including installing Python), try uv. + +/// + +## Create a Project + +First, create a directory for your project. + +What I normally do is that I create a directory named `code` inside my home/user directory. + +And inside of that I create one directory per project. + +
+ +```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 +``` + +
+ +## Create a Virtual Environment + +When you start working on a Python project **for the first time**, create a virtual environment **inside your project**. + +/// tip + +You only need to do this **once per project**, not every time you work. + +/// + +//// tab | `venv` + +To create a virtual environment, you can use the `venv` module that comes with Python. + +
+ +```console +$ python -m venv .venv +``` + +
+ +/// details | What that command means + +* `python`: use the program called `python` +* `-m`: call a module as a script, we'll tell it which module next +* `venv`: use the module called `venv` that normally comes installed with Python +* `.venv`: create the virtual environment in the new directory `.venv` + +/// + +//// + +//// tab | `uv` + +If you have `uv` installed, you can use it to create a virtual environment. + +
+ +```console +$ uv venv +``` + +
+ +/// tip + +By default, `uv` will create a virtual environment in a directory called `.venv`. + +But you could customize it passing an additional argument with the directory name. + +/// + +//// + +That command creates a new virtual environment in a directory called `.venv`. + +/// details | `.venv` or other name + +You could create the virtual environment in a different directory, but there's a convention of calling it `.venv`. + +/// + +## Activate the Virtual Environment + +Activate the new virtual environment so that any Python command you run or package you install uses it. + +/// tip + +Do this **every time** you start a **new terminal session** to work on the project. + +/// + +//// tab | Linux, macOS + +
+ +```console +$ source .venv/bin/activate +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ .venv\Scripts\Activate.ps1 +``` + +
+ +//// + +//// tab | Windows Bash + +Or if you use Bash for Windows (e.g. Git Bash): + +
+ +```console +$ source .venv/Scripts/activate +``` + +
+ +//// + +/// tip + +Every time you install a **new package** in that environment, **activate** the environment again. + +This makes sure that if you use a **terminal (CLI) program** installed by that package, you use the one from your virtual environment and not any other that could be installed globally, probably with a different version than what you need. + +/// + +## Check the Virtual Environment is Active + +Check that the virtual environment is active (the previous command worked). + +/// tip + +This is **optional**, but it's a good way to **check** that everything is working as expected and you are using the virtual environment you intended. + +/// + +//// tab | Linux, macOS, Windows Bash + +
+ +```console +$ which python + +/home/user/code/awesome-project/.venv/bin/python +``` + +
+ +If it shows the `python` binary at `.venv/bin/python`, inside of your project (in this case `awesome-project`), then it worked. 🎉 + +//// + +//// tab | Windows PowerShell + +
+ +```console +$ Get-Command python + +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +
+ +If it shows the `python` binary at `.venv\Scripts\python`, inside of your project (in this case `awesome-project`), then it worked. 🎉 + +//// + +## Upgrade `pip` + +/// tip + +If you use `uv` you would use it to install things instead of `pip`, so you don't need to upgrade `pip`. 😎 + +/// + +If you are using `pip` to install packages (it comes by default with Python), you should **upgrade** it to the latest version. + +Many exotic errors while installing a package are solved by just upgrading `pip` first. + +/// tip + +You would normally do this **once**, right after you create the virtual environment. + +/// + +Make sure the virtual environment is active (with the command above) and then run: + +
+ +```console +$ python -m pip install --upgrade pip + +---> 100% +``` + +
+ +## Add `.gitignore` + +If you are using **Git** (you should), add a `.gitignore` file to exclude everything in your `.venv` from Git. + +/// tip + +If you used `uv` to create the virtual environment, it already did this for you, you can skip this step. 😎 + +/// + +/// tip + +Do this **once**, right after you create the virtual environment. + +/// + +
+ +```console +$ echo "*" > .venv/.gitignore +``` + +
+ +/// details | What that command means + +* `echo "*"`: will "print" the text `*` in the terminal (the next part changes that a bit) +* `>`: anything printed to the terminal by the command to the left of `>` should not be printed but instead written to the file that goes to the right of `>` +* `.gitignore`: the name of the file where the text should be written + +And `*` for Git means "everything". So, it will ignore everything in the `.venv` directory. + +That command will create a file `.gitignore` with the content: + +```gitignore +* +``` + +/// + +## Install Packages + +After activating the environment, you can install packages in it. + +/// tip + +Do this **once** when installing or upgrading the packages your project needs. + +If you need to upgrade a version or add a new package you would **do this again**. + +/// + +### Install Packages Directly + +If you're in a hurry and don't want to use a file to declare your project's package requirements, you can install them directly. + +/// tip + +It's a (very) good idea to put the packages and versions your program needs in a file (for example `requirements.txt` or `pyproject.toml`). + +/// + +//// tab | `pip` + +
+ +```console +$ pip install "fastapi[standard]" + +---> 100% +``` + +
+ +//// + +//// tab | `uv` + +If you have `uv`: + +
+ +```console +$ uv pip install "fastapi[standard]" +---> 100% +``` + +
+ +//// + +### Install from `requirements.txt` + +If you have a `requirements.txt`, you can now use it to install its packages. + +//// tab | `pip` + +
+ +```console +$ pip install -r requirements.txt +---> 100% +``` + +
+ +//// + +//// tab | `uv` + +If you have `uv`: + +
+ +```console +$ uv pip install -r requirements.txt +---> 100% +``` + +
+ +//// + +/// details | `requirements.txt` + +A `requirements.txt` with some packages could look like: + +```requirements.txt +fastapi[standard]==0.113.0 +pydantic==2.8.0 +``` + +/// + +## Run Your Program + +After you activated the virtual environment, you can run your program, and it will use the Python inside of your virtual environment with the packages you installed there. + +
+ +```console +$ python main.py + +Hello World +``` + +
+ +## Configure Your Editor + +You would probably use an editor, make sure you configure it to use the same virtual environment you created (it will probably autodetect it) so that you can get autocompletion and inline errors. + +For example: + +* VS Code +* PyCharm + +/// tip + +You normally have to do this only **once**, when you create the virtual environment. + +/// + +## Deactivate the Virtual Environment + +Once you are done working on your project you can **deactivate** the virtual environment. + +
+ +```console +$ deactivate +``` + +
+ +This way, when you run `python` it won't try to run it from that virtual environment with the packages installed there. + +## Ready to Work + +Now you're ready to start working on your project. + + + +/// tip + +Do you want to understand what's all that above? + +Continue reading. 👇🤓 + +/// + +## Why Virtual Environments + +To work with FastAPI you need to install Python. + +After that, you would need to **install** FastAPI and any other **packages** you want to use. + +To install packages you would normally use the `pip` command that comes with Python (or similar alternatives). + +Nevertheless, if you just use `pip` directly, the packages would be installed in your **global Python environment** (the global installation of Python). + +### The Problem + +So, what's the problem with installing packages in the global Python environment? + +At some point, you will probably end up writing many different programs that depend on **different packages**. And some of these projects you work on will depend on **different versions** of the same package. 😱 + +For example, you could create a project called `philosophers-stone`, this program depends on another package called **`harry`, using the version `1`**. So, you need to install `harry`. + +```mermaid +flowchart LR + stone(philosophers-stone) -->|requires| harry-1[harry v1] +``` + +Then, at some point later, you create another project called `prisoner-of-azkaban`, and this project also depends on `harry`, but this project needs **`harry` version `3`**. + +```mermaid +flowchart LR + azkaban(prisoner-of-azkaban) --> |requires| harry-3[harry v3] +``` + +But now the problem is, if you install the packages globally (in the global environment) instead of in a local **virtual environment**, you will have to choose which version of `harry` to install. + +If you want to run `philosophers-stone` you will need to first install `harry` version `1`, for example with: + +
+ +```console +$ pip install "harry==1" +``` + +
+ +And then you would end up with `harry` version `1` installed in your global Python environment. + +```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 +``` + +But then if you want to run `prisoner-of-azkaban`, you will need to uninstall `harry` version `1` and install `harry` version `3` (or just installing version `3` would automatically uninstall version `1`). + +
+ +```console +$ pip install "harry==3" +``` + +
+ +And then you would end up with `harry` version `3` installed in your global Python environment. + +And if you try to run `philosophers-stone` again, there's a chance it would **not work** because it needs `harry` version `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 + +It's very common in Python packages to try the best to **avoid breaking changes** in **new versions**, but it's better to be safe, and install newer versions intentionally and when you can run the tests to check everything is working correctly. + +/// + +Now, imagine that with **many** other **packages** that all your **projects depend on**. That's very difficult to manage. And you would probably end up running some projects with some **incompatible versions** of the packages, and not knowing why something isn't working. + +Also, depending on your operating system (e.g. Linux, Windows, macOS), it could have come with Python already installed. And in that case it probably had some packages pre-installed with some specific versions **needed by your system**. If you install packages in the global Python environment, you could end up **breaking** some of the programs that came with your operating system. + +## Where are Packages Installed + +When you install Python, it creates some directories with some files in your computer. + +Some of these directories are the ones in charge of having all the packages you install. + +When you run: + +
+ +```console +// Don't run this now, it's just an example 🤓 +$ pip install "fastapi[standard]" +---> 100% +``` + +
+ +That will download a compressed file with the FastAPI code, normally from PyPI. + +It will also **download** files for other packages that FastAPI depends on. + +Then it will **extract** all those files and put them in a directory in your computer. + +By default, it will put those files downloaded and extracted in the directory that comes with your Python installation, that's the **global environment**. + +## What are Virtual Environments + +The solution to the problems of having all the packages in the global environment is to use a **virtual environment for each project** you work on. + +A virtual environment is a **directory**, very similar to the global one, where you can install the packages for a project. + +This way, each project will have it's own virtual environment (`.venv` directory) with its own packages. + +```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 +``` + +## What Does Activating a Virtual Environment Mean + +When you activate a virtual environment, for example with: + +//// tab | Linux, macOS + +
+ +```console +$ source .venv/bin/activate +``` + +
+ +//// + +//// tab | Windows PowerShell + +
+ +```console +$ .venv\Scripts\Activate.ps1 +``` + +
+ +//// + +//// tab | Windows Bash + +Or if you use Bash for Windows (e.g. Git Bash): + +
+ +```console +$ source .venv/Scripts/activate +``` + +
+ +//// + +That command will create or modify some [environment variables](environment-variables.md){.internal-link target=_blank} that will be available for the next commands. + +One of those variables is the `PATH` variable. + +/// tip + +You can learn more about the `PATH` environment variable in the [Environment Variables](environment-variables.md#path-environment-variable){.internal-link target=_blank} section. + +/// + +Activating a virtual environment adds its path `.venv/bin` (on Linux and macOS) or `.venv\Scripts` (on Windows) to the `PATH` environment variable. + +Let's say that before activating the environment, the `PATH` variable looked like this: + +//// tab | Linux, macOS + +```plaintext +/usr/bin:/bin:/usr/sbin:/sbin +``` + +That means that the system would look for programs in: + +* `/usr/bin` +* `/bin` +* `/usr/sbin` +* `/sbin` + +//// + +//// tab | Windows + +```plaintext +C:\Windows\System32 +``` + +That means that the system would look for programs in: + +* `C:\Windows\System32` + +//// + +After activating the virtual environment, the `PATH` variable would look something like this: + +//// tab | Linux, macOS + +```plaintext +/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: + +```plaintext +/home/user/code/awesome-project/.venv/bin +``` + +before looking in the other directories. + +So, when you type `python` in the terminal, the system will find the Python program in + +```plaintext +/home/user/code/awesome-project/.venv/bin/python +``` + +and use that one. + +//// + +//// tab | Windows + +```plaintext +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: + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts +``` + +before looking in the other directories. + +So, when you type `python` in the terminal, the system will find the Python program in + +```plaintext +C:\Users\user\code\awesome-project\.venv\Scripts\python +``` + +and use that one. + +//// + +An important detail is that it will put the virtual environment path at the **beginning** of the `PATH` variable. The system will find it **before** finding any other Python available. This way, when you run `python`, it will use the Python **from the virtual environment** instead of any other `python` (for example, a `python` from a global environment). + +Activating a virtual environment also changes a couple of other things, but this is one of the most important things it does. + +## Checking a Virtual Environment + +When you check if a virtual environment is active, for example with: + +//// 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 +``` + +
+ +//// + +That means that the `python` program that will be used is the one **in the virtual environment**. + +you use `which` in Linux and macOS and `Get-Command` in Windows PowerShell. + +The way that command works is that it will go and check in the `PATH` environment variable, going through **each path in order**, looking for the program called `python`. Once it finds it, it will **show you the path** to that program. + +The most important part is that when you call `python`, that is the exact "`python`" that will be executed. + +So, you can confirm if you are in the correct virtual environment. + +/// tip + +It's easy to activate one virtual environment, get one Python, and then **go to another project**. + +And the second project **wouldn't work** because you are using the **incorrect Python**, from a virtual environment for another project. + +It's useful being able to check what `python` is being used. 🤓 + +/// + +## Why Deactivate a Virtual Environment + +For example, you could be working on a project `philosophers-stone`, **activate that virtual environment**, install packages and work with that environment. + +And then you want to work on **another project** `prisoner-of-azkaban`. + +You go to that project: + +
+ +```console +$ cd ~/code/prisoner-of-azkaban +``` + +
+ +If you don't deactivate the virtual environment for `philosophers-stone`, when you run `python` in the terminal, it will try to use the Python from `philosophers-stone`. + +
+ +```console +$ cd ~/code/prisoner-of-azkaban + +$ python main.py + +// Error importing sirius, it's not installed 😱 +Traceback (most recent call last): + File "main.py", line 1, in + import sirius +``` + +
+ +But if you deactivate the virtual environment and activate the new one for `prisoner-of-askaban` then when you run `python` it will use the Python from the virtual environment in `prisoner-of-azkaban`. + +
+ +```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 🐺 +``` + +
+ +## Alternatives + +This is a simple guide to get you started and teach you how everything works **underneath**. + +There are many **alternatives** to managing virtual environments, package dependencies (requirements), projects. + +Once you are ready and want to use a tool to **manage the entire project**, packages dependencies, virtual environments, etc. I would suggest you try uv. + +`uv` can do a lot of things, it can: + +* **Install Python** for you, including different versions +* Manage the **virtual environment** for your projects +* Install **packages** +* Manage package **dependencies and versions** for your project +* Make sure you have an **exact** set of packages and versions to install, including their dependencies, so that you can be sure that you can run your project in production exactly the same as in your computer while developing, this is called **locking** +* And many other things + +## Conclusion + +If you read and understood all this, now **you know much more** about virtual environments than many developers out there. 🤓 + +Knowing these details will most probably be useful in a future time when you are debugging something that seems complex, but you will know **how it all works underneath**. 😎 diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index d0527ca3c..6f1e12511 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -108,6 +108,8 @@ nav: - learn/index.md - python-types.md - async.md + - environment-variables.md + - virtual-environments.md - Tutorial - User Guide: - tutorial/index.md - tutorial/first-steps.md From d0ce9d2bdf7f3c78b6f193288b9925b952da27c9 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 22 Aug 2024 00:47:57 +0000 Subject: [PATCH 21/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 12f1f50cd..a8bbcc3b7 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,7 @@ hide: ### Docs +* 📝 Add docs about Environment Variables and Virtual Environments. PR [#12054](https://github.com/fastapi/fastapi/pull/12054) by [@tiangolo](https://github.com/tiangolo). * 📝 Add Asyncer mention in async docs. PR [#12037](https://github.com/fastapi/fastapi/pull/12037) by [@tiangolo](https://github.com/tiangolo). * 📝 Move the Features docs to the top level to improve the main page menu. PR [#12036](https://github.com/fastapi/fastapi/pull/12036) by [@tiangolo](https://github.com/tiangolo). * ✏️ Fix import typo in reference example for `Security`. PR [#11168](https://github.com/fastapi/fastapi/pull/11168) by [@0shah0](https://github.com/0shah0). From 8f037167571ca60f87677594418fc68a05db6a9f Mon Sep 17 00:00:00 2001 From: Aymen Date: Sat, 24 Aug 2024 04:16:23 +0100 Subject: [PATCH 22/88] =?UTF-8?q?=F0=9F=93=9D=20Fix=20a=20typo=20in=20virt?= =?UTF-8?q?ual=20environement=20page=20(#12064)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/virtual-environments.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/virtual-environments.md b/docs/en/docs/virtual-environments.md index 3c4aa49c1..fcc72fbe7 100644 --- a/docs/en/docs/virtual-environments.md +++ b/docs/en/docs/virtual-environments.md @@ -558,7 +558,7 @@ The solution to the problems of having all the packages in the global environmen A virtual environment is a **directory**, very similar to the global one, where you can install the packages for a project. -This way, each project will have it's own virtual environment (`.venv` directory) with its own packages. +This way, each project will have its own virtual environment (`.venv` directory) with its own packages. ```mermaid flowchart TB From 6935fe8d38fe4befd0cc1cd8ddbbd836bb809497 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 24 Aug 2024 03:16:48 +0000 Subject: [PATCH 23/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a8bbcc3b7..8059de05d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,7 @@ hide: ### Docs +* 📝 Fix a typo in virtual environement page. PR [#12064](https://github.com/fastapi/fastapi/pull/12064) by [@aymenkrifa](https://github.com/aymenkrifa). * 📝 Add docs about Environment Variables and Virtual Environments. PR [#12054](https://github.com/fastapi/fastapi/pull/12054) by [@tiangolo](https://github.com/tiangolo). * 📝 Add Asyncer mention in async docs. PR [#12037](https://github.com/fastapi/fastapi/pull/12037) by [@tiangolo](https://github.com/tiangolo). * 📝 Move the Features docs to the top level to improve the main page menu. PR [#12036](https://github.com/fastapi/fastapi/pull/12036) by [@tiangolo](https://github.com/tiangolo). From 22bf988dfb085f45449bc137401af0105a86cdf5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Fri, 23 Aug 2024 22:48:20 -0500 Subject: [PATCH 24/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 8059de05d..c872f59e9 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,7 +14,7 @@ hide: ### Docs -* 📝 Fix a typo in virtual environement page. PR [#12064](https://github.com/fastapi/fastapi/pull/12064) by [@aymenkrifa](https://github.com/aymenkrifa). +* 📝 Fix a typo in `docs/en/docs/virtual-environments.md`. PR [#12064](https://github.com/fastapi/fastapi/pull/12064) by [@aymenkrifa](https://github.com/aymenkrifa). * 📝 Add docs about Environment Variables and Virtual Environments. PR [#12054](https://github.com/fastapi/fastapi/pull/12054) by [@tiangolo](https://github.com/tiangolo). * 📝 Add Asyncer mention in async docs. PR [#12037](https://github.com/fastapi/fastapi/pull/12037) by [@tiangolo](https://github.com/tiangolo). * 📝 Move the Features docs to the top level to improve the main page menu. PR [#12036](https://github.com/fastapi/fastapi/pull/12036) by [@tiangolo](https://github.com/tiangolo). @@ -36,7 +36,7 @@ hide: * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/request_file.md`. PR [#12018](https://github.com/fastapi/fastapi/pull/12018) by [@Joao-Pedro-P-Holanda](https://github.com/Joao-Pedro-P-Holanda). * 🌐 Add Japanese translation for `docs/ja/docs/learn/index.md`. PR [#11592](https://github.com/fastapi/fastapi/pull/11592) by [@ukwhatn](https://github.com/ukwhatn). * 📝 Update Spanish translation docs for consistency. PR [#12044](https://github.com/fastapi/fastapi/pull/12044) by [@alejsdev](https://github.com/alejsdev). -* 🌐 Update docs about dependencies with yield. PR [#12028](https://github.com/fastapi/fastapi/pull/12028) by [@xuvjso](https://github.com/xuvjso). +* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/dependencies/dependencies-with-yield.md`. PR [#12028](https://github.com/fastapi/fastapi/pull/12028) by [@xuvjso](https://github.com/xuvjso). * 📝 Update FastAPI People, do not translate to have the most recent info. PR [#12034](https://github.com/fastapi/fastapi/pull/12034) by [@tiangolo](https://github.com/tiangolo). * 🌐 Update Urdu translation for `docs/ur/docs/benchmarks.md`. PR [#10046](https://github.com/fastapi/fastapi/pull/10046) by [@AhsanSheraz](https://github.com/AhsanSheraz). From 3a4ac2467594d0ccad92ecfb7f7f10ffa5d1d992 Mon Sep 17 00:00:00 2001 From: Pastukhov Nikita Date: Sat, 24 Aug 2024 22:09:52 +0300 Subject: [PATCH 25/88] =?UTF-8?q?=F0=9F=90=9B=20Ensure=20that=20`app.inclu?= =?UTF-8?q?de=5Frouter`=20merges=20nested=20lifespans=20(#9630)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Marcelo Trylesinski Co-authored-by: Sebastián Ramírez --- fastapi/routing.py | 27 +++++++- tests/test_router_events.py | 135 +++++++++++++++++++++++++++++++++++- 2 files changed, 158 insertions(+), 4 deletions(-) diff --git a/fastapi/routing.py b/fastapi/routing.py index 2e7959f3d..49f1b6013 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -3,14 +3,16 @@ import dataclasses import email.message import inspect import json -from contextlib import AsyncExitStack +from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Any, + AsyncIterator, Callable, Coroutine, Dict, List, + Mapping, Optional, Sequence, Set, @@ -67,7 +69,7 @@ from starlette.routing import ( websocket_session, ) from starlette.routing import Mount as Mount # noqa -from starlette.types import ASGIApp, Lifespan, Scope +from starlette.types import AppType, ASGIApp, Lifespan, Scope from starlette.websockets import WebSocket from typing_extensions import Annotated, Doc, deprecated @@ -119,6 +121,23 @@ def _prepare_response_content( return res +def _merge_lifespan_context( + original_context: Lifespan[Any], nested_context: Lifespan[Any] +) -> Lifespan[Any]: + @asynccontextmanager + async def merged_lifespan( + app: AppType, + ) -> AsyncIterator[Optional[Mapping[str, Any]]]: + async with original_context(app) as maybe_original_state: + async with nested_context(app) as maybe_nested_state: + if maybe_nested_state is None and maybe_original_state is None: + yield None # old ASGI compatibility + else: + yield {**(maybe_nested_state or {}), **(maybe_original_state or {})} + + return merged_lifespan # type: ignore[return-value] + + async def serialize_response( *, field: Optional[ModelField] = None, @@ -1308,6 +1327,10 @@ class APIRouter(routing.Router): self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) + self.lifespan_context = _merge_lifespan_context( + self.lifespan_context, + router.lifespan_context, + ) def get( self, diff --git a/tests/test_router_events.py b/tests/test_router_events.py index 1b9de18ae..dd7ff3314 100644 --- a/tests/test_router_events.py +++ b/tests/test_router_events.py @@ -1,8 +1,8 @@ from contextlib import asynccontextmanager -from typing import AsyncGenerator, Dict +from typing import AsyncGenerator, Dict, Union import pytest -from fastapi import APIRouter, FastAPI +from fastapi import APIRouter, FastAPI, Request from fastapi.testclient import TestClient from pydantic import BaseModel @@ -109,3 +109,134 @@ def test_app_lifespan_state(state: State) -> None: assert response.json() == {"message": "Hello World"} assert state.app_startup is True assert state.app_shutdown is True + + +def test_router_nested_lifespan_state(state: State) -> None: + @asynccontextmanager + async def lifespan(app: FastAPI) -> AsyncGenerator[Dict[str, bool], None]: + state.app_startup = True + yield {"app": True} + state.app_shutdown = True + + @asynccontextmanager + async def router_lifespan(app: FastAPI) -> AsyncGenerator[Dict[str, bool], None]: + state.router_startup = True + yield {"router": True} + state.router_shutdown = True + + @asynccontextmanager + async def subrouter_lifespan(app: FastAPI) -> AsyncGenerator[Dict[str, bool], None]: + state.sub_router_startup = True + yield {"sub_router": True} + state.sub_router_shutdown = True + + sub_router = APIRouter(lifespan=subrouter_lifespan) + + router = APIRouter(lifespan=router_lifespan) + router.include_router(sub_router) + + app = FastAPI(lifespan=lifespan) + app.include_router(router) + + @app.get("/") + def main(request: Request) -> Dict[str, str]: + assert request.state.app + assert request.state.router + assert request.state.sub_router + return {"message": "Hello World"} + + assert state.app_startup is False + assert state.router_startup is False + assert state.sub_router_startup is False + assert state.app_shutdown is False + assert state.router_shutdown is False + assert state.sub_router_shutdown is False + + with TestClient(app) as client: + assert state.app_startup is True + assert state.router_startup is True + assert state.sub_router_startup is True + assert state.app_shutdown is False + assert state.router_shutdown is False + assert state.sub_router_shutdown is False + response = client.get("/") + assert response.status_code == 200, response.text + assert response.json() == {"message": "Hello World"} + + assert state.app_startup is True + assert state.router_startup is True + assert state.sub_router_startup is True + assert state.app_shutdown is True + assert state.router_shutdown is True + assert state.sub_router_shutdown is True + + +def test_router_nested_lifespan_state_overriding_by_parent() -> None: + @asynccontextmanager + async def lifespan( + app: FastAPI, + ) -> AsyncGenerator[Dict[str, Union[str, bool]], None]: + yield { + "app_specific": True, + "overridden": "app", + } + + @asynccontextmanager + async def router_lifespan( + app: FastAPI, + ) -> AsyncGenerator[Dict[str, Union[str, bool]], None]: + yield { + "router_specific": True, + "overridden": "router", # should override parent + } + + router = APIRouter(lifespan=router_lifespan) + app = FastAPI(lifespan=lifespan) + app.include_router(router) + + with TestClient(app) as client: + assert client.app_state == { + "app_specific": True, + "router_specific": True, + "overridden": "app", + } + + +def test_merged_no_return_lifespans_return_none() -> None: + @asynccontextmanager + async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]: + yield + + @asynccontextmanager + async def router_lifespan(app: FastAPI) -> AsyncGenerator[None, None]: + yield + + router = APIRouter(lifespan=router_lifespan) + app = FastAPI(lifespan=lifespan) + app.include_router(router) + + with TestClient(app) as client: + assert not client.app_state + + +def test_merged_mixed_state_lifespans() -> None: + @asynccontextmanager + async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]: + yield + + @asynccontextmanager + async def router_lifespan(app: FastAPI) -> AsyncGenerator[Dict[str, bool], None]: + yield {"router": True} + + @asynccontextmanager + async def sub_router_lifespan(app: FastAPI) -> AsyncGenerator[None, None]: + yield + + sub_router = APIRouter(lifespan=sub_router_lifespan) + router = APIRouter(lifespan=router_lifespan) + app = FastAPI(lifespan=lifespan) + router.include_router(sub_router) + app.include_router(router) + + with TestClient(app) as client: + assert client.app_state == {"router": True} From 48b36f26d83d607a044866633068dbf46e723e0f Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 24 Aug 2024 19:10:14 +0000 Subject: [PATCH 26/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index c872f59e9..d9cefc989 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Fixes + +* 🐛 Ensure that `app.include_router` merges nested lifespans. PR [#9630](https://github.com/fastapi/fastapi/pull/9630) by [@Lancetnik](https://github.com/Lancetnik). + ### Refactors * 🎨 Fix typing annotation for semi-internal `FastAPI.add_api_route()`. PR [#10240](https://github.com/fastapi/fastapi/pull/10240) by [@ordinary-jamie](https://github.com/ordinary-jamie). From 51b625e127982f626886d467122ef85d5772d1db Mon Sep 17 00:00:00 2001 From: Giunio <59511892+giunio-prc@users.noreply.github.com> Date: Sat, 24 Aug 2024 21:27:37 +0200 Subject: [PATCH 27/88] =?UTF-8?q?=F0=9F=90=9B=20Fix=20`allow=5Finf=5Fnan`?= =?UTF-8?q?=20option=20for=20Param=20and=20Body=20classes=20(#11867)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: svlandeg --- fastapi/params.py | 4 +- tests/test_allow_inf_nan_in_enforcing.py | 83 ++++++++++++++++++++++++ 2 files changed, 85 insertions(+), 2 deletions(-) create mode 100644 tests/test_allow_inf_nan_in_enforcing.py diff --git a/fastapi/params.py b/fastapi/params.py index 860146531..cc2a5c13c 100644 --- a/fastapi/params.py +++ b/fastapi/params.py @@ -91,7 +91,7 @@ class Param(FieldInfo): max_length=max_length, discriminator=discriminator, multiple_of=multiple_of, - allow_nan=allow_inf_nan, + allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, **extra, @@ -547,7 +547,7 @@ class Body(FieldInfo): max_length=max_length, discriminator=discriminator, multiple_of=multiple_of, - allow_nan=allow_inf_nan, + allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, **extra, diff --git a/tests/test_allow_inf_nan_in_enforcing.py b/tests/test_allow_inf_nan_in_enforcing.py new file mode 100644 index 000000000..9e855fdf8 --- /dev/null +++ b/tests/test_allow_inf_nan_in_enforcing.py @@ -0,0 +1,83 @@ +import pytest +from fastapi import Body, FastAPI, Query +from fastapi.testclient import TestClient +from typing_extensions import Annotated + +app = FastAPI() + + +@app.post("/") +async def get( + x: Annotated[float, Query(allow_inf_nan=True)] = 0, + y: Annotated[float, Query(allow_inf_nan=False)] = 0, + z: Annotated[float, Query()] = 0, + b: Annotated[float, Body(allow_inf_nan=False)] = 0, +) -> str: + return "OK" + + +client = TestClient(app) + + +@pytest.mark.parametrize( + "value,code", + [ + ("-1", 200), + ("inf", 200), + ("-inf", 200), + ("nan", 200), + ("0", 200), + ("342", 200), + ], +) +def test_allow_inf_nan_param_true(value: str, code: int): + response = client.post(f"/?x={value}") + assert response.status_code == code, response.text + + +@pytest.mark.parametrize( + "value,code", + [ + ("-1", 200), + ("inf", 422), + ("-inf", 422), + ("nan", 422), + ("0", 200), + ("342", 200), + ], +) +def test_allow_inf_nan_param_false(value: str, code: int): + response = client.post(f"/?y={value}") + assert response.status_code == code, response.text + + +@pytest.mark.parametrize( + "value,code", + [ + ("-1", 200), + ("inf", 200), + ("-inf", 200), + ("nan", 200), + ("0", 200), + ("342", 200), + ], +) +def test_allow_inf_nan_param_default(value: str, code: int): + response = client.post(f"/?z={value}") + assert response.status_code == code, response.text + + +@pytest.mark.parametrize( + "value,code", + [ + ("-1", 200), + ("inf", 422), + ("-inf", 422), + ("nan", 422), + ("0", 200), + ("342", 200), + ], +) +def test_allow_inf_nan_body(value: str, code: int): + response = client.post("/", json=value) + assert response.status_code == code, response.text From b69a9f3b6f822e71be275ca20347a0ab3dfe99e8 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 24 Aug 2024 19:27:59 +0000 Subject: [PATCH 28/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d9cefc989..28d430ab0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Fixes +* 🐛 Fix `allow_inf_nan` option for Param and Body classes. PR [#11867](https://github.com/fastapi/fastapi/pull/11867) by [@giunio-prc](https://github.com/giunio-prc). * 🐛 Ensure that `app.include_router` merges nested lifespans. PR [#9630](https://github.com/fastapi/fastapi/pull/9630) by [@Lancetnik](https://github.com/Lancetnik). ### Refactors From d00af00d3f15e9a963e2f1baf8f9b4c8357f6f66 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 24 Aug 2024 14:34:50 -0500 Subject: [PATCH 29/88] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.112.?= =?UTF-8?q?2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 2 ++ fastapi/__init__.py | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 28d430ab0..2af28ae05 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,8 @@ hide: ## Latest Changes +## 0.112.2 + ### Fixes * 🐛 Fix `allow_inf_nan` option for Param and Body classes. PR [#11867](https://github.com/fastapi/fastapi/pull/11867) by [@giunio-prc](https://github.com/giunio-prc). diff --git a/fastapi/__init__.py b/fastapi/__init__.py index 0b79d45ef..ac2508d89 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.112.1" +__version__ = "0.112.2" from starlette import status as status From 9656895b60e85aeee82a599dc601813ba815b0df Mon Sep 17 00:00:00 2001 From: GPla <36087062+GPla@users.noreply.github.com> Date: Sat, 24 Aug 2024 22:04:30 +0200 Subject: [PATCH 30/88] =?UTF-8?q?=F0=9F=93=9D=20Add=20note=20in=20Docker?= =?UTF-8?q?=20docs=20about=20ensuring=20graceful=20shutdowns=20and=20lifes?= =?UTF-8?q?pan=20events=20with=20`CMD`=20exec=20form=20(#11960)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: svlandeg Co-authored-by: Sebastián Ramírez --- docs/en/docs/deployment/docker.md | 32 +++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/docs/en/docs/deployment/docker.md b/docs/en/docs/deployment/docker.md index 253e25fe5..ab1c2201f 100644 --- a/docs/en/docs/deployment/docker.md +++ b/docs/en/docs/deployment/docker.md @@ -232,6 +232,38 @@ Review what each line does by clicking each number bubble in the code. 👆 /// +/// warning + +Make sure to **always** use the **exec form** of the `CMD` instruction, as explained below. + +/// + +#### Use `CMD` - Exec Form + +The `CMD` Docker instruction can be written using two forms: + +✅ **Exec** form: + +```Dockerfile +# ✅ Do this +CMD ["fastapi", "run", "app/main.py", "--port", "80"] +``` + +⛔️ **Shell** form: + +```Dockerfile +# ⛔️ Don't do this +CMD fastapi run app/main.py --port 80 +``` + +Make sure to always use the **exec** form to ensure that FastAPI can shutdown gracefully and [lifespan events](../advanced/events.md){.internal-link target=_blank} are triggered. + +You can read more about it in the Docker docs for shell and exec form. + +This can be quite noticeable when using `docker compose`. See this Docker Compose FAQ section for more technical details: Why do my services take 10 seconds to recreate or stop?. + +#### Directory Structure + You should now have a directory structure like: ``` From e4727ed20aa83604a9d28d397e4ce4994f8b9640 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 24 Aug 2024 20:04:51 +0000 Subject: [PATCH 31/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2af28ae05..83d992b8b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Docs + +* 📝 Add note in Docker docs about ensuring graceful shutdowns and lifespan events with `CMD` exec form. PR [#11960](https://github.com/fastapi/fastapi/pull/11960) by [@GPla](https://github.com/GPla). + ## 0.112.2 ### Fixes From 6aa44a85a211f5175b2b45d0dbf23128f6be0627 Mon Sep 17 00:00:00 2001 From: Sofie Van Landeghem Date: Sat, 24 Aug 2024 23:52:09 +0200 Subject: [PATCH 32/88] =?UTF-8?q?=F0=9F=93=9D=20Fix=20minor=20typos=20and?= =?UTF-8?q?=20issues=20in=20the=20documentation=20(#12063)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- docs/en/docs/advanced/response-directly.md | 2 +- docs/en/docs/async.md | 2 +- docs/en/docs/index.md | 2 +- docs/en/docs/python-types.md | 2 +- docs/en/docs/tutorial/bigger-applications.md | 4 ++-- docs/en/docs/tutorial/body-multiple-params.md | 2 +- docs/en/docs/tutorial/body-updates.md | 2 +- docs/en/docs/tutorial/body.md | 2 +- docs/en/docs/tutorial/cors.md | 2 +- .../docs/tutorial/dependencies/classes-as-dependencies.md | 2 +- docs/en/docs/tutorial/extra-data-types.md | 2 +- docs/en/docs/tutorial/handling-errors.md | 4 ++-- docs/en/docs/tutorial/index.md | 2 +- docs/en/docs/tutorial/middleware.md | 2 +- docs/en/docs/tutorial/query-params-str-validations.md | 6 +++--- docs/en/docs/tutorial/schema-extra-example.md | 2 +- docs/en/docs/tutorial/security/first-steps.md | 2 +- docs/en/docs/tutorial/security/get-current-user.md | 2 +- 19 files changed, 23 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 889a89ed7..ec7a95497 100644 --- a/README.md +++ b/README.md @@ -394,7 +394,7 @@ Coming back to the previous code example, **FastAPI** will: * Check if there is an optional query parameter named `q` (as in `http://127.0.0.1:8000/items/foo?q=somequery`) for `GET` requests. * As the `q` parameter is declared with `= None`, it is optional. * Without the `None` it would be required (as is the body in the case with `PUT`). -* For `PUT` requests to `/items/{item_id}`, Read the body as JSON: +* For `PUT` requests to `/items/{item_id}`, read the body as JSON: * Check that it has a required attribute `name` that should be a `str`. * Check that it has a required attribute `price` that has to be a `float`. * Check that it has an optional attribute `is_offer`, that should be a `bool`, if present. diff --git a/docs/en/docs/advanced/response-directly.md b/docs/en/docs/advanced/response-directly.md index 73071ed1b..2251659c5 100644 --- a/docs/en/docs/advanced/response-directly.md +++ b/docs/en/docs/advanced/response-directly.md @@ -28,7 +28,7 @@ This gives you a lot of flexibility. You can return any data type, override any ## Using the `jsonable_encoder` in a `Response` -Because **FastAPI** doesn't do any change to a `Response` you return, you have to make sure it's contents are ready for it. +Because **FastAPI** doesn't do any change to a `Response` you return, you have to make sure its contents are ready for it. For example, you cannot put a Pydantic model in a `JSONResponse` without first converting it to a `dict` with all the data types (like `datetime`, `UUID`, etc) converted to JSON-compatible types. diff --git a/docs/en/docs/async.md b/docs/en/docs/async.md index 7cf4af627..752a5c247 100644 --- a/docs/en/docs/async.md +++ b/docs/en/docs/async.md @@ -292,7 +292,7 @@ For example: ### Concurrency + Parallelism: Web + Machine Learning -With **FastAPI** you can take the advantage of concurrency that is very common for web development (the same main attraction of NodeJS). +With **FastAPI** you can take advantage of concurrency that is very common for web development (the same main attraction of NodeJS). But you can also exploit the benefits of parallelism and multiprocessing (having multiple processes running in parallel) for **CPU bound** workloads like those in Machine Learning systems. diff --git a/docs/en/docs/index.md b/docs/en/docs/index.md index ac4f4d00f..3ed3d7bf6 100644 --- a/docs/en/docs/index.md +++ b/docs/en/docs/index.md @@ -390,7 +390,7 @@ Coming back to the previous code example, **FastAPI** will: * Check if there is an optional query parameter named `q` (as in `http://127.0.0.1:8000/items/foo?q=somequery`) for `GET` requests. * As the `q` parameter is declared with `= None`, it is optional. * Without the `None` it would be required (as is the body in the case with `PUT`). -* For `PUT` requests to `/items/{item_id}`, Read the body as JSON: +* For `PUT` requests to `/items/{item_id}`, read the body as JSON: * Check that it has a required attribute `name` that should be a `str`. * Check that it has a required attribute `price` that has to be a `float`. * Check that it has an optional attribute `is_offer`, that should be a `bool`, if present. diff --git a/docs/en/docs/python-types.md b/docs/en/docs/python-types.md index 4ed1fc680..6994adb5f 100644 --- a/docs/en/docs/python-types.md +++ b/docs/en/docs/python-types.md @@ -324,7 +324,7 @@ In Python 3.6 and above (including Python 3.10) you can declare it by importing {!../../../docs_src/python_types/tutorial009.py!} ``` -Using `Optional[str]` instead of just `str` will let the editor help you detecting errors where you could be assuming that a value is always a `str`, when it could actually be `None` too. +Using `Optional[str]` instead of just `str` will let the editor help you detect errors where you could be assuming that a value is always a `str`, when it could actually be `None` too. `Optional[Something]` is actually a shortcut for `Union[Something, None]`, they are equivalent. diff --git a/docs/en/docs/tutorial/bigger-applications.md b/docs/en/docs/tutorial/bigger-applications.md index 97f6b205b..230f9c08c 100644 --- a/docs/en/docs/tutorial/bigger-applications.md +++ b/docs/en/docs/tutorial/bigger-applications.md @@ -1,6 +1,6 @@ # Bigger Applications - Multiple Files -If you are building an application or a web API, it's rarely the case that you can put everything on a single file. +If you are building an application or a web API, it's rarely the case that you can put everything in a single file. **FastAPI** provides a convenience tool to structure your application while keeping all the flexibility. @@ -478,7 +478,7 @@ We can declare all that without having to modify the original `APIRouter` by pas {!../../../docs_src/bigger_applications/app/main.py!} ``` -That way, the original `APIRouter` will keep unmodified, so we can still share that same `app/internal/admin.py` file with other projects in the organization. +That way, the original `APIRouter` will stay unmodified, so we can still share that same `app/internal/admin.py` file with other projects in the organization. The result is that in our app, each of the *path operations* from the `admin` module will have: diff --git a/docs/en/docs/tutorial/body-multiple-params.md b/docs/en/docs/tutorial/body-multiple-params.md index 511fb358e..d63cd2529 100644 --- a/docs/en/docs/tutorial/body-multiple-params.md +++ b/docs/en/docs/tutorial/body-multiple-params.md @@ -97,7 +97,7 @@ But you can also declare multiple body parameters, e.g. `item` and `user`: //// -In this case, **FastAPI** will notice that there are more than one body parameters in the function (two parameters that are Pydantic models). +In this case, **FastAPI** will notice that there is more than one body parameter in the function (there are two parameters that are Pydantic models). So, it will then use the parameter names as keys (field names) in the body, and expect a body like: diff --git a/docs/en/docs/tutorial/body-updates.md b/docs/en/docs/tutorial/body-updates.md index 261f44d33..3257f9a08 100644 --- a/docs/en/docs/tutorial/body-updates.md +++ b/docs/en/docs/tutorial/body-updates.md @@ -155,7 +155,7 @@ In summary, to apply partial updates you would: * Put that data in a Pydantic model. * Generate a `dict` without default values from the input model (using `exclude_unset`). * This way you can update only the values actually set by the user, instead of overriding values already stored with default values in your model. -* Create a copy of the stored model, updating it's attributes with the received partial updates (using the `update` parameter). +* Create a copy of the stored model, updating its attributes with the received partial updates (using the `update` parameter). * Convert the copied model to something that can be stored in your DB (for example, using the `jsonable_encoder`). * This is comparable to using the model's `.model_dump()` method again, but it makes sure (and converts) the values to data types that can be converted to JSON, for example, `datetime` to `str`. * Save the data to your DB. diff --git a/docs/en/docs/tutorial/body.md b/docs/en/docs/tutorial/body.md index 608b50dbb..83f08ce84 100644 --- a/docs/en/docs/tutorial/body.md +++ b/docs/en/docs/tutorial/body.md @@ -123,7 +123,7 @@ The JSON Schemas of your models will be part of your OpenAPI generated schema, a -And will be also used in the API docs inside each *path operation* that needs them: +And will also be used in the API docs inside each *path operation* that needs them: diff --git a/docs/en/docs/tutorial/cors.md b/docs/en/docs/tutorial/cors.md index fd329e138..7dd0a5df5 100644 --- a/docs/en/docs/tutorial/cors.md +++ b/docs/en/docs/tutorial/cors.md @@ -40,7 +40,7 @@ You can configure it in your **FastAPI** application using the `CORSMiddleware`. * Create a list of allowed origins (as strings). * Add it as a "middleware" to your **FastAPI** application. -You can also specify if your backend allows: +You can also specify whether your backend allows: * Credentials (Authorization headers, Cookies, etc). * Specific HTTP methods (`POST`, `PUT`) or all of them with the wildcard `"*"`. diff --git a/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md b/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md index a392672bb..b3394f14e 100644 --- a/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md +++ b/docs/en/docs/tutorial/dependencies/classes-as-dependencies.md @@ -381,7 +381,7 @@ The last `CommonQueryParams`, in: ...is what **FastAPI** will actually use to know what is the dependency. -From it is that FastAPI will extract the declared parameters and that is what FastAPI will actually call. +It is from this one that FastAPI will extract the declared parameters and that is what FastAPI will actually call. --- diff --git a/docs/en/docs/tutorial/extra-data-types.md b/docs/en/docs/tutorial/extra-data-types.md index 849dee41f..3009acaf3 100644 --- a/docs/en/docs/tutorial/extra-data-types.md +++ b/docs/en/docs/tutorial/extra-data-types.md @@ -49,7 +49,7 @@ Here are some of the additional data types you can use: * `Decimal`: * Standard Python `Decimal`. * In requests and responses, handled the same as a `float`. -* You can check all the valid pydantic data types here: Pydantic data types. +* You can check all the valid Pydantic data types here: Pydantic data types. ## Example diff --git a/docs/en/docs/tutorial/handling-errors.md b/docs/en/docs/tutorial/handling-errors.md index ca3cff661..14a3cf998 100644 --- a/docs/en/docs/tutorial/handling-errors.md +++ b/docs/en/docs/tutorial/handling-errors.md @@ -176,7 +176,7 @@ These are technical details that you might skip if it's not important for you no **FastAPI** uses it so that, if you use a Pydantic model in `response_model`, and your data has an error, you will see the error in your log. -But the client/user will not see it. Instead, the client will receive an "Internal Server Error" with a HTTP status code `500`. +But the client/user will not see it. Instead, the client will receive an "Internal Server Error" with an HTTP status code `500`. It should be this way because if you have a Pydantic `ValidationError` in your *response* or anywhere in your code (not in the client's *request*), it's actually a bug in your code. @@ -262,7 +262,7 @@ from starlette.exceptions import HTTPException as StarletteHTTPException ### Reuse **FastAPI**'s exception handlers -If you want to use the exception along with the same default exception handlers from **FastAPI**, You can import and reuse the default exception handlers from `fastapi.exception_handlers`: +If you want to use the exception along with the same default exception handlers from **FastAPI**, you can import and reuse the default exception handlers from `fastapi.exception_handlers`: ```Python hl_lines="2-5 15 21" {!../../../docs_src/handling_errors/tutorial006.py!} diff --git a/docs/en/docs/tutorial/index.md b/docs/en/docs/tutorial/index.md index 386fe5de9..bf613aace 100644 --- a/docs/en/docs/tutorial/index.md +++ b/docs/en/docs/tutorial/index.md @@ -95,7 +95,7 @@ If you don't want to have those optional dependencies, you can instead install ` There is also an **Advanced User Guide** that you can read later after this **Tutorial - User guide**. -The **Advanced User Guide**, builds on this, uses the same concepts, and teaches you some extra features. +The **Advanced User Guide** builds on this one, uses the same concepts, and teaches you some extra features. But you should first read the **Tutorial - User Guide** (what you are reading right now). diff --git a/docs/en/docs/tutorial/middleware.md b/docs/en/docs/tutorial/middleware.md index f0b3faf3b..06fb3f504 100644 --- a/docs/en/docs/tutorial/middleware.md +++ b/docs/en/docs/tutorial/middleware.md @@ -29,7 +29,7 @@ The middleware function receives: * A function `call_next` that will receive the `request` as a parameter. * This function will pass the `request` to the corresponding *path operation*. * Then it returns the `response` generated by the corresponding *path operation*. -* You can then modify further the `response` before returning it. +* You can then further modify the `response` before returning it. ```Python hl_lines="8-9 11 14" {!../../../docs_src/middleware/tutorial001.py!} diff --git a/docs/en/docs/tutorial/query-params-str-validations.md b/docs/en/docs/tutorial/query-params-str-validations.md index 859242d93..dd101a2a6 100644 --- a/docs/en/docs/tutorial/query-params-str-validations.md +++ b/docs/en/docs/tutorial/query-params-str-validations.md @@ -273,7 +273,7 @@ The **default** value of the **function parameter** is the **actual default** va You could **call** that same function in **other places** without FastAPI, and it would **work as expected**. If there's a **required** parameter (without a default value), your **editor** will let you know with an error, **Python** will also complain if you run it without passing the required parameter. -When you don't use `Annotated` and instead use the **(old) default value style**, if you call that function without FastAPI in **other place**, you have to **remember** to pass the arguments to the function for it to work correctly, otherwise the values will be different from what you expect (e.g. `QueryInfo` or something similar instead of `str`). And your editor won't complain, and Python won't complain running that function, only when the operations inside error out. +When you don't use `Annotated` and instead use the **(old) default value style**, if you call that function without FastAPI in **other places**, you have to **remember** to pass the arguments to the function for it to work correctly, otherwise the values will be different from what you expect (e.g. `QueryInfo` or something similar instead of `str`). And your editor won't complain, and Python won't complain running that function, only when the operations inside error out. Because `Annotated` can have more than one metadata annotation, you could now even use the same function with other tools, like Typer. 🚀 @@ -645,7 +645,7 @@ Remember that in most of the cases, when something is required, you can simply o ## 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 other way, to receive 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. For example, to declare a query parameter `q` that can appear multiple times in the URL, you can write: @@ -1182,4 +1182,4 @@ Validations specific for strings: In these examples you saw how to declare validations for `str` values. -See the next chapters to see how to declare validations for other types, like numbers. +See the next chapters to learn how to declare validations for other types, like numbers. diff --git a/docs/en/docs/tutorial/schema-extra-example.md b/docs/en/docs/tutorial/schema-extra-example.md index 70745b048..20dee3a4f 100644 --- a/docs/en/docs/tutorial/schema-extra-example.md +++ b/docs/en/docs/tutorial/schema-extra-example.md @@ -347,7 +347,7 @@ If the ideas above already work for you, that might be enough, and you probably Before OpenAPI 3.1.0, OpenAPI used an older and modified version of **JSON Schema**. -JSON Schema didn't have `examples`, so OpenAPI added it's own `example` field to its own modified version. +JSON Schema didn't have `examples`, so OpenAPI added its own `example` field to its own modified version. OpenAPI also added `example` and `examples` fields to other parts of the specification: diff --git a/docs/en/docs/tutorial/security/first-steps.md b/docs/en/docs/tutorial/security/first-steps.md index 4bd026caf..d1fe0163e 100644 --- a/docs/en/docs/tutorial/security/first-steps.md +++ b/docs/en/docs/tutorial/security/first-steps.md @@ -152,7 +152,7 @@ A "bearer" token is not the only option. But it's the best one for our use case. -And it might be the best for most use cases, unless you are an OAuth2 expert and know exactly why there's another option that suits better your needs. +And it might be the best for most use cases, unless you are an OAuth2 expert and know exactly why there's another option that better suits your needs. In that case, **FastAPI** also provides you with the tools to build it. diff --git a/docs/en/docs/tutorial/security/get-current-user.md b/docs/en/docs/tutorial/security/get-current-user.md index 6f3bf3944..7faaa3e13 100644 --- a/docs/en/docs/tutorial/security/get-current-user.md +++ b/docs/en/docs/tutorial/security/get-current-user.md @@ -316,7 +316,7 @@ And you can make it as complex as you want. And still, have it written only once But you can have thousands of endpoints (*path operations*) using the same security system. -And all of them (or any portion of them that you want) can take the advantage of re-using these dependencies or any other dependencies you create. +And all of them (or any portion of them that you want) can take advantage of re-using these dependencies or any other dependencies you create. And all these thousands of *path operations* can be as small as 3 lines: From d8e526c1db42b9049a3c9a26f2ac91109c896812 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 24 Aug 2024 21:52:29 +0000 Subject: [PATCH 33/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 83d992b8b..2218b352b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Fix minor typos and issues in the documentation. PR [#12063](https://github.com/fastapi/fastapi/pull/12063) by [@svlandeg](https://github.com/svlandeg). * 📝 Add note in Docker docs about ensuring graceful shutdowns and lifespan events with `CMD` exec form. PR [#11960](https://github.com/fastapi/fastapi/pull/11960) by [@GPla](https://github.com/GPla). ## 0.112.2 From c692176d4288e8b8f6f404c7c15aaab74083a6e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 24 Aug 2024 19:01:04 -0500 Subject: [PATCH 34/88] =?UTF-8?q?=F0=9F=93=9D=20Clarify=20`response=5Fclas?= =?UTF-8?q?s`=20parameter,=20validations,=20and=20returning=20a=20response?= =?UTF-8?q?=20directly=20(#12067)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/advanced/custom-response.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/en/docs/advanced/custom-response.md b/docs/en/docs/advanced/custom-response.md index 8a6555dba..79f755815 100644 --- a/docs/en/docs/advanced/custom-response.md +++ b/docs/en/docs/advanced/custom-response.md @@ -4,9 +4,9 @@ By default, **FastAPI** will return the responses using `JSONResponse`. You can override it by returning a `Response` directly as seen in [Return a Response directly](response-directly.md){.internal-link target=_blank}. -But if you return a `Response` directly, the data won't be automatically converted, and the documentation won't be automatically generated (for example, including the specific "media type", in the HTTP header `Content-Type` as part of the generated OpenAPI). +But if you return a `Response` directly (or any subclass, like `JSONResponse`), the data won't be automatically converted (even if you declare a `response_model`), and the documentation won't be automatically generated (for example, including the specific "media type", in the HTTP header `Content-Type` as part of the generated OpenAPI). -But you can also declare the `Response` that you want to be used, in the *path operation decorator*. +But you can also declare the `Response` that you want to be used (e.g. any `Response` subclass), in the *path operation decorator* using the `response_class` parameter. The contents that you return from your *path operation function* will be put inside of that `Response`. From b5cbff9521c6c800aebf37d73a3532951db95bff Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 25 Aug 2024 00:01:26 +0000 Subject: [PATCH 35/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2218b352b..ac8f16f53 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Clarify `response_class` parameter, validations, and returning a response directly. PR [#12067](https://github.com/fastapi/fastapi/pull/12067) by [@tiangolo](https://github.com/tiangolo). * 📝 Fix minor typos and issues in the documentation. PR [#12063](https://github.com/fastapi/fastapi/pull/12063) by [@svlandeg](https://github.com/svlandeg). * 📝 Add note in Docker docs about ensuring graceful shutdowns and lifespan events with `CMD` exec form. PR [#11960](https://github.com/fastapi/fastapi/pull/11960) by [@GPla](https://github.com/GPla). From bd1b77548f0f1788c5ae0fbd8144f5139bdb959e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 24 Aug 2024 21:44:06 -0500 Subject: [PATCH 36/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20docs=20about=20se?= =?UTF-8?q?rving=20FastAPI:=20ASGI=20servers,=20Docker=20containers,=20etc?= =?UTF-8?q?.=20(#12069)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/advanced/sub-applications.md | 4 +- docs/en/docs/alternatives.md | 2 +- docs/en/docs/contributing.md | 2 +- docs/en/docs/deployment/concepts.md | 8 +- docs/en/docs/deployment/docker.md | 226 ++++--------------- docs/en/docs/deployment/manually.md | 89 +------- docs/en/docs/deployment/server-workers.md | 165 ++++++-------- docs/en/docs/deployment/versions.md | 2 +- docs/en/docs/tutorial/bigger-applications.md | 4 +- 9 files changed, 129 insertions(+), 373 deletions(-) diff --git a/docs/en/docs/advanced/sub-applications.md b/docs/en/docs/advanced/sub-applications.md index 8c52e091f..568a9deca 100644 --- a/docs/en/docs/advanced/sub-applications.md +++ b/docs/en/docs/advanced/sub-applications.md @@ -36,12 +36,12 @@ In this case, it will be mounted at the path `/subapi`: ### Check the automatic API docs -Now, run `uvicorn` with the main app, if your file is `main.py`, it would be: +Now, run the `fastapi` command with your file:
```console -$ uvicorn main:app --reload +$ fastapi dev main.py INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` diff --git a/docs/en/docs/alternatives.md b/docs/en/docs/alternatives.md index 2ad584c95..e98c0475a 100644 --- a/docs/en/docs/alternatives.md +++ b/docs/en/docs/alternatives.md @@ -474,7 +474,7 @@ It is the recommended server for Starlette and **FastAPI**. The main web server to run **FastAPI** applications. -You can combine it with Gunicorn, to have an asynchronous multi-process server. +You can also use the `--workers` command line option to have an asynchronous multi-process server. Check more details in the [Deployment](deployment/index.md){.internal-link target=_blank} section. diff --git a/docs/en/docs/contributing.md b/docs/en/docs/contributing.md index 91d5724a8..0dc07b89b 100644 --- a/docs/en/docs/contributing.md +++ b/docs/en/docs/contributing.md @@ -170,7 +170,7 @@ If you run the examples with, e.g.:
```console -$ uvicorn tutorial001:app --reload +$ fastapi dev tutorial001.py INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` diff --git a/docs/en/docs/deployment/concepts.md b/docs/en/docs/deployment/concepts.md index f917d18b3..69ee71a73 100644 --- a/docs/en/docs/deployment/concepts.md +++ b/docs/en/docs/deployment/concepts.md @@ -94,7 +94,7 @@ In most cases, when you create a web API, you want it to be **always running**, ### In a Remote Server -When you set up a remote server (a cloud server, a virtual machine, etc.) the simplest thing you can do is to use `fastapi run`, Uvicorn (or similar) manually, the same way you do when developing locally. +When you set up a remote server (a cloud server, a virtual machine, etc.) the simplest thing you can do is use `fastapi run` (which uses Uvicorn) or something similar, manually, the same way you do when developing locally. And it will work and will be useful **during development**. @@ -178,7 +178,7 @@ For example, this could be handled by: ## Replication - Processes and Memory -With a FastAPI application, using a server program like Uvicorn, running it once in **one process** can serve multiple clients concurrently. +With a FastAPI application, using a server program like the `fastapi` command that runs Uvicorn, running it once in **one process** can serve multiple clients concurrently. But in many cases, you will want to run several worker processes at the same time. @@ -232,9 +232,7 @@ The main constraint to consider is that there has to be a **single** component h Here are some possible combinations and strategies: -* **Gunicorn** managing **Uvicorn workers** - * Gunicorn would be the **process manager** listening on the **IP** and **port**, the replication would be by having **multiple Uvicorn worker processes**. -* **Uvicorn** managing **Uvicorn workers** +* **Uvicorn** with `--workers` * One Uvicorn **process manager** would listen on the **IP** and **port**, and it would start **multiple Uvicorn worker processes**. * **Kubernetes** and other distributed **container systems** * Something in the **Kubernetes** layer would listen on the **IP** and **port**. The replication would be by having **multiple containers**, each with **one Uvicorn process** running. diff --git a/docs/en/docs/deployment/docker.md b/docs/en/docs/deployment/docker.md index ab1c2201f..2d832a238 100644 --- a/docs/en/docs/deployment/docker.md +++ b/docs/en/docs/deployment/docker.md @@ -167,22 +167,22 @@ def read_item(item_id: int, q: Union[str, None] = None): Now in the same project directory create a file `Dockerfile` with: ```{ .dockerfile .annotate } -# (1) +# (1)! FROM python:3.9 -# (2) +# (2)! WORKDIR /code -# (3) +# (3)! COPY ./requirements.txt /code/requirements.txt -# (4) +# (4)! RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt -# (5) +# (5)! COPY ./app /code/app -# (6) +# (6)! CMD ["fastapi", "run", "app/main.py", "--port", "80"] ``` @@ -400,10 +400,10 @@ COPY ./requirements.txt /code/requirements.txt RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt -# (1) +# (1)! COPY ./main.py /code/ -# (2) +# (2)! CMD ["fastapi", "run", "main.py", "--port", "80"] ``` @@ -456,11 +456,11 @@ Without using containers, making applications run on startup and with restarts c ## Replication - Number of Processes -If you have a cluster of machines with **Kubernetes**, Docker Swarm Mode, Nomad, or another similar complex system to manage distributed containers on multiple machines, then you will probably want to **handle replication** at the **cluster level** instead of using a **process manager** (like Gunicorn with workers) in each container. +If you have a cluster of machines with **Kubernetes**, Docker Swarm Mode, Nomad, or another similar complex system to manage distributed containers on multiple machines, then you will probably want to **handle replication** at the **cluster level** instead of using a **process manager** (like Uvicorn with workers) in each container. One of those distributed container management systems like Kubernetes normally has some integrated way of handling **replication of containers** while still supporting **load balancing** for the incoming requests. All at the **cluster level**. -In those cases, you would probably want to build a **Docker image from scratch** as [explained above](#dockerfile), installing your dependencies, and running **a single Uvicorn process** instead of running something like Gunicorn with Uvicorn workers. +In those cases, you would probably want to build a **Docker image from scratch** as [explained above](#dockerfile), installing your dependencies, and running **a single Uvicorn process** instead of using multiple Uvicorn workers. ### Load Balancer @@ -490,37 +490,44 @@ And normally this **load balancer** would be able to handle requests that go to In this type of scenario, you probably would want to have **a single (Uvicorn) process per container**, as you would already be handling replication at the cluster level. -So, in this case, you **would not** want to have a process manager like Gunicorn with Uvicorn workers, or Uvicorn using its own Uvicorn workers. You would want to have just a **single Uvicorn process** per container (but probably multiple containers). +So, in this case, you **would not** want to have a multiple workers in the container, for example with the `--workers` command line option.You would want to have just a **single Uvicorn process** per container (but probably multiple containers). -Having another process manager inside the container (as would be with Gunicorn or Uvicorn managing Uvicorn workers) would only add **unnecessary complexity** that you are most probably already taking care of with your cluster system. +Having another process manager inside the container (as would be with multiple workers) would only add **unnecessary complexity** that you are most probably already taking care of with your cluster system. ### Containers with Multiple Processes and Special Cases -Of course, there are **special cases** where you could want to have **a container** with a **Gunicorn process manager** starting several **Uvicorn worker processes** inside. +Of course, there are **special cases** where you could want to have **a container** with several **Uvicorn worker processes** inside. -In those cases, you can use the **official Docker image** that includes **Gunicorn** as a process manager running multiple **Uvicorn worker processes**, and some default settings to adjust the number of workers based on the current CPU cores automatically. I'll tell you more about it below in [Official Docker Image with Gunicorn - Uvicorn](#official-docker-image-with-gunicorn-uvicorn). +In those cases, you can use the `--workers` command line option to set the number of workers that you want to run: -Here are some examples of when that could make sense: +```{ .dockerfile .annotate } +FROM python:3.9 -#### A Simple App +WORKDIR /code -You could want a process manager in the container if your application is **simple enough** that you don't need (at least not yet) to fine-tune the number of processes too much, and you can just use an automated default (with the official Docker image), and you are running it on a **single server**, not a cluster. +COPY ./requirements.txt /code/requirements.txt -#### Docker Compose +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt -You could be deploying to a **single server** (not a cluster) with **Docker Compose**, so you wouldn't have an easy way to manage replication of containers (with Docker Compose) while preserving the shared network and **load balancing**. +COPY ./app /code/app -Then you could want to have **a single container** with a **process manager** starting **several worker processes** inside. +# (1)! +CMD ["fastapi", "run", "app/main.py", "--port", "80", "--workers", "4"] +``` -#### Prometheus and Other Reasons +1. Here we use the `--workers` command line option to set the number of workers to 4. -You could also have **other reasons** that would make it easier to have a **single container** with **multiple processes** instead of having **multiple containers** with **a single process** in each of them. +Here are some examples of when that could make sense: -For example (depending on your setup) you could have some tool like a Prometheus exporter in the same container that should have access to **each of the requests** that come. +#### A Simple App + +You could want a process manager in the container if your application is **simple enough** that can run it on a **single server**, not a cluster. + +#### Docker Compose -In this case, if you had **multiple containers**, by default, when Prometheus came to **read the metrics**, it would get the ones for **a single container each time** (for the container that handled that particular request), instead of getting the **accumulated metrics** for all the replicated containers. +You could be deploying to a **single server** (not a cluster) with **Docker Compose**, so you wouldn't have an easy way to manage replication of containers (with Docker Compose) while preserving the shared network and **load balancing**. -Then, in that case, it could be simpler to have **one container** with **multiple processes**, and a local tool (e.g. a Prometheus exporter) on the same container collecting Prometheus metrics for all the internal processes and exposing those metrics on that single container. +Then you could want to have **a single container** with a **process manager** starting **several worker processes** inside. --- @@ -541,7 +548,7 @@ And then you can set those same memory limits and requirements in your configura If your application is **simple**, this will probably **not be a problem**, and you might not need to specify hard memory limits. But if you are **using a lot of memory** (for example with **machine learning** models), you should check how much memory you are consuming and adjust the **number of containers** that runs in **each machine** (and maybe add more machines to your cluster). -If you run **multiple processes per container** (for example with the official Docker image) you will have to make sure that the number of processes started doesn't **consume more memory** than what is available. +If you run **multiple processes per container** you will have to make sure that the number of processes started doesn't **consume more memory** than what is available. ## Previous Steps Before Starting and Containers @@ -561,80 +568,26 @@ If in your use case there's no problem in running those previous steps **multipl ### Single Container -If you have a simple setup, with a **single container** that then starts multiple **worker processes** (or also just one process), then you could run those previous steps in the same container, right before starting the process with the app. The official Docker image supports this internally. +If you have a simple setup, with a **single container** that then starts multiple **worker processes** (or also just one process), then you could run those previous steps in the same container, right before starting the process with the app. -## Official Docker Image with Gunicorn - Uvicorn +### Base Docker Image -There is an official Docker image that includes Gunicorn running with Uvicorn workers, as detailed in a previous chapter: [Server Workers - Gunicorn with Uvicorn](server-workers.md){.internal-link target=_blank}. +There used to be an official FastAPI Docker image: tiangolo/uvicorn-gunicorn-fastapi. But it is now deprecated. ⛔️ -This image would be useful mainly in the situations described above in: [Containers with Multiple Processes and Special Cases](#containers-with-multiple-processes-and-special-cases). - -* tiangolo/uvicorn-gunicorn-fastapi. - -/// warning - -There's a high chance that you **don't** need this base image or any other similar one, and would be better off by building the image from scratch as [described above in: Build a Docker Image for FastAPI](#build-a-docker-image-for-fastapi). - -/// +You should probably **not** use this base Docker image (or any other similar one). -This image has an **auto-tuning** mechanism included to set the **number of worker processes** based on the CPU cores available. +If you are using **Kubernetes** (or others) and you are already setting **replication** at the cluster level, with multiple **containers**. In those cases, you are better off **building an image from scratch** as described above: [Build a Docker Image for FastAPI](#build-a-docker-image-for-fastapi). -It has **sensible defaults**, but you can still change and update all the configurations with **environment variables** or configuration files. +And if you need to have multiple workers, you can simply use the `--workers` command line option. -It also supports running **previous steps before starting** with a script. +/// note | Technical Details -/// tip +The Docker image was created when Uvicorn didn't support managing and restarting dead workers, so it was needed to use Gunicorn with Uvicorn, which added quite some complexity, just to have Gunicorn manage and restart the Uvicorn worker processes. -To see all the configurations and options, go to the Docker image page: tiangolo/uvicorn-gunicorn-fastapi. +But now that Uvicorn (and the `fastapi` command) support using `--workers`, there's no reason to use a base Docker image instead of building your own (it's pretty much the same amount of code 😅). /// -### Number of Processes on the Official Docker Image - -The **number of processes** on this image is **computed automatically** from the CPU **cores** available. - -This means that it will try to **squeeze** as much **performance** from the CPU as possible. - -You can also adjust it with the configurations using **environment variables**, etc. - -But it also means that as the number of processes depends on the CPU the container is running, the **amount of memory consumed** will also depend on that. - -So, if your application consumes a lot of memory (for example with machine learning models), and your server has a lot of CPU cores **but little memory**, then your container could end up trying to use more memory than what is available, and degrading performance a lot (or even crashing). 🚨 - -### Create a `Dockerfile` - -Here's how you would create a `Dockerfile` based on this image: - -```Dockerfile -FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9 - -COPY ./requirements.txt /app/requirements.txt - -RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt - -COPY ./app /app -``` - -### Bigger Applications - -If you followed the section about creating [Bigger Applications with Multiple Files](../tutorial/bigger-applications.md){.internal-link target=_blank}, your `Dockerfile` might instead look like: - -```Dockerfile hl_lines="7" -FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9 - -COPY ./requirements.txt /app/requirements.txt - -RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt - -COPY ./app /app/app -``` - -### When to Use - -You should probably **not** use this official base image (or any other similar one) if you are using **Kubernetes** (or others) and you are already setting **replication** at the cluster level, with multiple **containers**. In those cases, you are better off **building an image from scratch** as described above: [Build a Docker Image for FastAPI](#build-a-docker-image-for-fastapi). - -This image would be useful mainly in the special cases described above in [Containers with Multiple Processes and Special Cases](#containers-with-multiple-processes-and-special-cases). For example, if your application is **simple enough** that setting a default number of processes based on the CPU works well, you don't want to bother with manually configuring the replication at the cluster level, and you are not running more than one container with your app. Or if you are deploying with **Docker Compose**, running on a single server, etc. - ## Deploy the Container Image After having a Container (Docker) Image there are several ways to deploy it. @@ -647,98 +600,9 @@ For example: * With another tool like Nomad * With a cloud service that takes your container image and deploys it -## Docker Image with Poetry +## Docker Image with `uv` -If you use Poetry to manage your project's dependencies, you could use Docker multi-stage building: - -```{ .dockerfile .annotate } -# (1) -FROM python:3.9 as requirements-stage - -# (2) -WORKDIR /tmp - -# (3) -RUN pip install poetry - -# (4) -COPY ./pyproject.toml ./poetry.lock* /tmp/ - -# (5) -RUN poetry export -f requirements.txt --output requirements.txt --without-hashes - -# (6) -FROM python:3.9 - -# (7) -WORKDIR /code - -# (8) -COPY --from=requirements-stage /tmp/requirements.txt /code/requirements.txt - -# (9) -RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt - -# (10) -COPY ./app /code/app - -# (11) -CMD ["fastapi", "run", "app/main.py", "--port", "80"] -``` - -1. This is the first stage, it is named `requirements-stage`. - -2. Set `/tmp` as the current working directory. - - Here's where we will generate the file `requirements.txt` - -3. Install Poetry in this Docker stage. - -4. Copy the `pyproject.toml` and `poetry.lock` files to the `/tmp` directory. - - Because it uses `./poetry.lock*` (ending with a `*`), it won't crash if that file is not available yet. - -5. Generate the `requirements.txt` file. - -6. This is the final stage, anything here will be preserved in the final container image. - -7. Set the current working directory to `/code`. - -8. Copy the `requirements.txt` file to the `/code` directory. - - This file only lives in the previous Docker stage, that's why we use `--from-requirements-stage` to copy it. - -9. Install the package dependencies in the generated `requirements.txt` file. - -10. Copy the `app` directory to the `/code` directory. - -11. Use the `fastapi run` command to run your app. - -/// tip - -Click the bubble numbers to see what each line does. - -/// - -A **Docker stage** is a part of a `Dockerfile` that works as a **temporary container image** that is only used to generate some files to be used later. - -The first stage will only be used to **install Poetry** and to **generate the `requirements.txt`** with your project dependencies from Poetry's `pyproject.toml` file. - -This `requirements.txt` file will be used with `pip` later in the **next stage**. - -In the final container image **only the final stage** is preserved. The previous stage(s) will be discarded. - -When using Poetry, it would make sense to use **Docker multi-stage builds** because you don't really need to have Poetry and its dependencies installed in the final container image, you **only need** to have the generated `requirements.txt` file to install your project dependencies. - -Then in the next (and final) stage you would build the image more or less in the same way as described before. - -### Behind a TLS Termination Proxy - Poetry - -Again, if you are running your container behind a TLS Termination Proxy (load balancer) like Nginx or Traefik, add the option `--proxy-headers` to the command: - -```Dockerfile -CMD ["fastapi", "run", "app/main.py", "--proxy-headers", "--port", "80"] -``` +If you are using uv to install and manage your project, you can follow their uv Docker guide. ## Recap @@ -754,5 +618,3 @@ Using container systems (e.g. with **Docker** and **Kubernetes**) it becomes fai In most cases, you probably won't want to use any base image, and instead **build a container image from scratch** one based on the official Python Docker image. Taking care of the **order** of instructions in the `Dockerfile` and the **Docker cache** you can **minimize build times**, to maximize your productivity (and avoid boredom). 😎 - -In certain special cases, you might want to use the official Docker image for FastAPI. 🤓 diff --git a/docs/en/docs/deployment/manually.md b/docs/en/docs/deployment/manually.md index 3324a7503..3f7c7a008 100644 --- a/docs/en/docs/deployment/manually.md +++ b/docs/en/docs/deployment/manually.md @@ -67,6 +67,8 @@ There are several alternatives, including: * Uvicorn: a high performance ASGI server. * Hypercorn: an ASGI server compatible with HTTP/2 and Trio among other features. * Daphne: the ASGI server built for Django Channels. +* Granian: A Rust HTTP server for Python applications. +* NGINX Unit: NGINX Unit is a lightweight and versatile web application runtime. ## Server Machine and Server Program @@ -84,11 +86,9 @@ When you install FastAPI, it comes with a production server, Uvicorn, and you ca But you can also install an ASGI server manually. -Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then you can install the server: +Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then you can install the server application. -//// tab | Uvicorn - -* Uvicorn, a lightning-fast ASGI server, built on uvloop and httptools. +For example, to install Uvicorn:
@@ -100,6 +100,8 @@ $ pip install "uvicorn[standard]"
+A similar process would apply to any other ASGI server program. + /// tip By adding the `standard`, Uvicorn will install and use some recommended extra dependencies. @@ -110,32 +112,10 @@ When you install FastAPI with something like `pip install "fastapi[standard]"` y /// -//// - -//// tab | Hypercorn - -* Hypercorn, an ASGI server also compatible with HTTP/2. - -
- -```console -$ pip install hypercorn - ----> 100% -``` - -
- -...or any other ASGI server. - -//// - ## Run the Server Program If you installed an ASGI server manually, you would normally need to pass an import string in a special format for it to import your FastAPI application: -//// tab | Uvicorn -
```console @@ -146,22 +126,6 @@ $ uvicorn main:app --host 0.0.0.0 --port 80
-//// - -//// tab | Hypercorn - -
- -```console -$ hypercorn main:app --bind 0.0.0.0:80 - -Running on 0.0.0.0:8080 over http (CTRL + C to quit) -``` - -
- -//// - /// note The command `uvicorn main:app` refers to: @@ -177,9 +141,11 @@ from main import app /// +Each alternative ASGI server program would have a similar command, you can read more in their respective documentation. + /// warning -Uvicorn and others support a `--reload` option that is useful during development. +Uvicorn and other servers support a `--reload` option that is useful during development. The `--reload` option consumes much more resources, is more unstable, etc. @@ -187,43 +153,6 @@ It helps a lot during **development**, but you **shouldn't** use it in **product /// -## Hypercorn with Trio - -Starlette and **FastAPI** are based on AnyIO, which makes them compatible with both Python's standard library asyncio and Trio. - -Nevertheless, Uvicorn is currently only compatible with asyncio, and it normally uses `uvloop`, the high-performance drop-in replacement for `asyncio`. - -But if you want to directly use **Trio**, then you can use **Hypercorn** as it supports it. ✨ - -### Install Hypercorn with Trio - -First you need to install Hypercorn with Trio support: - -
- -```console -$ pip install "hypercorn[trio]" ----> 100% -``` - -
- -### Run with Trio - -Then you can pass the command line option `--worker-class` with the value `trio`: - -
- -```console -$ hypercorn main:app --worker-class trio -``` - -
- -And that will start Hypercorn with your app using Trio as the backend. - -Now you can use Trio internally in your app. Or even better, you can use AnyIO, to keep your code compatible with both Trio and asyncio. 🎉 - ## Deployment Concepts These examples run the server program (e.g Uvicorn), starting **a single process**, listening on all the IPs (`0.0.0.0`) on a predefined port (e.g. `80`). diff --git a/docs/en/docs/deployment/server-workers.md b/docs/en/docs/deployment/server-workers.md index efde5f3a1..5e369e071 100644 --- a/docs/en/docs/deployment/server-workers.md +++ b/docs/en/docs/deployment/server-workers.md @@ -1,4 +1,4 @@ -# Server Workers - Gunicorn with Uvicorn +# Server Workers - Uvicorn with Workers Let's check back those deployment concepts from before: @@ -9,125 +9,92 @@ Let's check back those deployment concepts from before: * Memory * Previous steps before starting -Up to this point, with all the tutorials in the docs, you have probably been running a **server program** like Uvicorn, running a **single process**. +Up to this point, with all the tutorials in the docs, you have probably been running a **server program**, for example, using the `fastapi` command, that runs Uvicorn, running a **single process**. When deploying applications you will probably want to have some **replication of processes** to take advantage of **multiple cores** and to be able to handle more requests. As you saw in the previous chapter about [Deployment Concepts](concepts.md){.internal-link target=_blank}, there are multiple strategies you can use. -Here I'll show you how to use **Gunicorn** with **Uvicorn worker processes**. +Here I'll show you how to use **Uvicorn** with **worker processes** using the `fastapi` command or the `uvicorn` command directly. /// info If you are using containers, for example with Docker or Kubernetes, I'll tell you more about that in the next chapter: [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank}. -In particular, when running on **Kubernetes** you will probably **not** want to use Gunicorn and instead run **a single Uvicorn process per container**, but I'll tell you about it later in that chapter. +In particular, when running on **Kubernetes** you will probably **not** want to use workers and instead run **a single Uvicorn process per container**, but I'll tell you about it later in that chapter. /// -## Gunicorn with Uvicorn Workers +## Multiple Workers -**Gunicorn** is mainly an application server using the **WSGI standard**. That means that Gunicorn can serve applications like Flask and Django. Gunicorn by itself is not compatible with **FastAPI**, as FastAPI uses the newest **ASGI standard**. +You can start multiple workers with the `--workers` command line option: -But Gunicorn supports working as a **process manager** and allowing users to tell it which specific **worker process class** to use. Then Gunicorn would start one or more **worker processes** using that class. +//// tab | `fastapi` -And **Uvicorn** has a **Gunicorn-compatible worker class**. - -Using that combination, Gunicorn would act as a **process manager**, listening on the **port** and the **IP**. And it would **transmit** the communication to the worker processes running the **Uvicorn class**. - -And then the Gunicorn-compatible **Uvicorn worker** class would be in charge of converting the data sent by Gunicorn to the ASGI standard for FastAPI to use it. - -## Install Gunicorn and Uvicorn - -Make sure you create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}, activate it, and then install `gunicorn`: +If you use the `fastapi` command:
```console -$ pip install "uvicorn[standard]" gunicorn - ----> 100% +$
 fastapi run --workers 4 main.py
+INFO     Using path main.py
+INFO     Resolved absolute path /home/user/code/awesomeapp/main.py
+INFO     Searching for package file structure from directories with __init__.py files
+INFO     Importing from /home/user/code/awesomeapp
+
+ ╭─ Python module file ─╮
+ │                      │
+ │  🐍 main.py          │
+ │                      │
+ ╰──────────────────────╯
+
+INFO     Importing module main
+INFO     Found importable FastAPI app
+
+ ╭─ Importable FastAPI app ─╮
+ │                          │
+ │  from main import app    │
+ │                          │
+ ╰──────────────────────────╯
+
+INFO     Using import string main:app
+
+ ╭─────────── FastAPI CLI - Production mode ───────────╮
+ │                                                     │
+ │  Serving at: http://0.0.0.0:8000                    │
+ │                                                     │
+ │  API docs: http://0.0.0.0:8000/docs                 │
+ │                                                     │
+ │  Running in production mode, for development use:   │
+ │                                                     │
+ fastapi dev
+ │                                                     │
+ ╰─────────────────────────────────────────────────────╯
+
+INFO:     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:     Waiting for application startup.
+INFO:     Application startup complete.
+INFO:     Started server process [27369]
+INFO:     Waiting for application startup.
+INFO:     Application startup complete.
+INFO:     Started server process [27370]
+INFO:     Waiting for application startup.
+INFO:     Application startup complete.
+INFO:     Started server process [27367]
+INFO:     Waiting for application startup.
+INFO:     Application startup complete.
+
```
-That will install both Uvicorn with the `standard` extra packages (to get high performance) and Gunicorn. +//// -## Run Gunicorn with Uvicorn Workers +//// tab | `uvicorn` -Then you can run Gunicorn with: - -
- -```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. -``` - -
- -Let's see what each of those options mean: - -* `main:app`: This is the same syntax used by Uvicorn, `main` means the Python module named "`main`", so, a file `main.py`. And `app` is the name of the variable that is the **FastAPI** application. - * You can imagine that `main:app` is equivalent to a Python `import` statement like: - - ```Python - from main import app - ``` - - * So, the colon in `main:app` would be equivalent to the Python `import` part in `from main import app`. - -* `--workers`: The number of worker processes to use, each will run a Uvicorn worker, in this case, 4 workers. - -* `--worker-class`: The Gunicorn-compatible worker class to use in the worker processes. - * Here we pass the class that Gunicorn can import and use with: - - ```Python - import uvicorn.workers.UvicornWorker - ``` - -* `--bind`: This tells Gunicorn the IP and the port to listen to, using a colon (`:`) to separate the IP and the port. - * If you were running Uvicorn directly, instead of `--bind 0.0.0.0:80` (the Gunicorn option) you would use `--host 0.0.0.0` and `--port 80`. - -In the output, you can see that it shows the **PID** (process ID) of each process (it's just a number). - -You can see that: - -* The Gunicorn **process manager** starts with PID `19499` (in your case it will be a different number). -* Then it starts `Listening at: http://0.0.0.0:80`. -* Then it detects that it has to use the worker class at `uvicorn.workers.UvicornWorker`. -* And then it starts **4 workers**, each with its own PID: `19511`, `19513`, `19514`, and `19515`. - -Gunicorn would also take care of managing **dead processes** and **restarting** new ones if needed to keep the number of workers. So that helps in part with the **restart** concept from the list above. - -Nevertheless, you would probably also want to have something outside making sure to **restart Gunicorn** if necessary, and also to **run it on startup**, etc. - -## Uvicorn with Workers - -Uvicorn also has an option to start and run several **worker processes**. - -Nevertheless, as of now, Uvicorn's capabilities for handling worker processes are more limited than Gunicorn's. So, if you want to have a process manager at this level (at the Python level), then it might be better to try with Gunicorn as the process manager. - -In any case, you would run it like this: +If you prefer to use the `uvicorn` command directly:
@@ -151,13 +118,15 @@ $ uvicorn main:app --host 0.0.0.0 --port 8080 --workers 4
+//// + The only new option here is `--workers` telling Uvicorn to start 4 worker processes. You can also see that it shows the **PID** of each process, `27365` for the parent process (this is the **process manager**) and one for each worker process: `27368`, `27369`, `27370`, and `27367`. ## Deployment Concepts -Here you saw how to use **Gunicorn** (or Uvicorn) managing **Uvicorn worker processes** to **parallelize** the execution of the application, take advantage of **multiple cores** in the CPU, and be able to serve **more requests**. +Here you saw how to use multiple **workers** to **parallelize** the execution of the application, take advantage of **multiple cores** in the CPU, and be able to serve **more requests**. From the list of deployment concepts from above, using workers would mainly help with the **replication** part, and a little bit with the **restarts**, but you still need to take care of the others: @@ -172,13 +141,11 @@ From the list of deployment concepts from above, using workers would mainly help In the next chapter about [FastAPI in Containers - Docker](docker.md){.internal-link target=_blank} I'll tell some strategies you could use to handle the other **deployment concepts**. -I'll also show you the **official Docker image** that includes **Gunicorn with Uvicorn workers** and some default configurations that can be useful for simple cases. - -There I'll also show you how to **build your own image from scratch** to run a single Uvicorn process (without Gunicorn). It is a simple process and is probably what you would want to do when using a distributed container management system like **Kubernetes**. +I'll show you how to **build your own image from scratch** to run a single Uvicorn process. It is a simple process and is probably what you would want to do when using a distributed container management system like **Kubernetes**. ## Recap -You can use **Gunicorn** (or also Uvicorn) as a process manager with Uvicorn workers to take advantage of **multi-core CPUs**, to run **multiple processes in parallel**. +You can use multiple worker processes with the `--workers` CLI option with the `fastapi` or `uvicorn` commands to take advantage of **multi-core CPUs**, to run **multiple processes in parallel**. You could use these tools and ideas if you are setting up **your own deployment system** while taking care of the other deployment concepts yourself. diff --git a/docs/en/docs/deployment/versions.md b/docs/en/docs/deployment/versions.md index e387d5712..23f49cf99 100644 --- a/docs/en/docs/deployment/versions.md +++ b/docs/en/docs/deployment/versions.md @@ -30,7 +30,7 @@ fastapi[standard]>=0.112.0,<0.113.0 that would mean that you would use the versions `0.112.0` or above, but less than `0.113.0`, for example, a version `0.112.2` would still be accepted. -If you use any other tool to manage your installations, like Poetry, Pipenv, or others, they all have a way that you can use to define specific versions for your packages. +If you use any other tool to manage your installations, like `uv`, Poetry, Pipenv, or others, they all have a way that you can use to define specific versions for your packages. ## Available versions diff --git a/docs/en/docs/tutorial/bigger-applications.md b/docs/en/docs/tutorial/bigger-applications.md index 230f9c08c..1c33fd051 100644 --- a/docs/en/docs/tutorial/bigger-applications.md +++ b/docs/en/docs/tutorial/bigger-applications.md @@ -519,12 +519,12 @@ As we cannot just isolate them and "mount" them independently of the rest, the * ## Check the automatic API docs -Now, run `uvicorn`, using the module `app.main` and the variable `app`: +Now, run your app:
```console -$ uvicorn app.main:app --reload +$ fastapi dev app/main.py INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` From 3a96938771c67a9cc343a38b143f55b618817bd3 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 25 Aug 2024 02:44:27 +0000 Subject: [PATCH 37/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index ac8f16f53..b5b3188ef 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update docs about serving FastAPI: ASGI servers, Docker containers, etc.. PR [#12069](https://github.com/fastapi/fastapi/pull/12069) by [@tiangolo](https://github.com/tiangolo). * 📝 Clarify `response_class` parameter, validations, and returning a response directly. PR [#12067](https://github.com/fastapi/fastapi/pull/12067) by [@tiangolo](https://github.com/tiangolo). * 📝 Fix minor typos and issues in the documentation. PR [#12063](https://github.com/fastapi/fastapi/pull/12063) by [@svlandeg](https://github.com/svlandeg). * 📝 Add note in Docker docs about ensuring graceful shutdowns and lifespan events with `CMD` exec form. PR [#11960](https://github.com/fastapi/fastapi/pull/11960) by [@GPla](https://github.com/GPla). From 5fdbeed7928231a249d479c0c266f83877cafce6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sun, 25 Aug 2024 21:14:56 -0500 Subject: [PATCH 38/88] =?UTF-8?q?=F0=9F=91=B7=20Update=20`latest-changes`?= =?UTF-8?q?=20GitHub=20Action=20(#12073)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/latest-changes.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/workflows/latest-changes.yml b/.github/workflows/latest-changes.yml index 27e062d09..16da3bc63 100644 --- a/.github/workflows/latest-changes.yml +++ b/.github/workflows/latest-changes.yml @@ -34,8 +34,7 @@ jobs: if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }} with: limit-access-to-actor: true - - uses: docker://tiangolo/latest-changes:0.3.0 - # - uses: tiangolo/latest-changes@main + - uses: tiangolo/latest-changes@0.3.1 with: token: ${{ secrets.GITHUB_TOKEN }} latest_changes_file: docs/en/docs/release-notes.md From 9416e89bd7e3491157f8c962012aebd7be7ed5d6 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 26 Aug 2024 02:15:38 +0000 Subject: [PATCH 39/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index b5b3188ef..1dff0bddc 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,10 @@ hide: * 📝 Fix minor typos and issues in the documentation. PR [#12063](https://github.com/fastapi/fastapi/pull/12063) by [@svlandeg](https://github.com/svlandeg). * 📝 Add note in Docker docs about ensuring graceful shutdowns and lifespan events with `CMD` exec form. PR [#11960](https://github.com/fastapi/fastapi/pull/11960) by [@GPla](https://github.com/GPla). +### Internal + +* 👷 Update `latest-changes` GitHub Action. PR [#12073](https://github.com/fastapi/fastapi/pull/12073) by [@tiangolo](https://github.com/tiangolo). + ## 0.112.2 ### Fixes From f41f6234af886914ebd3022faad80bb6320bb1bf Mon Sep 17 00:00:00 2001 From: lkw123 <2020393267@qq.com> Date: Wed, 28 Aug 2024 21:48:13 +0800 Subject: [PATCH 40/88] =?UTF-8?q?=F0=9F=8C=90=20Update=20Chinese=20transla?= =?UTF-8?q?tion=20for=20`docs/zh/docs/how-to/index.md`=20(#12070)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/how-to/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/zh/docs/how-to/index.md b/docs/zh/docs/how-to/index.md index 262dcfaee..ac097618b 100644 --- a/docs/zh/docs/how-to/index.md +++ b/docs/zh/docs/how-to/index.md @@ -6,7 +6,7 @@ 如果某些内容看起来对你的项目有用,请继续查阅,否则请直接跳过它们。 -/// 小技巧 +/// tip | 小技巧 如果你想以系统的方式**学习 FastAPI**(推荐),请阅读 [教程 - 用户指南](../tutorial/index.md){.internal-link target=_blank} 的每一章节。 From be9abcf35315cff34d30e86ce7d2deec3e3df9be Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 28 Aug 2024 13:48:40 +0000 Subject: [PATCH 41/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 1dff0bddc..20caacd64 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -14,6 +14,10 @@ hide: * 📝 Fix minor typos and issues in the documentation. PR [#12063](https://github.com/fastapi/fastapi/pull/12063) by [@svlandeg](https://github.com/svlandeg). * 📝 Add note in Docker docs about ensuring graceful shutdowns and lifespan events with `CMD` exec form. PR [#11960](https://github.com/fastapi/fastapi/pull/11960) by [@GPla](https://github.com/GPla). +### Translations + +* 🌐 Update Chinese translation for `docs/zh/docs/how-to/index.md`. PR [#12070](https://github.com/fastapi/fastapi/pull/12070) by [@synthpop123](https://github.com/synthpop123). + ### Internal * 👷 Update `latest-changes` GitHub Action. PR [#12073](https://github.com/fastapi/fastapi/pull/12073) by [@tiangolo](https://github.com/tiangolo). From 4909e44a7ff9b7048f7e6db8c7ad72283fd6a30d Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 28 Aug 2024 09:07:00 -0500 Subject: [PATCH 42/88] =?UTF-8?q?=E2=AC=86=20[pre-commit.ci]=20pre-commit?= =?UTF-8?q?=20autoupdate=20(#12076)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit updates: - [github.com/astral-sh/ruff-pre-commit: v0.6.1 → v0.6.2](https://github.com/astral-sh/ruff-pre-commit/compare/v0.6.1...v0.6.2) Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- .pre-commit-config.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 7532f21b5..317514062 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.6.1 + rev: v0.6.2 hooks: - id: ruff args: From 48bf0db58fb5008c78d758d830e0d58f34edfb62 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 28 Aug 2024 14:07:23 +0000 Subject: [PATCH 43/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 20caacd64..baf25d451 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -20,6 +20,7 @@ hide: ### Internal +* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12076](https://github.com/fastapi/fastapi/pull/12076) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). * 👷 Update `latest-changes` GitHub Action. PR [#12073](https://github.com/fastapi/fastapi/pull/12073) by [@tiangolo](https://github.com/tiangolo). ## 0.112.2 From cabed9efb6a6b615f3bf45e9e523ff290f252f0f Mon Sep 17 00:00:00 2001 From: Alec Gillis Date: Wed, 28 Aug 2024 16:33:37 -0700 Subject: [PATCH 44/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20comma=20in=20`doc?= =?UTF-8?q?s/en/docs/async.md`=20(#12062)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Alec Gillis Co-authored-by: Sofie Van Landeghem --- docs/en/docs/async.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/async.md b/docs/en/docs/async.md index 752a5c247..63bd8ca68 100644 --- a/docs/en/docs/async.md +++ b/docs/en/docs/async.md @@ -387,7 +387,7 @@ In previous versions of NodeJS / Browser JavaScript, you would have used "callba ## Coroutines -**Coroutine** is just the very fancy term for the thing returned by an `async def` function. Python knows that it is something like a function that it can start and that it will end at some point, but that it might be paused ⏸ internally too, whenever there is an `await` inside of it. +**Coroutine** is just the very fancy term for the thing returned by an `async def` function. Python knows that it is something like a function, that it can start and that it will end at some point, but that it might be paused ⏸ internally too, whenever there is an `await` inside of it. But all this functionality of using asynchronous code with `async` and `await` is many times summarized as using "coroutines". It is comparable to the main key feature of Go, the "Goroutines". From a930128910f65e53bdff76f4e52f484e5129f60b Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 28 Aug 2024 23:35:03 +0000 Subject: [PATCH 45/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index baf25d451..838516421 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update comma in `docs/en/docs/async.md`. PR [#12062](https://github.com/fastapi/fastapi/pull/12062) by [@Alec-Gillis](https://github.com/Alec-Gillis). * 📝 Update docs about serving FastAPI: ASGI servers, Docker containers, etc.. PR [#12069](https://github.com/fastapi/fastapi/pull/12069) by [@tiangolo](https://github.com/tiangolo). * 📝 Clarify `response_class` parameter, validations, and returning a response directly. PR [#12067](https://github.com/fastapi/fastapi/pull/12067) by [@tiangolo](https://github.com/tiangolo). * 📝 Fix minor typos and issues in the documentation. PR [#12063](https://github.com/fastapi/fastapi/pull/12063) by [@svlandeg](https://github.com/svlandeg). From 9b35d355bfb44c33000359a2b24f215286996693 Mon Sep 17 00:00:00 2001 From: Muhammad Ashiq Ameer <46787072+MuhammadAshiqAmeer@users.noreply.github.com> Date: Thu, 29 Aug 2024 05:09:15 +0530 Subject: [PATCH 46/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20`docs=5Fsrc/path?= =?UTF-8?q?=5Fparams=5Fnumeric=5Fvalidations/tutorial006.py`=20(#11478)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sofie Van Landeghem --- docs_src/path_params_numeric_validations/tutorial006.py | 2 ++ docs_src/path_params_numeric_validations/tutorial006_an.py | 2 ++ docs_src/path_params_numeric_validations/tutorial006_an_py39.py | 2 ++ 3 files changed, 6 insertions(+) diff --git a/docs_src/path_params_numeric_validations/tutorial006.py b/docs_src/path_params_numeric_validations/tutorial006.py index 0ea32694a..f07629aa0 100644 --- a/docs_src/path_params_numeric_validations/tutorial006.py +++ b/docs_src/path_params_numeric_validations/tutorial006.py @@ -13,4 +13,6 @@ async def read_items( results = {"item_id": item_id} if q: results.update({"q": q}) + if size: + results.update({"size": size}) return results diff --git a/docs_src/path_params_numeric_validations/tutorial006_an.py b/docs_src/path_params_numeric_validations/tutorial006_an.py index 22a143623..ac4732573 100644 --- a/docs_src/path_params_numeric_validations/tutorial006_an.py +++ b/docs_src/path_params_numeric_validations/tutorial006_an.py @@ -14,4 +14,6 @@ async def read_items( results = {"item_id": item_id} if q: results.update({"q": q}) + if size: + results.update({"size": size}) return results diff --git a/docs_src/path_params_numeric_validations/tutorial006_an_py39.py b/docs_src/path_params_numeric_validations/tutorial006_an_py39.py index 804751893..426ec3776 100644 --- a/docs_src/path_params_numeric_validations/tutorial006_an_py39.py +++ b/docs_src/path_params_numeric_validations/tutorial006_an_py39.py @@ -15,4 +15,6 @@ async def read_items( results = {"item_id": item_id} if q: results.update({"q": q}) + if size: + results.update({"size": size}) return results From 33328952518b78ed40d5f58cf21f3e40e48f6615 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 28 Aug 2024 23:40:13 +0000 Subject: [PATCH 47/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 838516421..34a3fbc57 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Update `docs_src/path_params_numeric_validations/tutorial006.py`. PR [#11478](https://github.com/fastapi/fastapi/pull/11478) by [@MuhammadAshiqAmeer](https://github.com/MuhammadAshiqAmeer). * 📝 Update comma in `docs/en/docs/async.md`. PR [#12062](https://github.com/fastapi/fastapi/pull/12062) by [@Alec-Gillis](https://github.com/Alec-Gillis). * 📝 Update docs about serving FastAPI: ASGI servers, Docker containers, etc.. PR [#12069](https://github.com/fastapi/fastapi/pull/12069) by [@tiangolo](https://github.com/tiangolo). * 📝 Clarify `response_class` parameter, validations, and returning a response directly. PR [#12067](https://github.com/fastapi/fastapi/pull/12067) by [@tiangolo](https://github.com/tiangolo). From ae27540348d943e786e83176a8fc32d535baece7 Mon Sep 17 00:00:00 2001 From: Sofie Van Landeghem Date: Thu, 29 Aug 2024 01:41:46 +0200 Subject: [PATCH 48/88] =?UTF-8?q?=F0=9F=8C=90=20Add=20Dutch=20translation?= =?UTF-8?q?=20for=20`docs/nl/docs/index.md`=20(#12042)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Max Scheijen --- docs/en/mkdocs.yml | 2 + docs/nl/docs/index.md | 494 ++++++++++++++++++++++++++++++++++++++++++ docs/nl/mkdocs.yml | 1 + 3 files changed, 497 insertions(+) create mode 100644 docs/nl/docs/index.md create mode 100644 docs/nl/mkdocs.yml diff --git a/docs/en/mkdocs.yml b/docs/en/mkdocs.yml index 6f1e12511..528c80b8e 100644 --- a/docs/en/mkdocs.yml +++ b/docs/en/mkdocs.yml @@ -363,6 +363,8 @@ extra: name: ja - 日本語 - link: /ko/ name: ko - 한국어 + - link: /nl/ + name: nl - Nederlands - link: /pl/ name: pl - Polski - link: /pt/ diff --git a/docs/nl/docs/index.md b/docs/nl/docs/index.md new file mode 100644 index 000000000..8edc3ba0c --- /dev/null +++ b/docs/nl/docs/index.md @@ -0,0 +1,494 @@ +# FastAPI + + + +

+ FastAPI +

+

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

+

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

+ +--- + +**Documentatie**: https://fastapi.tiangolo.com + +**Broncode**: https://github.com/tiangolo/fastapi + +--- + +FastAPI is een modern, snel (zeer goede prestaties), web framework voor het bouwen van API's in Python, gebruikmakend van standaard Python type-hints. + +De belangrijkste kenmerken zijn: + +* **Snel**: Zeer goede prestaties, vergelijkbaar met **NodeJS** en **Go** (dankzij Starlette en Pydantic). [Een van de snelste beschikbare Python frameworks](#prestaties). +* **Snel te programmeren**: Verhoog de snelheid om functionaliteit te ontwikkelen met ongeveer 200% tot 300%. * +* **Minder bugs**: Verminder ongeveer 40% van de door mensen (ontwikkelaars) veroorzaakte fouten. * +* **Intuïtief**: Buitengewoon goede ondersteuning voor editors. Overal automische code aanvulling. Minder tijd kwijt aan debuggen. +* **Eenvoudig**: Ontworpen om gemakkelijk te gebruiken en te leren. Minder tijd nodig om documentatie te lezen. +* **Kort**: Minimaliseer codeduplicatie. Elke parameterdeclaratie ondersteunt meerdere functionaliteiten. Minder bugs. +* **Robust**: Code gereed voor productie. Met automatische interactieve documentatie. +* **Standards-based**: Gebaseerd op (en volledig verenigbaar met) open standaarden voor API's: OpenAPI (voorheen bekend als Swagger) en JSON Schema. + +* schatting op basis van testen met een intern ontwikkelteam en bouwen van productieapplicaties. + +## Sponsors + + + +{% if sponsors %} +{% for sponsor in sponsors.gold -%} + +{% endfor -%} +{%- for sponsor in sponsors.silver -%} + +{% endfor %} +{% endif %} + + + +Overige sponsoren + +## Meningen + +"_[...] Ik gebruik **FastAPI** heel vaak tegenwoordig. [...] Ik ben van plan om het te gebruiken voor alle **ML-services van mijn team bij Microsoft**. Sommige van deze worden geïntegreerd in het kernproduct van **Windows** en sommige **Office**-producten._" + +
Kabir Khan - Microsoft (ref)
+ +--- + +"_We hebben de **FastAPI** library gebruikt om een **REST** server te maken die bevraagd kan worden om **voorspellingen** te maken. [voor Ludwig]_" + +
Piero Molino, Yaroslav Dudin en Sai Sumanth Miryala - Uber (ref)
+ +--- + +"_**Netflix** is verheugd om een open-source release aan te kondigen van ons **crisismanagement**-orkestratieframework: **Dispatch**! [gebouwd met **FastAPI**]_" + +
Kevin Glisson, Marc Vilanova, Forest Monsen - Netflix (ref)
+ +--- + +"_Ik ben super enthousiast over **FastAPI**. Het is zo leuk!_" + +
Brian Okken - Python Bytes podcast presentator (ref)
+ +--- + +"_Wat je hebt gebouwd ziet er echt super solide en gepolijst uit. In veel opzichten is het wat ik wilde dat **Hug** kon zijn - het is echt inspirerend om iemand dit te zien bouwen._" + +
Timothy Crosley - Hug creator (ref)
+ +--- + +"Wie geïnteresseerd is in een **modern framework** voor het bouwen van REST API's, bekijkt best eens **FastAPI** [...] Het is snel, gebruiksvriendelijk en gemakkelijk te leren [...]_" + +"_We zijn overgestapt naar **FastAPI** voor onze **API's** [...] Het gaat jou vast ook bevallen [...]_" + +
Ines Montani - Matthew Honnibal - Explosion AI oprichters - spaCy ontwikkelaars (ref) - (ref)
+ +--- + +"_Wie een Python API wil bouwen voor productie, kan ik ten stelligste **FastAPI** aanraden. Het is **prachtig ontworpen**, **eenvoudig te gebruiken** en **gemakkelijk schaalbaar**, het is een **cruciale component** geworden in onze strategie om API's centraal te zetten, en het vereenvoudigt automatisering en diensten zoals onze Virtual TAC Engineer._" + +
Deon Pillsbury - Cisco (ref)
+ +--- + +## **Typer**, de FastAPI van CLIs + + + +Als je een CLI-app bouwt die in de terminal moet worden gebruikt in plaats van een web-API, gebruik dan **Typer**. + +**Typer** is het kleine broertje van FastAPI. En het is bedoeld als de **FastAPI van CLI's**. ️ + +## Vereisten + +FastAPI staat op de schouders van reuzen: + +* Starlette voor de webonderdelen. +* Pydantic voor de datadelen. + +## Installatie + +
+ +```console +$ pip install "fastapi[standard]" + +---> 100% +``` + +
+ +**Opmerking**: Zet `"fastapi[standard]"` tussen aanhalingstekens om ervoor te zorgen dat het werkt in alle terminals. + +## Voorbeeld + +### Creëer het + +* Maak het bestand `main.py` aan met daarin: + +```Python +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +
+Of maak gebruik van async def... + +Als je code gebruik maakt van `async` / `await`, gebruik dan `async def`: + +```Python hl_lines="9 14" +from typing import Union + +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +async def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +async def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} +``` + +**Opmerking**: + +Als je het niet weet, kijk dan in het gedeelte _"Heb je haast?"_ over `async` en `await` in de documentatie. + +
+ +### Voer het uit + +Run de server met: + +
+ +```console +$ fastapi dev main.py + + ╭────────── FastAPI CLI - Development mode ───────────╮ + │ │ + │ Serving at: http://127.0.0.1:8000 │ + │ │ + │ API docs: http://127.0.0.1:8000/docs │ + │ │ + │ Running in development mode, for production use: │ + │ │ + │ fastapi run │ + │ │ + ╰─────────────────────────────────────────────────────╯ + +INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp'] +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [2248755] using WatchFiles +INFO: Started server process [2248757] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +
+Over het commando fastapi dev main.py... + +Het commando `fastapi dev` leest het `main.py` bestand, detecteert de **FastAPI** app, en start een server met Uvicorn. + +Standaard zal dit commando `fastapi dev` starten met "auto-reload" geactiveerd voor ontwikkeling op het lokale systeem. + +Je kan hier meer over lezen in de FastAPI CLI documentatie. + +
+ +### Controleer het + +Open je browser op http://127.0.0.1:8000/items/5?q=somequery. + +Je zult een JSON response zien: + +```JSON +{"item_id": 5, "q": "somequery"} +``` + +Je hebt een API gemaakt die: + +* HTTP verzoeken kan ontvangen op de _paden_ `/` en `/items/{item_id}`. +* Beide _paden_ hebben `GET` operaties (ook bekend als HTTP _methoden_). +* Het _pad_ `/items/{item_id}` heeft een _pad parameter_ `item_id` dat een `int` moet zijn. +* Het _pad_ `/items/{item_id}` heeft een optionele `str` _query parameter_ `q`. + +### Interactieve API documentatie + +Ga naar http://127.0.0.1:8000/docs. + +Je ziet de automatische interactieve API documentatie (verstrekt door Swagger UI): + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png) + +### Alternatieve API documentatie + +Ga vervolgens naar http://127.0.0.1:8000/redoc. + +Je ziet de automatische interactieve API documentatie (verstrekt door ReDoc): + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png) + +## Voorbeeld upgrade + +Pas nu het bestand `main.py` aan om de body van een `PUT` request te ontvangen. + +Dankzij Pydantic kunnen we de body declareren met standaard Python types. + +```Python hl_lines="4 9-12 25-27" +from typing import Union + +from fastapi import FastAPI +from pydantic import BaseModel + +app = FastAPI() + + +class Item(BaseModel): + name: str + price: float + is_offer: Union[bool, None] = None + + +@app.get("/") +def read_root(): + return {"Hello": "World"} + + +@app.get("/items/{item_id}") +def read_item(item_id: int, q: Union[str, None] = None): + return {"item_id": item_id, "q": q} + + +@app.put("/items/{item_id}") +def update_item(item_id: int, item: Item): + return {"item_name": item.name, "item_id": item_id} +``` + +De `fastapi dev` server zou automatisch moeten herladen. + +### Interactieve API documentatie upgrade + +Ga nu naar http://127.0.0.1:8000/docs. + +* De interactieve API-documentatie wordt automatisch bijgewerkt, inclusief de nieuwe body: + +![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* Klik op de knop "Try it out", hiermee kan je de parameters invullen en direct met de API interacteren: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-04-swagger-03.png) + +* Klik vervolgens op de knop "Execute", de gebruikersinterface zal communiceren met jouw API, de parameters verzenden, de resultaten ophalen en deze op het scherm tonen: + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-05-swagger-04.png) + +### Alternatieve API documentatie upgrade + +Ga vervolgens naar http://127.0.0.1:8000/redoc. + +* De alternatieve documentatie zal ook de nieuwe queryparameter en body weergeven: + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### Samenvatting + +Samengevat declareer je **eenmalig** de types van parameters, body, etc. als functieparameters. + +Dat doe je met standaard moderne Python types. + +Je hoeft geen nieuwe syntax te leren, de methods of klassen van een specifieke bibliotheek, etc. + +Gewoon standaard **Python**. + +Bijvoorbeeld, voor een `int`: + +```Python +item_id: int +``` + +of voor een complexer `Item` model: + +```Python +item: Item +``` + +...en met die ene verklaring krijg je: + +* Editor ondersteuning, inclusief: + * Code aanvulling. + * Type validatie. +* Validatie van data: + * Automatische en duidelijke foutboodschappen wanneer de data ongeldig is. + * Validatie zelfs voor diep geneste JSON objecten. +* Conversie van invoergegevens: afkomstig van het netwerk naar Python-data en -types. Zoals: + * JSON. + * Pad parameters. + * Query parameters. + * Cookies. + * Headers. + * Formulieren. + * Bestanden. +* Conversie van uitvoergegevens: converstie van Python-data en -types naar netwerkgegevens (zoals JSON): + * Converteer Python types (`str`, `int`, `float`, `bool`, `list`, etc). + * `datetime` objecten. + * `UUID` objecten. + * Database modellen. + * ...en nog veel meer. +* Automatische interactieve API-documentatie, inclusief 2 alternatieve gebruikersinterfaces: + * Swagger UI. + * ReDoc. + +--- + +Terugkomend op het vorige code voorbeeld, **FastAPI** zal: + +* Valideren dat er een `item_id` bestaat in het pad voor `GET` en `PUT` verzoeken. +* Valideren dat het `item_id` van het type `int` is voor `GET` en `PUT` verzoeken. + * Wanneer dat niet het geval is, krijgt de cliënt een nuttige, duidelijke foutmelding. +* Controleren of er een optionele query parameter is met de naam `q` (zoals in `http://127.0.0.1:8000/items/foo?q=somequery`) voor `GET` verzoeken. + * Aangezien de `q` parameter werd gedeclareerd met `= None`, is deze optioneel. + * Zonder de `None` declaratie zou deze verplicht zijn (net als bij de body in het geval met `PUT`). +* Voor `PUT` verzoeken naar `/items/{item_id}`, lees de body als JSON: + * Controleer of het een verplicht attribuut `naam` heeft en dat dat een `str` is. + * Controleer of het een verplicht attribuut `price` heeft en dat dat een`float` is. + * Controleer of het een optioneel attribuut `is_offer` heeft, dat een `bool` is wanneer het aanwezig is. + * Dit alles werkt ook voor diep geneste JSON objecten. +* Converteer automatisch van en naar JSON. +* Documenteer alles met OpenAPI, dat gebruikt kan worden door: + * Interactieve documentatiesystemen. + * Automatische client code generatie systemen, voor vele talen. +* Biedt 2 interactieve documentatie-webinterfaces aan. + +--- + +Dit was nog maar een snel overzicht, maar je zou nu toch al een idee moeten hebben over hoe het allemaal werkt. + +Probeer deze regel te veranderen: + +```Python + return {"item_name": item.name, "item_id": item_id} +``` + +...van: + +```Python + ... "item_name": item.name ... +``` + +...naar: + +```Python + ... "item_price": item.price ... +``` + +...en zie hoe je editor de attributen automatisch invult en hun types herkent: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +Voor een vollediger voorbeeld met meer mogelijkheden, zie de Tutorial - Gebruikershandleiding. + +**Spoiler alert**: de tutorial - gebruikershandleiding bevat: + +* Declaratie van **parameters** op andere plaatsen zoals: **headers**, **cookies**, **formuliervelden** en **bestanden**. +* Hoe stel je **validatie restricties** in zoals `maximum_length` of een `regex`. +* Een zeer krachtig en eenvoudig te gebruiken **Dependency Injection** systeem. +* Beveiliging en authenticatie, inclusief ondersteuning voor **OAuth2** met **JWT-tokens** en **HTTP Basic** auth. +* Meer geavanceerde (maar even eenvoudige) technieken voor het declareren van **diep geneste JSON modellen** (dankzij Pydantic). +* **GraphQL** integratie met Strawberry en andere packages. +* Veel extra functies (dankzij Starlette) zoals: + * **WebSockets** + * uiterst gemakkelijke tests gebaseerd op HTTPX en `pytest` + * **CORS** + * **Cookie Sessions** + * ...en meer. + +## Prestaties + +Onafhankelijke TechEmpower benchmarks tonen **FastAPI** applicaties draaiend onder Uvicorn aan als een van de snelste Python frameworks beschikbaar, alleen onder Starlette en Uvicorn zelf (intern gebruikt door FastAPI). (*) + +Zie de sectie Benchmarks om hier meer over te lezen. + +## Afhankelijkheden + +FastAPI maakt gebruik van Pydantic en Starlette. + +### `standard` Afhankelijkheden + +Wanneer je FastAPI installeert met `pip install "fastapi[standard]"`, worden de volgende `standard` optionele afhankelijkheden geïnstalleerd: + +Gebruikt door Pydantic: + +* email_validator - voor email validatie. + +Gebruikt door Starlette: + +* httpx - Vereist indien je de `TestClient` wil gebruiken. +* jinja2 - Vereist als je de standaard templateconfiguratie wil gebruiken. +* python-multipart - Vereist indien je "parsen" van formulieren wil ondersteunen met `requests.form()`. + +Gebruikt door FastAPI / Starlette: + +* uvicorn - voor de server die jouw applicatie laadt en bedient. +* `fastapi-cli` - om het `fastapi` commando te voorzien. + +### Zonder `standard` Afhankelijkheden + +Indien je de optionele `standard` afhankelijkheden niet wenst te installeren, kan je installeren met `pip install fastapi` in plaats van `pip install "fastapi[standard]"`. + +### Bijkomende Optionele Afhankelijkheden + +Er zijn nog een aantal bijkomende afhankelijkheden die je eventueel kan installeren. + +Bijkomende optionele afhankelijkheden voor Pydantic: + +* pydantic-settings - voor het beheren van settings. +* pydantic-extra-types - voor extra data types die gebruikt kunnen worden met Pydantic. + +Bijkomende optionele afhankelijkheden voor FastAPI: + +* orjson - Vereist indien je `ORJSONResponse` wil gebruiken. +* ujson - Vereist indien je `UJSONResponse` wil gebruiken. + +## Licentie + +Dit project is gelicenseerd onder de voorwaarden van de MIT licentie. diff --git a/docs/nl/mkdocs.yml b/docs/nl/mkdocs.yml new file mode 100644 index 000000000..de18856f4 --- /dev/null +++ b/docs/nl/mkdocs.yml @@ -0,0 +1 @@ +INHERIT: ../en/mkdocs.yml From ffa6d2eafd8955d3157e77119e07a8b7c09efef2 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 28 Aug 2024 23:44:01 +0000 Subject: [PATCH 49/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 34a3fbc57..6cfbe779b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -18,6 +18,7 @@ hide: ### Translations +* 🌐 Add Dutch translation for `docs/nl/docs/index.md`. PR [#12042](https://github.com/fastapi/fastapi/pull/12042) by [@svlandeg](https://github.com/svlandeg). * 🌐 Update Chinese translation for `docs/zh/docs/how-to/index.md`. PR [#12070](https://github.com/fastapi/fastapi/pull/12070) by [@synthpop123](https://github.com/synthpop123). ### Internal From 4cf3421178d3ecd909cb393f39e52eed5744e44a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Wed, 28 Aug 2024 19:01:29 -0500 Subject: [PATCH 50/88] =?UTF-8?q?=F0=9F=94=A7=20Update=20sponsors,=20remov?= =?UTF-8?q?e=20Kong=20(#12085)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 - docs/en/data/sponsors.yml | 3 --- docs/en/overrides/main.html | 6 ------ 3 files changed, 10 deletions(-) diff --git a/README.md b/README.md index ec7a95497..d8de34e0c 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,6 @@ The key features are: - diff --git a/docs/en/data/sponsors.yml b/docs/en/data/sponsors.yml index 8c0956ac5..76e20638a 100644 --- a/docs/en/data/sponsors.yml +++ b/docs/en/data/sponsors.yml @@ -23,9 +23,6 @@ gold: - url: https://www.mongodb.com/developer/languages/python/python-quickstart-fastapi/?utm_campaign=fastapi_framework&utm_source=fastapi_sponsorship&utm_medium=web_referral title: Simplify Full Stack Development with FastAPI & MongoDB img: https://fastapi.tiangolo.com/img/sponsors/mongodb.png - - url: https://konghq.com/products/kong-konnect?utm_medium=referral&utm_source=github&utm_campaign=platform&utm_content=fast-api - title: Kong Konnect - API management platform - img: https://fastapi.tiangolo.com/img/sponsors/kong.png - url: https://zuplo.link/fastapi-gh title: 'Zuplo: Scale, Protect, Document, and Monetize your FastAPI' img: https://fastapi.tiangolo.com/img/sponsors/zuplo.png diff --git a/docs/en/overrides/main.html b/docs/en/overrides/main.html index 229cbca71..851f8e895 100644 --- a/docs/en/overrides/main.html +++ b/docs/en/overrides/main.html @@ -70,12 +70,6 @@
-
From 17a29149e4a40dd756f0eb02a9317229e6b3e718 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 29 Aug 2024 00:02:01 +0000 Subject: [PATCH 51/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 6cfbe779b..71e7334ad 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -23,6 +23,7 @@ hide: ### Internal +* 🔧 Update sponsors, remove Kong. PR [#12085](https://github.com/fastapi/fastapi/pull/12085) by [@tiangolo](https://github.com/tiangolo). * ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12076](https://github.com/fastapi/fastapi/pull/12076) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). * 👷 Update `latest-changes` GitHub Action. PR [#12073](https://github.com/fastapi/fastapi/pull/12073) by [@tiangolo](https://github.com/tiangolo). From 6e98249c2121959b5253cecc1237ee5438f98758 Mon Sep 17 00:00:00 2001 From: Marcin Sulikowski Date: Fri, 30 Aug 2024 18:00:41 +0200 Subject: [PATCH 52/88] =?UTF-8?q?=F0=9F=93=9D=20Fix=20async=20test=20examp?= =?UTF-8?q?le=20not=20to=20trigger=20DeprecationWarning=20(#12084)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/de/docs/advanced/async-tests.md | 2 +- docs/em/docs/advanced/async-tests.md | 2 +- docs/en/docs/advanced/async-tests.md | 2 +- docs/pt/docs/advanced/async-tests.md | 2 +- docs_src/async_tests/test_main.py | 6 ++++-- 5 files changed, 8 insertions(+), 6 deletions(-) diff --git a/docs/de/docs/advanced/async-tests.md b/docs/de/docs/advanced/async-tests.md index 9f0bd4aa2..e56841faa 100644 --- a/docs/de/docs/advanced/async-tests.md +++ b/docs/de/docs/advanced/async-tests.md @@ -72,7 +72,7 @@ Beachten Sie, dass die Testfunktion jetzt `async def` ist und nicht nur `def` wi Dann können wir einen `AsyncClient` mit der App erstellen und mit `await` asynchrone Requests an ihn senden. -```Python hl_lines="9-10" +```Python hl_lines="9-12" {!../../../docs_src/async_tests/test_main.py!} ``` diff --git a/docs/em/docs/advanced/async-tests.md b/docs/em/docs/advanced/async-tests.md index 324b4f68a..11f885fe6 100644 --- a/docs/em/docs/advanced/async-tests.md +++ b/docs/em/docs/advanced/async-tests.md @@ -72,7 +72,7 @@ $ pytest ⤴️ 👥 💪 ✍ `AsyncClient` ⏮️ 📱, & 📨 🔁 📨 ⚫️, ⚙️ `await`. -```Python hl_lines="9-10" +```Python hl_lines="9-12" {!../../../docs_src/async_tests/test_main.py!} ``` diff --git a/docs/en/docs/advanced/async-tests.md b/docs/en/docs/advanced/async-tests.md index ac459ff0c..580d9142c 100644 --- a/docs/en/docs/advanced/async-tests.md +++ b/docs/en/docs/advanced/async-tests.md @@ -72,7 +72,7 @@ Note that the test function is now `async def` instead of just `def` as before w Then we can create an `AsyncClient` with the app, and send async requests to it, using `await`. -```Python hl_lines="9-10" +```Python hl_lines="9-12" {!../../../docs_src/async_tests/test_main.py!} ``` diff --git a/docs/pt/docs/advanced/async-tests.md b/docs/pt/docs/advanced/async-tests.md index ab5bfa648..7cac26262 100644 --- a/docs/pt/docs/advanced/async-tests.md +++ b/docs/pt/docs/advanced/async-tests.md @@ -72,7 +72,7 @@ Note que a função de teste é `async def` agora, no lugar de apenas `def` como Então podemos criar um `AsyncClient` com a aplicação, e enviar requisições assíncronas para ela utilizando `await`. -```Python hl_lines="9-10" +```Python hl_lines="9-12" {!../../../docs_src/async_tests/test_main.py!} ``` diff --git a/docs_src/async_tests/test_main.py b/docs_src/async_tests/test_main.py index 9f1527d5f..a57a31f7d 100644 --- a/docs_src/async_tests/test_main.py +++ b/docs_src/async_tests/test_main.py @@ -1,12 +1,14 @@ import pytest -from httpx import AsyncClient +from httpx import ASGITransport, AsyncClient from .main import app @pytest.mark.anyio async def test_root(): - async with AsyncClient(app=app, base_url="http://test") as ac: + async with AsyncClient( + transport=ASGITransport(app=app), base_url="http://test" + ) as ac: response = await ac.get("/") assert response.status_code == 200 assert response.json() == {"message": "Tomato"} From 4eec14fa8c8870898cfa0416b6ff20a724c0dd30 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 30 Aug 2024 16:01:05 +0000 Subject: [PATCH 53/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 71e7334ad..83080e0aa 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Fix async test example not to trigger DeprecationWarning. PR [#12084](https://github.com/fastapi/fastapi/pull/12084) by [@marcinsulikowski](https://github.com/marcinsulikowski). * 📝 Update `docs_src/path_params_numeric_validations/tutorial006.py`. PR [#11478](https://github.com/fastapi/fastapi/pull/11478) by [@MuhammadAshiqAmeer](https://github.com/MuhammadAshiqAmeer). * 📝 Update comma in `docs/en/docs/async.md`. PR [#12062](https://github.com/fastapi/fastapi/pull/12062) by [@Alec-Gillis](https://github.com/Alec-Gillis). * 📝 Update docs about serving FastAPI: ASGI servers, Docker containers, etc.. PR [#12069](https://github.com/fastapi/fastapi/pull/12069) by [@tiangolo](https://github.com/tiangolo). From 9519380764a371c4c642f969e8f1b82822f7de28 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Fri, 30 Aug 2024 18:20:21 +0200 Subject: [PATCH 54/88] =?UTF-8?q?=F0=9F=94=A7=20Update=20sponsors:=20Coher?= =?UTF-8?q?ence=20(#12093)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- docs/en/data/sponsors.yml | 2 +- docs/en/docs/deployment/cloud.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index d8de34e0c..5554f71d4 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ The key features are: - + diff --git a/docs/en/data/sponsors.yml b/docs/en/data/sponsors.yml index 76e20638a..3a767b6b1 100644 --- a/docs/en/data/sponsors.yml +++ b/docs/en/data/sponsors.yml @@ -17,7 +17,7 @@ gold: - url: https://www.propelauth.com/?utm_source=fastapi&utm_campaign=1223&utm_medium=mainbadge title: Auth, user management and more for your B2B product img: https://fastapi.tiangolo.com/img/sponsors/propelauth.png - - url: https://docs.withcoherence.com/configuration/frameworks/?utm_medium=advertising&utm_source=fastapi&utm_campaign=docs#fastapi-example + - url: https://docs.withcoherence.com/coherence-templates/full-stack-template/#fastapi?utm_medium=advertising&utm_source=fastapi&utm_campaign=docs 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 diff --git a/docs/en/docs/deployment/cloud.md b/docs/en/docs/deployment/cloud.md index d34fbe2f7..3ea5087f8 100644 --- a/docs/en/docs/deployment/cloud.md +++ b/docs/en/docs/deployment/cloud.md @@ -14,4 +14,4 @@ You might want to try their services and follow their guides: * Platform.sh * Porter -* Coherence +* Coherence From a2458d594facb238f42dc471754612109b5f5c2d Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 30 Aug 2024 16:20:42 +0000 Subject: [PATCH 55/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 83080e0aa..2f7fb0cbd 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 🔧 Update sponsors: Coherence. PR [#12093](https://github.com/fastapi/fastapi/pull/12093) by [@tiangolo](https://github.com/tiangolo). * 📝 Fix async test example not to trigger DeprecationWarning. PR [#12084](https://github.com/fastapi/fastapi/pull/12084) by [@marcinsulikowski](https://github.com/marcinsulikowski). * 📝 Update `docs_src/path_params_numeric_validations/tutorial006.py`. PR [#11478](https://github.com/fastapi/fastapi/pull/11478) by [@MuhammadAshiqAmeer](https://github.com/MuhammadAshiqAmeer). * 📝 Update comma in `docs/en/docs/async.md`. PR [#12062](https://github.com/fastapi/fastapi/pull/12062) by [@Alec-Gillis](https://github.com/Alec-Gillis). From 5827b922c3ebf999eae867dbb855c0bf2aa07a7e Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 31 Aug 2024 03:23:14 +0000 Subject: [PATCH 56/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2f7fb0cbd..d1ac98ed1 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Tweak middleware code sample `time.time()` to `time.perf_counter()`. PR [#11957](https://github.com/fastapi/fastapi/pull/11957) by [@domdent](https://github.com/domdent). * 🔧 Update sponsors: Coherence. PR [#12093](https://github.com/fastapi/fastapi/pull/12093) by [@tiangolo](https://github.com/tiangolo). * 📝 Fix async test example not to trigger DeprecationWarning. PR [#12084](https://github.com/fastapi/fastapi/pull/12084) by [@marcinsulikowski](https://github.com/marcinsulikowski). * 📝 Update `docs_src/path_params_numeric_validations/tutorial006.py`. PR [#11478](https://github.com/fastapi/fastapi/pull/11478) by [@MuhammadAshiqAmeer](https://github.com/MuhammadAshiqAmeer). From c37f2c976dfe71ac46ccc082b551d41cb7b6122f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 31 Aug 2024 12:15:50 +0200 Subject: [PATCH 57/88] =?UTF-8?q?=F0=9F=93=9D=20Add=20note=20about=20`time?= =?UTF-8?q?.perf=5Fcounter()`=20in=20middlewares=20(#12095)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/middleware.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/en/docs/tutorial/middleware.md b/docs/en/docs/tutorial/middleware.md index 06fb3f504..199b593d3 100644 --- a/docs/en/docs/tutorial/middleware.md +++ b/docs/en/docs/tutorial/middleware.md @@ -63,6 +63,12 @@ For example, you could add a custom header `X-Process-Time` containing the time {!../../../docs_src/middleware/tutorial001.py!} ``` +/// tip + +Here we use `time.perf_counter()` instead of `time.time()` because it can be more precise for these use cases. 🤓 + +/// + ## Other middlewares You can later read more about other middlewares in the [Advanced User Guide: Advanced Middleware](../advanced/middleware.md){.internal-link target=_blank}. From 6c8a205db106835c2cd4af5d0b5110f562c2a92f Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 31 Aug 2024 10:16:12 +0000 Subject: [PATCH 58/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d1ac98ed1..e0e9192bd 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Docs +* 📝 Add note about `time.perf_counter()` in middlewares. PR [#12095](https://github.com/fastapi/fastapi/pull/12095) by [@tiangolo](https://github.com/tiangolo). * 📝 Tweak middleware code sample `time.time()` to `time.perf_counter()`. PR [#11957](https://github.com/fastapi/fastapi/pull/11957) by [@domdent](https://github.com/domdent). * 🔧 Update sponsors: Coherence. PR [#12093](https://github.com/fastapi/fastapi/pull/12093) by [@tiangolo](https://github.com/tiangolo). * 📝 Fix async test example not to trigger DeprecationWarning. PR [#12084](https://github.com/fastapi/fastapi/pull/12084) by [@marcinsulikowski](https://github.com/marcinsulikowski). From 0077af97195ec77ab2fcc5a3cf1536c7ed6125d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 31 Aug 2024 12:18:37 +0200 Subject: [PATCH 59/88] =?UTF-8?q?=F0=9F=94=A7=20Update=20labeler=20config?= =?UTF-8?q?=20to=20handle=20sponsorships=20data=20(#12096)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/labeler.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/labeler.yml b/.github/labeler.yml index 1d49a2411..c5b1f84f3 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -7,6 +7,8 @@ docs: - all-globs-to-all-files: - '!fastapi/**' - '!pyproject.toml' + - '!docs/en/data/sponsors.yml' + - '!docs/en/overrides/main.html' lang-all: - all: @@ -28,6 +30,8 @@ internal: - .pre-commit-config.yaml - pdm_build.py - requirements*.txt + - docs/en/data/sponsors.yml + - docs/en/overrides/main.html - all-globs-to-all-files: - '!docs/*/docs/**' - '!fastapi/**' From 83422b1923b070da891bfacec707f4d2c796a32c Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 31 Aug 2024 10:20:40 +0000 Subject: [PATCH 60/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index e0e9192bd..a87ce21d4 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -27,6 +27,7 @@ hide: ### Internal +* 🔧 Update labeler config to handle sponsorships data. PR [#12096](https://github.com/fastapi/fastapi/pull/12096) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update sponsors, remove Kong. PR [#12085](https://github.com/fastapi/fastapi/pull/12085) by [@tiangolo](https://github.com/tiangolo). * ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12076](https://github.com/fastapi/fastapi/pull/12076) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). * 👷 Update `latest-changes` GitHub Action. PR [#12073](https://github.com/fastapi/fastapi/pull/12073) by [@tiangolo](https://github.com/tiangolo). From eebc6c3d54f96cfd056c0a6fe4de7c3b0064ac42 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 31 Aug 2024 17:35:58 +0200 Subject: [PATCH 61/88] =?UTF-8?q?=F0=9F=94=A7=20Update=20sponsors=20link:?= =?UTF-8?q?=20Coherence=20(#12097)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/overrides/main.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/overrides/main.html b/docs/en/overrides/main.html index 851f8e895..47e46c4bf 100644 --- a/docs/en/overrides/main.html +++ b/docs/en/overrides/main.html @@ -59,7 +59,7 @@
- + From 47b3351be9c268a3b79faf9b41bf08921dbc8a8b Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 31 Aug 2024 15:36:24 +0000 Subject: [PATCH 62/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a87ce21d4..855338742 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -27,6 +27,7 @@ hide: ### Internal +* 🔧 Update sponsors link: Coherence. PR [#12097](https://github.com/fastapi/fastapi/pull/12097) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update labeler config to handle sponsorships data. PR [#12096](https://github.com/fastapi/fastapi/pull/12096) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update sponsors, remove Kong. PR [#12085](https://github.com/fastapi/fastapi/pull/12085) by [@tiangolo](https://github.com/tiangolo). * ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#12076](https://github.com/fastapi/fastapi/pull/12076) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). From 581aacc4a9f3bbb872b082ee55535fe60655de2e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 31 Aug 2024 22:19:30 +0200 Subject: [PATCH 63/88] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Refactor=20and=20sim?= =?UTF-8?q?plify=20dependencies=20data=20structures=20with=20dataclasses?= =?UTF-8?q?=20(#12098)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/dependencies/models.py | 75 ++++++++++++---------------------- fastapi/dependencies/utils.py | 2 +- 2 files changed, 28 insertions(+), 49 deletions(-) diff --git a/fastapi/dependencies/models.py b/fastapi/dependencies/models.py index 61ef00638..418c11725 100644 --- a/fastapi/dependencies/models.py +++ b/fastapi/dependencies/models.py @@ -1,58 +1,37 @@ -from typing import Any, Callable, List, Optional, Sequence +from dataclasses import dataclass, field +from typing import Any, Callable, List, Optional, Sequence, Tuple from fastapi._compat import ModelField from fastapi.security.base import SecurityBase +@dataclass class SecurityRequirement: - def __init__( - self, security_scheme: SecurityBase, scopes: Optional[Sequence[str]] = None - ): - self.security_scheme = security_scheme - self.scopes = scopes + security_scheme: SecurityBase + scopes: Optional[Sequence[str]] = None +@dataclass class Dependant: - def __init__( - self, - *, - path_params: Optional[List[ModelField]] = None, - query_params: Optional[List[ModelField]] = None, - header_params: Optional[List[ModelField]] = None, - cookie_params: Optional[List[ModelField]] = None, - body_params: Optional[List[ModelField]] = None, - dependencies: Optional[List["Dependant"]] = None, - security_schemes: Optional[List[SecurityRequirement]] = None, - name: Optional[str] = None, - call: Optional[Callable[..., Any]] = None, - request_param_name: Optional[str] = None, - websocket_param_name: Optional[str] = None, - http_connection_param_name: Optional[str] = None, - response_param_name: Optional[str] = None, - background_tasks_param_name: Optional[str] = None, - security_scopes_param_name: Optional[str] = None, - security_scopes: Optional[List[str]] = None, - use_cache: bool = True, - path: Optional[str] = None, - ) -> None: - self.path_params = path_params or [] - self.query_params = query_params or [] - self.header_params = header_params or [] - self.cookie_params = cookie_params or [] - self.body_params = body_params or [] - self.dependencies = dependencies or [] - self.security_requirements = security_schemes or [] - self.request_param_name = request_param_name - self.websocket_param_name = websocket_param_name - self.http_connection_param_name = http_connection_param_name - self.response_param_name = response_param_name - self.background_tasks_param_name = background_tasks_param_name - self.security_scopes = security_scopes - self.security_scopes_param_name = security_scopes_param_name - self.name = name - self.call = call - self.use_cache = use_cache - # Store the path to be able to re-generate a dependable from it in overrides - self.path = path - # Save the cache key at creation to optimize performance + path_params: List[ModelField] = field(default_factory=list) + query_params: List[ModelField] = field(default_factory=list) + header_params: List[ModelField] = field(default_factory=list) + cookie_params: List[ModelField] = field(default_factory=list) + body_params: List[ModelField] = field(default_factory=list) + dependencies: List["Dependant"] = field(default_factory=list) + security_requirements: List[SecurityRequirement] = field(default_factory=list) + name: Optional[str] = None + call: Optional[Callable[..., Any]] = None + request_param_name: Optional[str] = None + websocket_param_name: Optional[str] = None + http_connection_param_name: Optional[str] = None + response_param_name: Optional[str] = None + background_tasks_param_name: Optional[str] = None + security_scopes_param_name: Optional[str] = None + security_scopes: Optional[List[str]] = None + use_cache: bool = True + path: Optional[str] = None + cache_key: Tuple[Optional[Callable[..., Any]], Tuple[str, ...]] = field(init=False) + + def __post_init__(self) -> None: self.cache_key = (self.call, tuple(sorted(set(self.security_scopes or [])))) diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index 3e8e7b410..85703c9e9 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -175,7 +175,7 @@ def get_flat_dependant( header_params=dependant.header_params.copy(), cookie_params=dependant.cookie_params.copy(), body_params=dependant.body_params.copy(), - security_schemes=dependant.security_requirements.copy(), + security_requirements=dependant.security_requirements.copy(), use_cache=dependant.use_cache, path=dependant.path, ) From 75c4e7fc44fda0c63d5627af65cb0ba7919fd334 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 31 Aug 2024 20:19:51 +0000 Subject: [PATCH 64/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 855338742..a02b722f6 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -7,6 +7,10 @@ hide: ## Latest Changes +### Refactors + +* ♻️ Refactor and simplify dependencies data structures with dataclasses. PR [#12098](https://github.com/fastapi/fastapi/pull/12098) by [@tiangolo](https://github.com/tiangolo). + ### Docs * 📝 Add note about `time.perf_counter()` in middlewares. PR [#12095](https://github.com/fastapi/fastapi/pull/12095) by [@tiangolo](https://github.com/tiangolo). From 08547e1d571df8e8cf71d8b15a767acbc38aea62 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 31 Aug 2024 22:27:44 +0200 Subject: [PATCH 65/88] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Refactor=20and=20sim?= =?UTF-8?q?plify=20internal=20`analyze=5Fparam()`=20to=20structure=20data?= =?UTF-8?q?=20with=20dataclasses=20instead=20of=20tuple=20(#12099)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/dependencies/utils.py | 30 +++++++++++++++++++----------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index 85703c9e9..5ebdddaf6 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -1,6 +1,7 @@ import inspect from contextlib import AsyncExitStack, contextmanager from copy import copy, deepcopy +from dataclasses import dataclass from typing import ( Any, Callable, @@ -258,16 +259,16 @@ def get_dependant( ) for param_name, param in signature_params.items(): is_path_param = param_name in path_param_names - type_annotation, depends, param_field = analyze_param( + param_details = analyze_param( param_name=param_name, annotation=param.annotation, value=param.default, is_path_param=is_path_param, ) - if depends is not None: + if param_details.depends is not None: sub_dependant = get_param_sub_dependant( param_name=param_name, - depends=depends, + depends=param_details.depends, path=path, security_scopes=security_scopes, ) @@ -275,18 +276,18 @@ def get_dependant( continue if add_non_field_param_to_dependency( param_name=param_name, - type_annotation=type_annotation, + type_annotation=param_details.type_annotation, dependant=dependant, ): assert ( - param_field is None + param_details.field is None ), f"Cannot specify multiple FastAPI annotations for {param_name!r}" continue - assert param_field is not None - if is_body_param(param_field=param_field, is_path_param=is_path_param): - dependant.body_params.append(param_field) + assert param_details.field is not None + if is_body_param(param_field=param_details.field, is_path_param=is_path_param): + dependant.body_params.append(param_details.field) else: - add_param_to_fields(field=param_field, dependant=dependant) + add_param_to_fields(field=param_details.field, dependant=dependant) return dependant @@ -314,13 +315,20 @@ def add_non_field_param_to_dependency( return None +@dataclass +class ParamDetails: + type_annotation: Any + depends: Optional[params.Depends] + field: Optional[ModelField] + + def analyze_param( *, param_name: str, annotation: Any, value: Any, is_path_param: bool, -) -> Tuple[Any, Optional[params.Depends], Optional[ModelField]]: +) -> ParamDetails: field_info = None depends = None type_annotation: Any = Any @@ -450,7 +458,7 @@ def analyze_param( field_info=field_info, ) - return type_annotation, depends, field + return ParamDetails(type_annotation=type_annotation, depends=depends, field=field) def is_body_param(*, param_field: ModelField, is_path_param: bool) -> bool: From 8d7d89e8c603ca13043ce037503c66cc6a662a48 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 31 Aug 2024 20:28:07 +0000 Subject: [PATCH 66/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a02b722f6..677816f40 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ♻️ Refactor and simplify internal `analyze_param()` to structure data with dataclasses instead of tuple. PR [#12099](https://github.com/fastapi/fastapi/pull/12099) by [@tiangolo](https://github.com/tiangolo). * ♻️ Refactor and simplify dependencies data structures with dataclasses. PR [#12098](https://github.com/fastapi/fastapi/pull/12098) by [@tiangolo](https://github.com/tiangolo). ### Docs From 5b7fa3900e3156dcb93f496516740bc06903d7d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sat, 31 Aug 2024 22:52:06 +0200 Subject: [PATCH 67/88] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Refactor=20and=20sim?= =?UTF-8?q?plify=20internal=20data=20from=20`solve=5Fdependencies()`=20usi?= =?UTF-8?q?ng=20dataclasses=20(#12100)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/dependencies/utils.py | 45 +++++++++++++++++++---------------- fastapi/routing.py | 33 +++++++++++++++---------- 2 files changed, 45 insertions(+), 33 deletions(-) diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index 5ebdddaf6..ed03df88b 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -529,6 +529,15 @@ async def solve_generator( return await stack.enter_async_context(cm) +@dataclass +class SolvedDependency: + values: Dict[str, Any] + errors: List[Any] + background_tasks: Optional[StarletteBackgroundTasks] + response: Response + dependency_cache: Dict[Tuple[Callable[..., Any], Tuple[str]], Any] + + async def solve_dependencies( *, request: Union[Request, WebSocket], @@ -539,13 +548,7 @@ async def solve_dependencies( dependency_overrides_provider: Optional[Any] = None, dependency_cache: Optional[Dict[Tuple[Callable[..., Any], Tuple[str]], Any]] = None, async_exit_stack: AsyncExitStack, -) -> Tuple[ - Dict[str, Any], - List[Any], - Optional[StarletteBackgroundTasks], - Response, - Dict[Tuple[Callable[..., Any], Tuple[str]], Any], -]: +) -> SolvedDependency: values: Dict[str, Any] = {} errors: List[Any] = [] if response is None: @@ -587,27 +590,21 @@ async def solve_dependencies( dependency_cache=dependency_cache, async_exit_stack=async_exit_stack, ) - ( - sub_values, - sub_errors, - background_tasks, - _, # the subdependency returns the same response we have - sub_dependency_cache, - ) = solved_result - dependency_cache.update(sub_dependency_cache) - if sub_errors: - errors.extend(sub_errors) + background_tasks = solved_result.background_tasks + dependency_cache.update(solved_result.dependency_cache) + if solved_result.errors: + errors.extend(solved_result.errors) continue if sub_dependant.use_cache and sub_dependant.cache_key in dependency_cache: solved = dependency_cache[sub_dependant.cache_key] elif is_gen_callable(call) or is_async_gen_callable(call): solved = await solve_generator( - call=call, stack=async_exit_stack, sub_values=sub_values + call=call, stack=async_exit_stack, sub_values=solved_result.values ) elif is_coroutine_callable(call): - solved = await call(**sub_values) + solved = await call(**solved_result.values) else: - solved = await run_in_threadpool(call, **sub_values) + solved = await run_in_threadpool(call, **solved_result.values) if sub_dependant.name is not None: values[sub_dependant.name] = solved if sub_dependant.cache_key not in dependency_cache: @@ -654,7 +651,13 @@ async def solve_dependencies( values[dependant.security_scopes_param_name] = SecurityScopes( scopes=dependant.security_scopes ) - return values, errors, background_tasks, response, dependency_cache + return SolvedDependency( + values=values, + errors=errors, + background_tasks=background_tasks, + response=response, + dependency_cache=dependency_cache, + ) def request_params_to_args( diff --git a/fastapi/routing.py b/fastapi/routing.py index 49f1b6013..c46772017 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -292,26 +292,34 @@ def get_request_handler( dependency_overrides_provider=dependency_overrides_provider, async_exit_stack=async_exit_stack, ) - values, errors, background_tasks, sub_response, _ = solved_result + errors = solved_result.errors if not errors: raw_response = await run_endpoint_function( - dependant=dependant, values=values, is_coroutine=is_coroutine + dependant=dependant, + values=solved_result.values, + is_coroutine=is_coroutine, ) if isinstance(raw_response, Response): if raw_response.background is None: - raw_response.background = background_tasks + raw_response.background = solved_result.background_tasks response = raw_response else: - response_args: Dict[str, Any] = {"background": background_tasks} + response_args: Dict[str, Any] = { + "background": solved_result.background_tasks + } # If status_code was set, use it, otherwise use the default from the # response class, in the case of redirect it's 307 current_status_code = ( - status_code if status_code else sub_response.status_code + status_code + if status_code + else solved_result.response.status_code ) if current_status_code is not None: response_args["status_code"] = current_status_code - if sub_response.status_code: - response_args["status_code"] = sub_response.status_code + if solved_result.response.status_code: + response_args["status_code"] = ( + solved_result.response.status_code + ) content = await serialize_response( field=response_field, response_content=raw_response, @@ -326,7 +334,7 @@ def get_request_handler( response = actual_response_class(content, **response_args) if not is_body_allowed_for_status_code(response.status_code): response.body = b"" - response.headers.raw.extend(sub_response.headers.raw) + response.headers.raw.extend(solved_result.response.headers.raw) if errors: validation_error = RequestValidationError( _normalize_errors(errors), body=body @@ -360,11 +368,12 @@ def get_websocket_app( dependency_overrides_provider=dependency_overrides_provider, async_exit_stack=async_exit_stack, ) - values, errors, _, _2, _3 = solved_result - if errors: - raise WebSocketRequestValidationError(_normalize_errors(errors)) + if solved_result.errors: + raise WebSocketRequestValidationError( + _normalize_errors(solved_result.errors) + ) assert dependant.call is not None, "dependant.call must be a function" - await dependant.call(**values) + await dependant.call(**solved_result.values) return app From 3660c7a063ddc605269b0c204acd4724ccf2d69c Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 31 Aug 2024 20:52:29 +0000 Subject: [PATCH 68/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 677816f40..3fc659cbb 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ♻️ Refactor and simplify internal data from `solve_dependencies()` using dataclasses. PR [#12100](https://github.com/fastapi/fastapi/pull/12100) by [@tiangolo](https://github.com/tiangolo). * ♻️ Refactor and simplify internal `analyze_param()` to structure data with dataclasses instead of tuple. PR [#12099](https://github.com/fastapi/fastapi/pull/12099) by [@tiangolo](https://github.com/tiangolo). * ♻️ Refactor and simplify dependencies data structures with dataclasses. PR [#12098](https://github.com/fastapi/fastapi/pull/12098) by [@tiangolo](https://github.com/tiangolo). From d08b95ea57fa5740c8c04da554f2b6e259f4dea4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sun, 1 Sep 2024 01:46:03 +0200 Subject: [PATCH 69/88] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Rename=20internal=20?= =?UTF-8?q?`create=5Fresponse=5Ffield()`=20to=20`create=5Fmodel=5Ffield()`?= =?UTF-8?q?=20as=20it's=20used=20for=20more=20than=20response=20models=20(?= =?UTF-8?q?#12103)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/dependencies/utils.py | 6 +++--- fastapi/routing.py | 6 +++--- fastapi/utils.py | 9 +++------ 3 files changed, 9 insertions(+), 12 deletions(-) diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index ed03df88b..c5ed709f7 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -55,7 +55,7 @@ from fastapi.logger import logger from fastapi.security.base import SecurityBase from fastapi.security.oauth2 import OAuth2, SecurityScopes from fastapi.security.open_id_connect_url import OpenIdConnect -from fastapi.utils import create_response_field, get_path_param_names +from fastapi.utils import create_model_field, get_path_param_names from pydantic.fields import FieldInfo from starlette.background import BackgroundTasks as StarletteBackgroundTasks from starlette.concurrency import run_in_threadpool @@ -449,7 +449,7 @@ def analyze_param( else: alias = field_info.alias or param_name field_info.alias = alias - field = create_response_field( + field = create_model_field( name=param_name, type_=use_annotation_from_field_info, default=field_info.default, @@ -818,7 +818,7 @@ def get_body_field(*, dependant: Dependant, name: str) -> Optional[ModelField]: ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] - final_field = create_response_field( + final_field = create_model_field( name="body", type_=BodyModel, required=required, diff --git a/fastapi/routing.py b/fastapi/routing.py index c46772017..61a112fc4 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -49,7 +49,7 @@ from fastapi.exceptions import ( from fastapi.types import DecoratedCallable, IncEx from fastapi.utils import ( create_cloned_field, - create_response_field, + create_model_field, generate_unique_id, get_value_or_default, is_body_allowed_for_status_code, @@ -497,7 +497,7 @@ class APIRoute(routing.Route): status_code ), f"Status code {status_code} must not have a response body" response_name = "Response_" + self.unique_id - self.response_field = create_response_field( + self.response_field = create_model_field( name=response_name, type_=self.response_model, mode="serialization", @@ -530,7 +530,7 @@ class APIRoute(routing.Route): additional_status_code ), f"Status code {additional_status_code} must not have a response body" response_name = f"Response_{additional_status_code}_{self.unique_id}" - response_field = create_response_field(name=response_name, type_=model) + response_field = create_model_field(name=response_name, type_=model) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: Dict[Union[int, str], ModelField] = response_fields diff --git a/fastapi/utils.py b/fastapi/utils.py index 5c2538fac..4c7350fea 100644 --- a/fastapi/utils.py +++ b/fastapi/utils.py @@ -60,9 +60,9 @@ def get_path_param_names(path: str) -> Set[str]: return set(re.findall("{(.*?)}", path)) -def create_response_field( +def create_model_field( name: str, - type_: Type[Any], + type_: Any, class_validators: Optional[Dict[str, Validator]] = None, default: Optional[Any] = Undefined, required: Union[bool, UndefinedType] = Undefined, @@ -71,9 +71,6 @@ def create_response_field( alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", ) -> ModelField: - """ - Create a new response field. Raises if type_ is invalid. - """ class_validators = class_validators or {} if PYDANTIC_V2: field_info = field_info or FieldInfo( @@ -135,7 +132,7 @@ def create_cloned_field( use_type.__fields__[f.name] = create_cloned_field( f, cloned_types=cloned_types ) - new_field = create_response_field(name=field.name, type_=use_type) + new_field = create_model_field(name=field.name, type_=use_type) new_field.has_alias = field.has_alias # type: ignore[attr-defined] new_field.alias = field.alias # type: ignore[misc] new_field.class_validators = field.class_validators # type: ignore[attr-defined] From d5c6cf8122cd8de3d4fcd37b616fbfa2ade1542b Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 31 Aug 2024 23:46:26 +0000 Subject: [PATCH 70/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 3fc659cbb..d7b278dbe 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ♻️ Rename internal `create_response_field()` to `create_model_field()` as it's used for more than response models. PR [#12103](https://github.com/fastapi/fastapi/pull/12103) by [@tiangolo](https://github.com/tiangolo). * ♻️ Refactor and simplify internal data from `solve_dependencies()` using dataclasses. PR [#12100](https://github.com/fastapi/fastapi/pull/12100) by [@tiangolo](https://github.com/tiangolo). * ♻️ Refactor and simplify internal `analyze_param()` to structure data with dataclasses instead of tuple. PR [#12099](https://github.com/fastapi/fastapi/pull/12099) by [@tiangolo](https://github.com/tiangolo). * ♻️ Refactor and simplify dependencies data structures with dataclasses. PR [#12098](https://github.com/fastapi/fastapi/pull/12098) by [@tiangolo](https://github.com/tiangolo). From 23bda0ffeb26e906b5dcf58423522ab4166669ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sun, 1 Sep 2024 21:39:25 +0200 Subject: [PATCH 71/88] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Refactor=20internal?= =?UTF-8?q?=20`check=5Ffile=5Ffield()`,=20rename=20to=20`ensure=5Fmultipar?= =?UTF-8?q?t=5Fis=5Finstalled()`=20to=20clarify=20its=20purpose=20(#12106)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/dependencies/utils.py | 47 ++++++++++++++++++++--------------- 1 file changed, 27 insertions(+), 20 deletions(-) diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index c5ed709f7..0dcba62f1 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -80,25 +80,23 @@ multipart_incorrect_install_error = ( ) -def check_file_field(field: ModelField) -> None: - field_info = field.field_info - if isinstance(field_info, params.Form): +def ensure_multipart_is_installed() -> None: + try: + # __version__ is available in both multiparts, and can be mocked + from multipart import __version__ # type: ignore + + assert __version__ try: - # __version__ is available in both multiparts, and can be mocked - from multipart import __version__ # type: ignore - - assert __version__ - try: - # parse_options_header is only available in the right multipart - from multipart.multipart import parse_options_header # type: ignore - - assert parse_options_header - except ImportError: - logger.error(multipart_incorrect_install_error) - raise RuntimeError(multipart_incorrect_install_error) from None + # parse_options_header is only available in the right multipart + from multipart.multipart import parse_options_header # type: ignore + + assert parse_options_header except ImportError: - logger.error(multipart_not_installed_error) - raise RuntimeError(multipart_not_installed_error) from None + logger.error(multipart_incorrect_install_error) + raise RuntimeError(multipart_incorrect_install_error) from None + except ImportError: + logger.error(multipart_not_installed_error) + raise RuntimeError(multipart_not_installed_error) from None def get_param_sub_dependant( @@ -336,6 +334,7 @@ def analyze_param( if annotation is not inspect.Signature.empty: use_annotation = annotation type_annotation = annotation + # Extract Annotated info if get_origin(use_annotation) is Annotated: annotated_args = get_args(annotation) type_annotation = annotated_args[0] @@ -355,6 +354,7 @@ def analyze_param( ) else: fastapi_annotation = None + # Set default for Annotated FieldInfo if isinstance(fastapi_annotation, FieldInfo): # Copy `field_info` because we mutate `field_info.default` below. field_info = copy_field_info( @@ -369,9 +369,10 @@ def analyze_param( field_info.default = value else: field_info.default = Required + # Get Annotated Depends elif isinstance(fastapi_annotation, params.Depends): depends = fastapi_annotation - + # Get Depends from default value if isinstance(value, params.Depends): assert depends is None, ( "Cannot specify `Depends` in `Annotated` and default value" @@ -382,6 +383,7 @@ def analyze_param( f" default value together for {param_name!r}" ) depends = value + # Get FieldInfo from default value elif isinstance(value, FieldInfo): assert field_info is None, ( "Cannot specify FastAPI annotations in `Annotated` and default value" @@ -391,11 +393,13 @@ def analyze_param( if PYDANTIC_V2: field_info.annotation = type_annotation + # Get Depends from type annotation if depends is not None and depends.dependency is None: # Copy `depends` before mutating it depends = copy(depends) depends.dependency = type_annotation + # Handle non-param type annotations like Request if lenient_issubclass( type_annotation, ( @@ -411,6 +415,7 @@ def analyze_param( assert ( field_info is None ), f"Cannot specify FastAPI annotation for type {type_annotation!r}" + # Handle default assignations, neither field_info nor depends was not found in Annotated nor default value elif field_info is None and depends is None: default_value = value if value is not inspect.Signature.empty else Required if is_path_param: @@ -428,7 +433,9 @@ def analyze_param( field_info = params.Query(annotation=use_annotation, default=default_value) field = None + # It's a field_info, not a dependency if field_info is not None: + # Handle field_info.in_ if is_path_param: assert isinstance(field_info, params.Path), ( f"Cannot use `{field_info.__class__.__name__}` for path param" @@ -444,6 +451,8 @@ def analyze_param( field_info, param_name, ) + if isinstance(field_info, params.Form): + ensure_multipart_is_installed() if not field_info.alias and getattr(field_info, "convert_underscores", None): alias = param_name.replace("_", "-") else: @@ -786,7 +795,6 @@ def get_body_field(*, dependant: Dependant, name: str) -> Optional[ModelField]: embed = getattr(field_info, "embed", None) body_param_names_set = {param.name for param in flat_dependant.body_params} if len(body_param_names_set) == 1 and not embed: - check_file_field(first_param) return first_param # If one field requires to embed, all have to be embedded # in case a sub-dependency is evaluated with a single unique body field @@ -825,5 +833,4 @@ def get_body_field(*, dependant: Dependant, name: str) -> Optional[ModelField]: alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), ) - check_file_field(final_field) return final_field From b203d7a15fb5b49635bd81811e09ad94700f68a6 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 1 Sep 2024 19:39:46 +0000 Subject: [PATCH 72/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index d7b278dbe..c3e7c3590 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -9,6 +9,7 @@ hide: ### Refactors +* ♻️ Refactor internal `check_file_field()`, rename to `ensure_multipart_is_installed()` to clarify its purpose. PR [#12106](https://github.com/fastapi/fastapi/pull/12106) by [@tiangolo](https://github.com/tiangolo). * ♻️ Rename internal `create_response_field()` to `create_model_field()` as it's used for more than response models. PR [#12103](https://github.com/fastapi/fastapi/pull/12103) by [@tiangolo](https://github.com/tiangolo). * ♻️ Refactor and simplify internal data from `solve_dependencies()` using dataclasses. PR [#12100](https://github.com/fastapi/fastapi/pull/12100) by [@tiangolo](https://github.com/tiangolo). * ♻️ Refactor and simplify internal `analyze_param()` to structure data with dataclasses instead of tuple. PR [#12099](https://github.com/fastapi/fastapi/pull/12099) by [@tiangolo](https://github.com/tiangolo). From 92bdfbc7bac466e502872a1ddf6e7cae069fd068 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 2 Sep 2024 21:36:52 +0200 Subject: [PATCH 73/88] =?UTF-8?q?=E2=AC=86=20Bump=20pypa/gh-action-pypi-pu?= =?UTF-8?q?blish=20from=201.9.0=20to=201.10.0=20(#12112)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [pypa/gh-action-pypi-publish](https://github.com/pypa/gh-action-pypi-publish) from 1.9.0 to 1.10.0. - [Release notes](https://github.com/pypa/gh-action-pypi-publish/releases) - [Commits](https://github.com/pypa/gh-action-pypi-publish/compare/v1.9.0...v1.10.0) --- updated-dependencies: - dependency-name: pypa/gh-action-pypi-publish dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/publish.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 591df634b..03f87d172 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -35,7 +35,7 @@ jobs: TIANGOLO_BUILD_PACKAGE: ${{ matrix.package }} run: python -m build - name: Publish - uses: pypa/gh-action-pypi-publish@v1.9.0 + uses: pypa/gh-action-pypi-publish@v1.10.0 - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} From 17f1f7b5bde8a75197c3aef7d4d24b04f8438083 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 2 Sep 2024 19:37:19 +0000 Subject: [PATCH 74/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index c3e7c3590..bc431dfac 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -35,6 +35,7 @@ hide: ### Internal +* ⬆ Bump pypa/gh-action-pypi-publish from 1.9.0 to 1.10.0. PR [#12112](https://github.com/fastapi/fastapi/pull/12112) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔧 Update sponsors link: Coherence. PR [#12097](https://github.com/fastapi/fastapi/pull/12097) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update labeler config to handle sponsorships data. PR [#12096](https://github.com/fastapi/fastapi/pull/12096) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update sponsors, remove Kong. PR [#12085](https://github.com/fastapi/fastapi/pull/12085) by [@tiangolo](https://github.com/tiangolo). From b63b4189eedc9e586fb51705a0a29ace8fa6a6d1 Mon Sep 17 00:00:00 2001 From: Sofie Van Landeghem Date: Mon, 2 Sep 2024 21:53:53 +0200 Subject: [PATCH 75/88] =?UTF-8?q?=F0=9F=92=9A=20Set=20`include-hidden-file?= =?UTF-8?q?s`=20to=20`True`=20when=20using=20the=20`upload-artifact`=20GH?= =?UTF-8?q?=20action=20(#12118)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * include-hidden-files when uploading coverage files * include-hidden-files when building docs --- .github/workflows/build-docs.yml | 1 + .github/workflows/test.yml | 2 ++ 2 files changed, 3 insertions(+) diff --git a/.github/workflows/build-docs.yml b/.github/workflows/build-docs.yml index e46629e9b..52c34a49e 100644 --- a/.github/workflows/build-docs.yml +++ b/.github/workflows/build-docs.yml @@ -113,6 +113,7 @@ jobs: with: name: docs-site-${{ matrix.lang }} path: ./site/** + include-hidden-files: true # https://github.com/marketplace/actions/alls-green#why docs-all-green: # This job does nothing and is only used for the branch protection diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 0458f83ff..e9db49b51 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -91,6 +91,7 @@ jobs: with: name: coverage-${{ matrix.python-version }}-${{ matrix.pydantic-version }} path: coverage + include-hidden-files: true coverage-combine: needs: [test] @@ -123,6 +124,7 @@ jobs: with: name: coverage-html path: htmlcov + include-hidden-files: true # https://github.com/marketplace/actions/alls-green#why check: # This job does nothing and is only used for the branch protection From a6ad088183d860c8f985a5e14f916efe77ff5011 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 2 Sep 2024 19:54:19 +0000 Subject: [PATCH 76/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index bc431dfac..4774f8af9 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -35,6 +35,7 @@ hide: ### Internal +* 💚 Set `include-hidden-files` to `True` when using the `upload-artifact` GH action. PR [#12118](https://github.com/fastapi/fastapi/pull/12118) by [@svlandeg](https://github.com/svlandeg). * ⬆ Bump pypa/gh-action-pypi-publish from 1.9.0 to 1.10.0. PR [#12112](https://github.com/fastapi/fastapi/pull/12112) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔧 Update sponsors link: Coherence. PR [#12097](https://github.com/fastapi/fastapi/pull/12097) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update labeler config to handle sponsorships data. PR [#12096](https://github.com/fastapi/fastapi/pull/12096) by [@tiangolo](https://github.com/tiangolo). From 6b3d1c6d4e84447e310584ee62eaa231636a63d3 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 3 Sep 2024 15:15:17 +0200 Subject: [PATCH 77/88] =?UTF-8?q?=E2=AC=86=20Bump=20pillow=20from=2010.3.0?= =?UTF-8?q?=20to=2010.4.0=20(#12105)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [pillow](https://github.com/python-pillow/Pillow) from 10.3.0 to 10.4.0. - [Release notes](https://github.com/python-pillow/Pillow/releases) - [Changelog](https://github.com/python-pillow/Pillow/blob/main/CHANGES.rst) - [Commits](https://github.com/python-pillow/Pillow/compare/10.3.0...10.4.0) --- updated-dependencies: - dependency-name: pillow dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- requirements-docs.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-docs.txt b/requirements-docs.txt index ab2b0165b..332fd1857 100644 --- a/requirements-docs.txt +++ b/requirements-docs.txt @@ -8,7 +8,7 @@ pyyaml >=5.3.1,<7.0.0 # For Material for MkDocs, Chinese search jieba==0.42.1 # For image processing by Material for MkDocs -pillow==10.3.0 +pillow==10.4.0 # For image processing by Material for MkDocs cairosvg==2.7.1 mkdocstrings[python]==0.25.1 From 7537bac43f1bcbf1edde837422cd4b720317c26b Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 3 Sep 2024 13:15:41 +0000 Subject: [PATCH 78/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 4774f8af9..27900f269 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -35,6 +35,7 @@ hide: ### Internal +* ⬆ Bump pillow from 10.3.0 to 10.4.0. PR [#12105](https://github.com/fastapi/fastapi/pull/12105) by [@dependabot[bot]](https://github.com/apps/dependabot). * 💚 Set `include-hidden-files` to `True` when using the `upload-artifact` GH action. PR [#12118](https://github.com/fastapi/fastapi/pull/12118) by [@svlandeg](https://github.com/svlandeg). * ⬆ Bump pypa/gh-action-pypi-publish from 1.9.0 to 1.10.0. PR [#12112](https://github.com/fastapi/fastapi/pull/12112) by [@dependabot[bot]](https://github.com/apps/dependabot). * 🔧 Update sponsors link: Coherence. PR [#12097](https://github.com/fastapi/fastapi/pull/12097) by [@tiangolo](https://github.com/tiangolo). From c1c57336b04d17077a142ec39724e9fb1a1d8bec Mon Sep 17 00:00:00 2001 From: Rafael de Oliveira Marques Date: Tue, 3 Sep 2024 10:43:56 -0300 Subject: [PATCH 79/88] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20transla?= =?UTF-8?q?tion=20for=20`docs/pt/docs/advanced/security/index.md`=20(#1211?= =?UTF-8?q?4)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/advanced/security/index.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 docs/pt/docs/advanced/security/index.md diff --git a/docs/pt/docs/advanced/security/index.md b/docs/pt/docs/advanced/security/index.md new file mode 100644 index 000000000..ae63f1c96 --- /dev/null +++ b/docs/pt/docs/advanced/security/index.md @@ -0,0 +1,19 @@ +# Segurança Avançada + +## Funcionalidades Adicionais + +Existem algumas funcionalidades adicionais para lidar com segurança além das cobertas em [Tutorial - Guia de Usuário: Segurança](../../tutorial/security/index.md){.internal-link target=_blank}. + +/// tip | "Dica" + +As próximas seções **não são necessariamente "avançadas"**. + +E é possível que para o seu caso de uso, a solução está em uma delas. + +/// + +## Leia o Tutorial primeiro + +As próximas seções pressupõem que você já leu o principal [Tutorial - Guia de Usuário: Segurança](../../tutorial/security/index.md){.internal-link target=_blank}. + +Todas elas são baseadas nos mesmos conceitos, mas permitem algumas funcionalidades extras. From e26229ed98f8c1e9ccfbf4274157c554e5cd80f3 Mon Sep 17 00:00:00 2001 From: Rafael de Oliveira Marques Date: Tue, 3 Sep 2024 10:44:35 -0300 Subject: [PATCH 80/88] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20transla?= =?UTF-8?q?tion=20for=20`docs/pt/docs/advanced/testing-events.md`=20(#1210?= =?UTF-8?q?8)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/pt/docs/advanced/testing-events.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 docs/pt/docs/advanced/testing-events.md diff --git a/docs/pt/docs/advanced/testing-events.md b/docs/pt/docs/advanced/testing-events.md new file mode 100644 index 000000000..392fb741c --- /dev/null +++ b/docs/pt/docs/advanced/testing-events.md @@ -0,0 +1,7 @@ +# Testando Eventos: inicialização - encerramento + +Quando você precisa que os seus manipuladores de eventos (`startup` e `shutdown`) sejam executados em seus testes, você pode utilizar o `TestClient` usando a instrução `with`: + +```Python hl_lines="9-12 20-24" +{!../../../docs_src/app_testing/tutorial003.py!} +``` From 56cfecc1bfef14506d50eb46b676dc832b85b914 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 3 Sep 2024 13:44:55 +0000 Subject: [PATCH 81/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 27900f269..2f871a5c4 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -30,6 +30,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/security/index.md`. PR [#12114](https://github.com/fastapi/fastapi/pull/12114) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Dutch translation for `docs/nl/docs/index.md`. PR [#12042](https://github.com/fastapi/fastapi/pull/12042) by [@svlandeg](https://github.com/svlandeg). * 🌐 Update Chinese translation for `docs/zh/docs/how-to/index.md`. PR [#12070](https://github.com/fastapi/fastapi/pull/12070) by [@synthpop123](https://github.com/synthpop123). From 7d69943a22aada657b2326cec43ac6a3023d8203 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 3 Sep 2024 13:45:21 +0000 Subject: [PATCH 82/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 2f871a5c4..a9acd0278 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -30,6 +30,7 @@ hide: ### Translations +* 🌐 Add Portuguese translation for `docs/pt/docs/advanced/testing-events.md`. PR [#12108](https://github.com/fastapi/fastapi/pull/12108) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/security/index.md`. PR [#12114](https://github.com/fastapi/fastapi/pull/12114) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Dutch translation for `docs/nl/docs/index.md`. PR [#12042](https://github.com/fastapi/fastapi/pull/12042) by [@svlandeg](https://github.com/svlandeg). * 🌐 Update Chinese translation for `docs/zh/docs/how-to/index.md`. PR [#12070](https://github.com/fastapi/fastapi/pull/12070) by [@synthpop123](https://github.com/synthpop123). From 7eae92544351036aa1ab0c70e7dea8e53eae97c9 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 3 Sep 2024 15:47:08 +0200 Subject: [PATCH 83/88] =?UTF-8?q?=E2=AC=86=20Bump=20pypa/gh-action-pypi-pu?= =?UTF-8?q?blish=20from=201.10.0=20to=201.10.1=20(#12120)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [pypa/gh-action-pypi-publish](https://github.com/pypa/gh-action-pypi-publish) from 1.10.0 to 1.10.1. - [Release notes](https://github.com/pypa/gh-action-pypi-publish/releases) - [Commits](https://github.com/pypa/gh-action-pypi-publish/compare/v1.10.0...v1.10.1) --- updated-dependencies: - dependency-name: pypa/gh-action-pypi-publish dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/publish.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 03f87d172..5004b94dd 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -35,7 +35,7 @@ jobs: TIANGOLO_BUILD_PACKAGE: ${{ matrix.package }} run: python -m build - name: Publish - uses: pypa/gh-action-pypi-publish@v1.10.0 + uses: pypa/gh-action-pypi-publish@v1.10.1 - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} From 560c43269dbd4b3c2964a69cfb1487567dfcb80e Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 3 Sep 2024 13:49:34 +0000 Subject: [PATCH 84/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a9acd0278..a82965aa8 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -37,6 +37,7 @@ hide: ### Internal +* ⬆ Bump pypa/gh-action-pypi-publish from 1.10.0 to 1.10.1. PR [#12120](https://github.com/fastapi/fastapi/pull/12120) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ Bump pillow from 10.3.0 to 10.4.0. PR [#12105](https://github.com/fastapi/fastapi/pull/12105) by [@dependabot[bot]](https://github.com/apps/dependabot). * 💚 Set `include-hidden-files` to `True` when using the `upload-artifact` GH action. PR [#12118](https://github.com/fastapi/fastapi/pull/12118) by [@svlandeg](https://github.com/svlandeg). * ⬆ Bump pypa/gh-action-pypi-publish from 1.9.0 to 1.10.0. PR [#12112](https://github.com/fastapi/fastapi/pull/12112) by [@dependabot[bot]](https://github.com/apps/dependabot). From 3feed9dd8c826a11354377c7a81b4d95382413d0 Mon Sep 17 00:00:00 2001 From: Max Scheijen <47034840+maxscheijen@users.noreply.github.com> Date: Tue, 3 Sep 2024 15:50:38 +0200 Subject: [PATCH 85/88] =?UTF-8?q?=F0=9F=8C=90=20=20Add=20Dutch=20translati?= =?UTF-8?q?on=20for=20`docs/nl/docs/features.md`=20(#12101)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/nl/docs/features.md | 201 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 201 insertions(+) create mode 100644 docs/nl/docs/features.md diff --git a/docs/nl/docs/features.md b/docs/nl/docs/features.md new file mode 100644 index 000000000..848b155ec --- /dev/null +++ b/docs/nl/docs/features.md @@ -0,0 +1,201 @@ +# Functionaliteit + +## FastAPI functionaliteit + +**FastAPI** biedt je het volgende: + +### Gebaseerd op open standaarden + +* OpenAPI voor het maken van API's, inclusief declaraties van padbewerkingen, parameters, request bodies, beveiliging, enz. +* Automatische datamodel documentatie met JSON Schema (aangezien OpenAPI zelf is gebaseerd op JSON Schema). +* Ontworpen op basis van deze standaarden, na zorgvuldig onderzoek. In plaats van achteraf deze laag er bovenop te bouwen. +* Dit maakt het ook mogelijk om automatisch **clientcode te genereren** in verschillende programmeertalen. + +### Automatische documentatie + +Interactieve API-documentatie en verkenning van webgebruikersinterfaces. Aangezien dit framework is gebaseerd op OpenAPI, zijn er meerdere documentatie opties mogelijk, waarvan er standaard 2 zijn inbegrepen. + +* Swagger UI, met interactieve interface, maakt het mogelijk je API rechtstreeks vanuit de browser aan te roepen en te testen. + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* Alternatieve API-documentatie met ReDoc. + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### Gewoon Moderne Python + +Het is allemaal gebaseerd op standaard **Python type** declaraties (dankzij Pydantic). Je hoeft dus geen nieuwe syntax te leren. Het is gewoon standaard moderne Python. + +Als je een opfriscursus van 2 minuten nodig hebt over het gebruik van Python types (zelfs als je FastAPI niet gebruikt), bekijk dan deze korte tutorial: [Python Types](python-types.md){.internal-link target=_blank}. + +Je schrijft gewoon standaard Python met types: + +```Python +from datetime import date + +from pydantic import BaseModel + +# Declareer een variabele als een str +# en krijg editorondersteuning in de functie +def main(user_id: str): + return user_id + + +# Een Pydantic model +class User(BaseModel): + id: int + name: str + joined: date +``` + +Vervolgens kan je het op deze manier gebruiken: + +```Python +my_user: User = User(id=3, name="John Doe", joined="2018-07-19") + +second_user_data = { + "id": 4, + "name": "Mary", + "joined": "2018-11-30", +} + +my_second_user: User = User(**second_user_data) +``` + +/// info + +`**second_user_data` betekent: + +Geef de sleutels (keys) en waarden (values) van de `second_user_data` dict direct door als sleutel-waarden argumenten, gelijk aan: `User(id=4, name=“Mary”, joined=“2018-11-30”)` + +/// + +### Editor-ondersteuning + +Het gehele framework is ontworpen om eenvoudig en intuïtief te zijn in gebruik. Alle beslissingen zijn getest op meerdere code-editors nog voordat het daadwerkelijke ontwikkelen begon, om zo de beste ontwikkelervaring te garanderen. + +Uit enquêtes onder Python ontwikkelaars blijkt maar al te duidelijk dat "(automatische) code aanvulling" een van de meest gebruikte functionaliteiten is. + +Het hele **FastAPI** framework is daarop gebaseerd. Automatische code aanvulling werkt overal. + +Je hoeft zelden terug te vallen op de documentatie. + +Zo kan je editor je helpen: + +* in Visual Studio Code: + +![editor ondersteuning](https://fastapi.tiangolo.com/img/vscode-completion.png) + +* in PyCharm: + +![editor ondersteuning](https://fastapi.tiangolo.com/img/pycharm-completion.png) + +Je krijgt autocomletion die je voorheen misschien zelfs voor onmogelijk had gehouden. Zoals bijvoorbeeld de `price` key in een JSON body (die genest had kunnen zijn) die afkomstig is van een request. + +Je hoeft niet langer de verkeerde keys in te typen, op en neer te gaan tussen de documentatie, of heen en weer te scrollen om te checken of je `username` of toch `user_name` had gebruikt. + +### Kort + +Dit framework heeft voor alles verstandige **standaardinstellingen**, met overal optionele configuraties. Alle parameters kunnen worden verfijnd zodat het past bij wat je nodig hebt, om zo de API te kunnen definiëren die jij nodig hebt. + +Maar standaard werkt alles **“gewoon”**. + +### Validatie + +* Validatie voor de meeste (of misschien wel alle?) Python **datatypes**, inclusief: + * JSON objecten (`dict`). + * JSON array (`list`) die itemtypes definiëren. + * String (`str`) velden, die min en max lengtes hebben. + * Getallen (`int`, `float`) met min en max waarden, enz. + +* Validatie voor meer exotische typen, zoals: + * URL. + * E-mail. + * UUID. + * ...en anderen. + +Alle validatie wordt uitgevoerd door het beproefde en robuuste **Pydantic**. + +### Beveiliging en authenticatie + +Beveiliging en authenticatie is geïntegreerd. Zonder compromissen te doen naar databases of datamodellen. + +Alle beveiligingsschema's gedefinieerd in OpenAPI, inclusief: + +* HTTP Basic. +* **OAuth2** (ook met **JWT tokens**). Bekijk de tutorial over [OAuth2 with JWT](tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. +* API keys in: + * Headers. + * Query parameters. + * Cookies, enz. + +Plus alle beveiligingsfuncties van Starlette (inclusief **sessiecookies**). + +Gebouwd als een herbruikbare tool met componenten die makkelijk te integreren zijn in en met je systemen, datastores, relationele en NoSQL databases, enz. + +### Dependency Injection + +FastAPI bevat een uiterst eenvoudig, maar uiterst krachtig Dependency Injection systeem. + +* Zelfs dependencies kunnen dependencies hebben, waardoor een hiërarchie of **“graph” van dependencies** ontstaat. +* Allemaal **automatisch afgehandeld** door het framework. +* Alle dependencies kunnen data nodig hebben van request, de vereiste **padoperaties veranderen** en automatische documentatie verstrekken. +* **Automatische validatie** zelfs voor *padoperatie* parameters gedefinieerd in dependencies. +* Ondersteuning voor complexe gebruikersauthenticatiesystemen, **databaseverbindingen**, enz. +* **Geen compromisen** met databases, gebruikersinterfaces, enz. Maar eenvoudige integratie met ze allemaal. + +### Ongelimiteerde "plug-ins" + +Of anders gezegd, je hebt ze niet nodig, importeer en gebruik de code die je nodig hebt. + +Elke integratie is ontworpen om eenvoudig te gebruiken (met afhankelijkheden), zodat je een “plug-in" kunt maken in 2 regels code, met dezelfde structuur en syntax die wordt gebruikt voor je *padbewerkingen*. + +### Getest + +* 100% van de code is getest. +* 100% type geannoteerde codebase. +* Wordt gebruikt in productietoepassingen. + +## Starlette functies + +**FastAPI** is volledig verenigbaar met (en gebaseerd op) Starlette. + +`FastAPI` is eigenlijk een subklasse van `Starlette`. Dus als je Starlette al kent of gebruikt, zal de meeste functionaliteit op dezelfde manier werken. + +Met **FastAPI** krijg je alle functies van **Starlette** (FastAPI is gewoon Starlette op steroïden): + +* Zeer indrukwekkende prestaties. Het is een van de snelste Python frameworks, vergelijkbaar met **NodeJS** en **Go**. +* **WebSocket** ondersteuning. +* Taken in de achtergrond tijdens het proces. +* Opstart- en afsluit events. +* Test client gebouwd op HTTPX. +* **CORS**, GZip, Statische bestanden, Streaming reacties. +* **Sessie en Cookie** ondersteuning. +* 100% van de code is getest. +* 100% type geannoteerde codebase. + +## Pydantic functionaliteit + +**FastAPI** is volledig verenigbaar met (en gebaseerd op) Pydantic. Dus alle extra Pydantic code die je nog hebt werkt ook. + +Inclusief externe pakketten die ook gebaseerd zijn op Pydantic, zoals ORMs, ODMs voor databases. + +Dit betekent ook dat je in veel gevallen het object dat je van een request krijgt **direct naar je database** kunt sturen, omdat alles automatisch wordt gevalideerd. + +Hetzelfde geldt ook andersom, in veel gevallen kun je dus het object dat je krijgt van de database **direct doorgeven aan de client**. + +Met **FastAPI** krijg je alle functionaliteit van **Pydantic** (omdat FastAPI is gebaseerd op Pydantic voor alle dataverwerking): + +* **Geen brainfucks**: + * Je hoeft geen nieuwe microtaal voor schemadefinities te leren. + * Als je bekend bent Python types, weet je hoe je Pydantic moet gebruiken. +* Werkt goed samen met je **IDE/linter/hersenen**: + * Doordat pydantic's datastructuren enkel instanties zijn van klassen, die je definieert, werkt automatische aanvulling, linting, mypy en je intuïtie allemaal goed met je gevalideerde data. +* Valideer **complexe structuren**: + * Gebruik van hiërarchische Pydantic modellen, Python `typing`'s `List` en `Dict`, enz. + * Met validators kunnen complexe dataschema's duidelijk en eenvoudig worden gedefinieerd, gecontroleerd en gedocumenteerd als JSON Schema. + * Je kunt diep **geneste JSON** objecten laten valideren en annoteren. +* **Uitbreidbaar**: + * Met Pydantic kunnen op maat gemaakte datatypen worden gedefinieerd of je kunt validatie uitbreiden met methoden op een model dat is ingericht met de decorator validator. +* 100% van de code is getest. From cbdc58b1b75a7e94c78d3dca39f0564bd071d190 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 3 Sep 2024 13:54:00 +0000 Subject: [PATCH 86/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index a82965aa8..df4927752 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -30,6 +30,7 @@ hide: ### Translations +* 🌐 Add Dutch translation for `docs/nl/docs/features.md`. PR [#12101](https://github.com/fastapi/fastapi/pull/12101) by [@maxscheijen](https://github.com/maxscheijen). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/testing-events.md`. PR [#12108](https://github.com/fastapi/fastapi/pull/12108) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Portuguese translation for `docs/pt/docs/advanced/security/index.md`. PR [#12114](https://github.com/fastapi/fastapi/pull/12114) by [@ceb10n](https://github.com/ceb10n). * 🌐 Add Dutch translation for `docs/nl/docs/index.md`. PR [#12042](https://github.com/fastapi/fastapi/pull/12042) by [@svlandeg](https://github.com/svlandeg). From f42fd9aac2529c1bda6b81fe9cecce0986dadbf3 Mon Sep 17 00:00:00 2001 From: Shubhendra Kushwaha Date: Tue, 3 Sep 2024 21:35:19 +0530 Subject: [PATCH 87/88] =?UTF-8?q?=F0=9F=93=9D=20Add=20External=20Link:=20T?= =?UTF-8?q?echniques=20and=20applications=20of=20SQLAlchemy=20global=20fil?= =?UTF-8?q?ters=20in=20FastAPI=20(#12109)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/data/external_links.yml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs/en/data/external_links.yml b/docs/en/data/external_links.yml index 15f6169ee..63fd3d0cf 100644 --- a/docs/en/data/external_links.yml +++ b/docs/en/data/external_links.yml @@ -264,6 +264,14 @@ Articles: author_link: https://devonray.com link: https://devonray.com/blog/deploying-a-fastapi-project-using-aws-lambda-aurora-cdk title: Deployment using Docker, Lambda, Aurora, CDK & GH Actions + - author: Shubhendra Kushwaha + author_link: https://www.linkedin.com/in/theshubhendra/ + link: https://theshubhendra.medium.com/mastering-soft-delete-advanced-sqlalchemy-techniques-4678f4738947 + title: 'Mastering Soft Delete: Advanced SQLAlchemy Techniques' + - author: Shubhendra Kushwaha + author_link: https://www.linkedin.com/in/theshubhendra/ + link: https://theshubhendra.medium.com/role-based-row-filtering-advanced-sqlalchemy-techniques-733e6b1328f6 + title: 'Role based row filtering: Advanced SQLAlchemy Techniques' German: - author: Marcel Sander (actidoo) author_link: https://www.actidoo.com From 9b2a9333b3b9820082deb35605c0619bd578baee Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 3 Sep 2024 16:05:42 +0000 Subject: [PATCH 88/88] =?UTF-8?q?=F0=9F=93=9D=20Update=20release=20notes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index df4927752..70dbce539 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -17,6 +17,7 @@ hide: ### Docs +* 📝 Add External Link: Techniques and applications of SQLAlchemy global filters in FastAPI. PR [#12109](https://github.com/fastapi/fastapi/pull/12109) by [@TheShubhendra](https://github.com/TheShubhendra). * 📝 Add note about `time.perf_counter()` in middlewares. PR [#12095](https://github.com/fastapi/fastapi/pull/12095) by [@tiangolo](https://github.com/tiangolo). * 📝 Tweak middleware code sample `time.time()` to `time.perf_counter()`. PR [#11957](https://github.com/fastapi/fastapi/pull/11957) by [@domdent](https://github.com/domdent). * 🔧 Update sponsors: Coherence. PR [#12093](https://github.com/fastapi/fastapi/pull/12093) by [@tiangolo](https://github.com/tiangolo).