From 623b0f37de152a49fa27078c1e28fd1ee80e2587 Mon Sep 17 00:00:00 2001 From: Carlton Gibson Date: Thu, 18 Aug 2022 17:24:28 +0200 Subject: [PATCH 001/194] =?UTF-8?q?=F0=9F=93=9D=20Remove=20unneeded=20Djan?= =?UTF-8?q?go/Flask=20references=20from=20async=20topic=20intro=20(#5280)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/async.md | 6 +----- docs/fr/docs/async.md | 4 ---- 2 files changed, 1 insertion(+), 9 deletions(-) diff --git a/docs/en/docs/async.md b/docs/en/docs/async.md index 43473c822309d..95d2f755a6d43 100644 --- a/docs/en/docs/async.md +++ b/docs/en/docs/async.md @@ -232,11 +232,7 @@ This "waiting" 🕙 is measured in microseconds, but still, summing it all, it's That's why it makes a lot of sense to use asynchronous ⏸🔀⏯ code for web APIs. -Most of the existing popular Python frameworks (including Flask and Django) were created before the new asynchronous features in Python existed. So, the ways they can be deployed support parallel execution and an older form of asynchronous execution that is not as powerful as the new capabilities. - -Even though the main specification for asynchronous web Python (ASGI) was developed at Django, to add support for WebSockets. - -That kind of asynchronicity is what made NodeJS popular (even though NodeJS is not parallel) and that's the strength of Go as a programming language. +This kind of asynchronicity is what made NodeJS popular (even though NodeJS is not parallel) and that's the strength of Go as a programming language. And that's the same level of performance you get with **FastAPI**. diff --git a/docs/fr/docs/async.md b/docs/fr/docs/async.md index 71c28b7039068..db88c4663ce3f 100644 --- a/docs/fr/docs/async.md +++ b/docs/fr/docs/async.md @@ -205,10 +205,6 @@ Cette "attente" 🕙 se mesure en microsecondes, mais tout de même, en cumulé C'est pourquoi il est logique d'utiliser du code asynchrone ⏸🔀⏯ pour des APIs web. -La plupart des frameworks Python existants (y compris Flask et Django) ont été créés avant que les nouvelles fonctionnalités asynchrones de Python n'existent. Donc, les façons dont ils peuvent être déployés supportent l'exécution parallèle et une ancienne forme d'exécution asynchrone qui n'est pas aussi puissante que les nouvelles fonctionnalités de Python. - -Et cela, bien que les spécifications principales du web asynchrone en Python (ou ASGI) ont été développées chez Django, pour ajouter le support des WebSockets. - Ce type d'asynchronicité est ce qui a rendu NodeJS populaire (bien que NodeJS ne soit pas parallèle) et c'est la force du Go en tant que langage de programmation. Et c'est le même niveau de performance que celui obtenu avec **FastAPI**. From a79228138bf2d3fa7b4d2cf4485b387cb833f910 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 18 Aug 2022 15:26:58 +0000 Subject: [PATCH 002/194] =?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 6cd2a298c5d47..1ad350acb5222 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 📝 Remove unneeded Django/Flask references from async topic intro. PR [#5280](https://github.com/tiangolo/fastapi/pull/5280) by [@carltongibson](https://github.com/carltongibson). * ✨ Add illustrations for Concurrent burgers and Parallel burgers. PR [#5277](https://github.com/tiangolo/fastapi/pull/5277) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update Jina sponsorship. PR [#5272](https://github.com/tiangolo/fastapi/pull/5272) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update sponsors, Striveworks badge. PR [#5179](https://github.com/tiangolo/fastapi/pull/5179) by [@tiangolo](https://github.com/tiangolo). From a0d79b37068e21647b55cd2b69c2d1cb78c49638 Mon Sep 17 00:00:00 2001 From: Baskara Febrianto <41407847+bas-baskara@users.noreply.github.com> Date: Thu, 18 Aug 2022 22:53:59 +0700 Subject: [PATCH 003/194] =?UTF-8?q?=F0=9F=8C=90=20Add=20Indonesian=20trans?= =?UTF-8?q?lation=20for=20`docs/id/docs/tutorial/index.md`=20(#4705)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Baskara Febrianto Co-authored-by: Sebastián Ramírez --- docs/id/docs/tutorial/index.md | 80 ++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 docs/id/docs/tutorial/index.md diff --git a/docs/id/docs/tutorial/index.md b/docs/id/docs/tutorial/index.md new file mode 100644 index 0000000000000..8fec3c087e6ad --- /dev/null +++ b/docs/id/docs/tutorial/index.md @@ -0,0 +1,80 @@ +# Tutorial - Pedoman Pengguna - Pengenalan + +Tutorial ini menunjukan cara menggunakan ***FastAPI*** dengan semua fitur-fiturnya, tahap demi tahap. + +Setiap bagian dibangun secara bertahap dari bagian sebelumnya, tetapi terstruktur untuk memisahkan banyak topik, sehingga kamu bisa secara langsung menuju ke topik spesifik untuk menyelesaikan kebutuhan API tertentu. + +Ini juga dibangun untuk digunakan sebagai referensi yang akan datang. + +Sehingga kamu dapat kembali lagi dan mencari apa yang kamu butuhkan dengan tepat. + +## Jalankan kode + +Semua blok-blok kode dapat dicopy dan digunakan langsung (Mereka semua sebenarnya adalah file python yang sudah teruji). + +Untuk menjalankan setiap contoh, copy kode ke file `main.py`, dan jalankan `uvicorn` dengan: + +
+ +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +INFO: Started reloader process [28720] +INFO: Started server process [28722] +INFO: Waiting for application startup. +INFO: Application startup complete. +``` + +
+ +**SANGAT disarankan** agar kamu menulis atau meng-copy kode, meng-editnya dan menjalankannya secara lokal. + +Dengan menggunakannya di dalam editor, benar-benar memperlihatkan manfaat dari FastAPI, melihat bagaimana sedikitnya kode yang harus kamu tulis, semua pengecekan tipe, pelengkapan otomatis, dll. + +--- + +## Install FastAPI + +Langkah pertama adalah dengan meng-install FastAPI. + +Untuk tutorial, kamu mungkin hendak meng-instalnya dengan semua pilihan fitur dan dependensinya: + +
+ +```console +$ pip install "fastapi[all]" + +---> 100% +``` + +
+ +...yang juga termasuk `uvicorn`, yang dapat kamu gunakan sebagai server yang menjalankan kodemu. + +!!! catatan + Kamu juga dapat meng-instalnya bagian demi bagian. + + Hal ini mungkin yang akan kamu lakukan ketika kamu hendak men-deploy aplikasimu ke tahap produksi: + + ``` + pip install fastapi + ``` + + Juga install `uvicorn` untk menjalankan server" + + ``` + pip install "uvicorn[standard]" + ``` + + Dan demikian juga untuk pilihan dependensi yang hendak kamu gunakan. + +## Pedoman Pengguna Lanjutan + +Tersedia juga **Pedoman Pengguna Lanjutan** yang dapat kamu baca nanti setelah **Tutorial - Pedoman Pengguna** ini. + +**Pedoman Pengguna Lanjutan**, dibangun atas hal ini, menggunakan konsep yang sama, dan mengajarkan kepadamu beberapa fitur tambahan. + +Tetapi kamu harus membaca terlebih dahulu **Tutorial - Pedoman Pengguna** (apa yang sedang kamu baca sekarang). + +Hal ini didesain sehingga kamu dapat membangun aplikasi lengkap dengan hanya **Tutorial - Pedoman Pengguna**, dan kemudian mengembangkannya ke banyak cara yang berbeda, tergantung dari kebutuhanmu, menggunakan beberapa ide-ide tambahan dari **Pedoman Pengguna Lanjutan**. From e23fa40e6c99b0550586194d4ee2ef7cc61277ab Mon Sep 17 00:00:00 2001 From: sUeharaE4 <44468359+sUeharaE4@users.noreply.github.com> Date: Fri, 19 Aug 2022 00:54:22 +0900 Subject: [PATCH 004/194] =?UTF-8?q?=F0=9F=8C=90=20Add=20Japanese=20transla?= =?UTF-8?q?tion=20for=20`docs/ja/docs/advanced/nosql-databases.md`=20(#420?= =?UTF-8?q?5)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: tokusumi <41147016+tokusumi@users.noreply.github.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- docs/ja/docs/advanced/nosql-databases.md | 156 +++++++++++++++++++++++ docs/ja/mkdocs.yml | 1 + 2 files changed, 157 insertions(+) create mode 100644 docs/ja/docs/advanced/nosql-databases.md diff --git a/docs/ja/docs/advanced/nosql-databases.md b/docs/ja/docs/advanced/nosql-databases.md new file mode 100644 index 0000000000000..fbd76e96b14e9 --- /dev/null +++ b/docs/ja/docs/advanced/nosql-databases.md @@ -0,0 +1,156 @@ +# NoSQL (分散 / ビッグデータ) Databases + +**FastAPI** はあらゆる NoSQLと統合することもできます。 + +ここではドキュメントベースのNoSQLデータベースである**Couchbase**を使用した例を見てみましょう。 + +他にもこれらのNoSQLデータベースを利用することが出来ます: + +* **MongoDB** +* **Cassandra** +* **CouchDB** +* **ArangoDB** +* **ElasticSearch** など。 + +!!! tip "豆知識" + **FastAPI**と**Couchbase**を使った公式プロジェクト・ジェネレータがあります。すべて**Docker**ベースで、フロントエンドやその他のツールも含まれています: https://github.com/tiangolo/full-stack-fastapi-couchbase + +## Couchbase コンポーネントの Import + +まずはImportしましょう。今はその他のソースコードに注意を払う必要はありません。 + +```Python hl_lines="3-5" +{!../../../docs_src/nosql_databases/tutorial001.py!} +``` + +## "document type" として利用する定数の定義 + +documentで利用する固定の`type`フィールドを用意しておきます。 + +これはCouchbaseで必須ではありませんが、後々の助けになるベストプラクティスです。 + +```Python hl_lines="9" +{!../../../docs_src/nosql_databases/tutorial001.py!} +``` + +## `Bucket` を取得する関数の追加 + +**Couchbase**では、bucketはdocumentのセットで、様々な種類のものがあります。 + +Bucketは通常、同一のアプリケーション内で互いに関係を持っています。 + +リレーショナルデータベースの世界でいう"database"(データベースサーバではなく特定のdatabase)と類似しています。 + +**MongoDB** で例えると"collection"と似た概念です。 + +次のコードでは主に `Bucket` を利用してCouchbaseを操作します。 + +この関数では以下の処理を行います: + +* **Couchbase** クラスタ(1台の場合もあるでしょう)に接続 + * タイムアウトのデフォルト値を設定 +* クラスタで認証を取得 +* `Bucket` インスタンスを取得 + * タイムアウトのデフォルト値を設定 +* 作成した`Bucket`インスタンスを返却 + +```Python hl_lines="12-21" +{!../../../docs_src/nosql_databases/tutorial001.py!} +``` + +## Pydantic モデルの作成 + +**Couchbase**のdocumentは実際には単にJSONオブジェクトなのでPydanticを利用してモデルに出来ます。 + +### `User` モデル + +まずは`User`モデルを作成してみましょう: + +```Python hl_lines="24-28" +{!../../../docs_src/nosql_databases/tutorial001.py!} +``` + +このモデルは*path operation*に使用するので`hashed_password`は含めません。 + +### `UserInDB` モデル + +それでは`UserInDB`モデルを作成しましょう。 + +こちらは実際にデータベースに保存されるデータを保持します。 + +`User`モデルの持つ全ての属性に加えていくつかの属性を追加するのでPydanticの`BaseModel`を継承せずに`User`のサブクラスとして定義します: + +```Python hl_lines="31-33" +{!../../../docs_src/nosql_databases/tutorial001.py!} +``` + +!!! note "備考" + データベースに保存される`hashed_password`と`type`フィールドを`UserInDB`モデルに保持させていることに注意してください。 + + しかしこれらは(*path operation*で返却する)一般的な`User`モデルには含まれません + +## user の取得 + +それでは次の関数を作成しましょう: + +* username を取得する +* username を利用してdocumentのIDを生成する +* 作成したIDでdocumentを取得する +* documentの内容を`UserInDB`モデルに設定する + +*path operation関数*とは別に、`username`(またはその他のパラメータ)からuserを取得することだけに特化した関数を作成することで、より簡単に複数の部分で再利用したりユニットテストを追加することができます。 + +```Python hl_lines="36-42" +{!../../../docs_src/nosql_databases/tutorial001.py!} +``` + +### f-strings + +`f"userprofile::{username}"` という記載に馴染みがありませんか?これは Python の"f-string"と呼ばれるものです。 + +f-stringの`{}`の中に入れられた変数は、文字列の中に展開/注入されます。 + +### `dict` アンパック + +`UserInDB(**result.value)`という記載に馴染みがありませんか?これは`dict`の"アンパック"と呼ばれるものです。 + +これは`result.value`の`dict`からそのキーと値をそれぞれ取りキーワード引数として`UserInDB`に渡します。 + +例えば`dict`が下記のようになっていた場合: + +```Python +{ + "username": "johndoe", + "hashed_password": "some_hash", +} +``` + +`UserInDB`には次のように渡されます: + +```Python +UserInDB(username="johndoe", hashed_password="some_hash") +``` + +## **FastAPI** コードの実装 + +### `FastAPI` app の作成 + +```Python hl_lines="46" +{!../../../docs_src/nosql_databases/tutorial001.py!} +``` + +### *path operation関数*の作成 + +私たちのコードはCouchbaseを呼び出しており、実験的なPython awaitを使用していないので、私たちは`async def`ではなく通常の`def`で関数を宣言する必要があります。 + +また、Couchbaseは単一の`Bucket`オブジェクトを複数のスレッドで使用しないことを推奨していますので、単に直接Bucketを取得して関数に渡すことが出来ます。 + +```Python hl_lines="49-53" +{!../../../docs_src/nosql_databases/tutorial001.py!} +``` + +## まとめ + +他のサードパーティ製のNoSQLデータベースを利用する場合でも、そのデータベースの標準ライブラリを利用するだけで利用できます。 + +他の外部ツール、システム、APIについても同じことが言えます。 diff --git a/docs/ja/mkdocs.yml b/docs/ja/mkdocs.yml index 985bb24d0b515..b3f18bbdd305f 100644 --- a/docs/ja/mkdocs.yml +++ b/docs/ja/mkdocs.yml @@ -85,6 +85,7 @@ nav: - advanced/additional-status-codes.md - advanced/response-directly.md - advanced/custom-response.md + - advanced/nosql-databases.md - advanced/conditional-openapi.md - async.md - デプロイ: From 7e3e4fa7eac3c6ec5fc085652fb633c2369076a2 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 18 Aug 2022 15:54:41 +0000 Subject: [PATCH 005/194] =?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 1ad350acb5222..88becd991e19d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 🌐 Add Indonesian translation for `docs/id/docs/tutorial/index.md`. PR [#4705](https://github.com/tiangolo/fastapi/pull/4705) by [@bas-baskara](https://github.com/bas-baskara). * 📝 Remove unneeded Django/Flask references from async topic intro. PR [#5280](https://github.com/tiangolo/fastapi/pull/5280) by [@carltongibson](https://github.com/carltongibson). * ✨ Add illustrations for Concurrent burgers and Parallel burgers. PR [#5277](https://github.com/tiangolo/fastapi/pull/5277) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update Jina sponsorship. PR [#5272](https://github.com/tiangolo/fastapi/pull/5272) by [@tiangolo](https://github.com/tiangolo). From fc4ad71069b7a690944a7f17129ab0630173f57f Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 18 Aug 2022 15:56:11 +0000 Subject: [PATCH 006/194] =?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 88becd991e19d..abbb1584b0f2f 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 🌐 Add Japanese translation for `docs/ja/docs/advanced/nosql-databases.md`. PR [#4205](https://github.com/tiangolo/fastapi/pull/4205) by [@sUeharaE4](https://github.com/sUeharaE4). * 🌐 Add Indonesian translation for `docs/id/docs/tutorial/index.md`. PR [#4705](https://github.com/tiangolo/fastapi/pull/4705) by [@bas-baskara](https://github.com/bas-baskara). * 📝 Remove unneeded Django/Flask references from async topic intro. PR [#5280](https://github.com/tiangolo/fastapi/pull/5280) by [@carltongibson](https://github.com/carltongibson). * ✨ Add illustrations for Concurrent burgers and Parallel burgers. PR [#5277](https://github.com/tiangolo/fastapi/pull/5277) by [@tiangolo](https://github.com/tiangolo). From dc7e13846c2ddddd9b8f56bb8c20dc9be61e24e5 Mon Sep 17 00:00:00 2001 From: jaystone776 Date: Thu, 18 Aug 2022 23:57:21 +0800 Subject: [PATCH 007/194] =?UTF-8?q?=F0=9F=8C=90=20Add=20Chinese=20translat?= =?UTF-8?q?ion=20for=20`docs/tutorial/security/first-steps.md`=20(#3841)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs/zh/docs/tutorial/security/first-steps.md | 189 ++++++++++++++++++ docs/zh/mkdocs.yml | 1 + 2 files changed, 190 insertions(+) create mode 100644 docs/zh/docs/tutorial/security/first-steps.md diff --git a/docs/zh/docs/tutorial/security/first-steps.md b/docs/zh/docs/tutorial/security/first-steps.md new file mode 100644 index 0000000000000..116572411c918 --- /dev/null +++ b/docs/zh/docs/tutorial/security/first-steps.md @@ -0,0 +1,189 @@ +# 安全 - 第一步 + +假设**后端** API 在某个域。 + +**前端**在另一个域,或(移动应用中)在同一个域的不同路径下。 + +并且,前端要使用后端的 **username** 与 **password** 验证用户身份。 + +固然,**FastAPI** 支持 **OAuth2** 身份验证。 + +但为了节省开发者的时间,不要只为了查找很少的内容,不得不阅读冗长的规范文档。 + +我们建议使用 **FastAPI** 的安全工具。 + +## 概览 + +首先,看看下面的代码是怎么运行的,然后再回过头来了解其背后的原理。 + +## 创建 `main.py` + +把下面的示例代码复制到 `main.py`: + +```Python +{!../../../docs_src/security/tutorial001.py!} +``` + +## 运行 + +!!! info "说明" + + 先安装 `python-multipart`。 + + 安装命令: `pip install python-multipart`。 + + 这是因为 **OAuth2** 使用**表单数据**发送 `username` 与 `password`。 + +用下面的命令运行该示例: + +
+ +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +## 查看文档 + +打开 API 文档: http://127.0.0.1:8000/docs。 + +界面如下图所示: + + + +!!! check "Authorize 按钮!" + + 页面右上角出现了一个「**Authorize**」按钮。 + + *路径操作*的右上角也出现了一个可以点击的小锁图标。 + +点击 **Authorize** 按钮,弹出授权表单,输入 `username` 与 `password` 及其它可选字段: + + + +!!! note "笔记" + + 目前,在表单中输入内容不会有任何反应,后文会介绍相关内容。 + +虽然此文档不是给前端最终用户使用的,但这个自动工具非常实用,可在文档中与所有 API 交互。 + +前端团队(可能就是开发者本人)可以使用本工具。 + +第三方应用与系统也可以调用本工具。 + +开发者也可以用它来调试、检查、测试应用。 + +## 密码流 + +现在,我们回过头来介绍这段代码的原理。 + +`Password` **流**是 OAuth2 定义的,用于处理安全与身份验证的方式(**流**)。 + +OAuth2 的设计目标是为了让后端或 API 独立于服务器验证用户身份。 + +但在本例中,**FastAPI** 应用会处理 API 与身份验证。 + +下面,我们来看一下简化的运行流程: + +- 用户在前端输入 `username` 与`password`,并点击**回车** +- (用户浏览器中运行的)前端把 `username` 与`password` 发送至 API 中指定的 URL(使用 `tokenUrl="token"` 声明) +- API 检查 `username` 与`password`,并用令牌(`Token`) 响应(暂未实现此功能): + - 令牌只是用于验证用户的字符串 + - 一般来说,令牌会在一段时间后过期 + - 过时后,用户要再次登录 + - 这样一来,就算令牌被人窃取,风险也较低。因为它与永久密钥不同,**在绝大多数情况下**不会长期有效 +- 前端临时将令牌存储在某个位置 +- 用户点击前端,前往前端应用的其它部件 +- 前端需要从 API 中提取更多数据: + - 为指定的端点(Endpoint)进行身份验证 + - 因此,用 API 验证身份时,要发送值为 `Bearer` + 令牌的请求头 `Authorization` + - 假如令牌为 `foobar`,`Authorization` 请求头就是: `Bearer foobar` + +## **FastAPI** 的 `OAuth2PasswordBearer` + +**FastAPI** 提供了不同抽象级别的安全工具。 + +本例使用 **OAuth2** 的 **Password** 流以及 **Bearer** 令牌(`Token`)。为此要使用 `OAuth2PasswordBearer` 类。 + +!!! info "说明" + + `Beare` 令牌不是唯一的选择。 + + 但它是最适合这个用例的方案。 + + 甚至可以说,它是适用于绝大多数用例的最佳方案,除非您是 OAuth2 的专家,知道为什么其它方案更合适。 + + 本例中,**FastAPI** 还提供了构建工具。 + +创建 `OAuth2PasswordBearer` 的类实例时,要传递 `tokenUrl` 参数。该参数包含客户端(用户浏览器中运行的前端) 的 URL,用于发送 `username` 与 `password`,并获取令牌。 + +```Python hl_lines="6" +{!../../../docs_src/security/tutorial001.py!} +``` + +!!! tip "提示" + + 在此,`tokenUrl="token"` 指向的是暂未创建的相对 URL `token`。这个相对 URL 相当于 `./token`。 + + 因为使用的是相对 URL,如果 API 位于 `https://example.com/`,则指向 `https://example.com/token`。但如果 API 位于 `https://example.com/api/v1/`,它指向的就是`https://example.com/api/v1/token`。 + + 使用相对 URL 非常重要,可以确保应用在遇到[使用代理](../../advanced/behind-a-proxy.md){.internal-link target=_blank}这样的高级用例时,也能正常运行。 + +该参数不会创建端点或*路径操作*,但会声明客户端用来获取令牌的 URL `/token` 。此信息用于 OpenAPI 及 API 文档。 + +接下来,学习如何创建实际的路径操作。 + +!!! info "说明" + + 严苛的 **Pythonista** 可能不喜欢用 `tokenUrl` 这种命名风格代替 `token_url`。 + + 这种命名方式是因为要使用与 OpenAPI 规范中相同的名字。以便在深入校验安全方案时,能通过复制粘贴查找更多相关信息。 + +`oauth2_scheme` 变量是 `OAuth2PasswordBearer` 的实例,也是**可调用项**。 + +以如下方式调用: + +```Python +oauth2_scheme(some, parameters) +``` + +因此,`Depends` 可以调用 `oauth2_scheme` 变量。 + +### 使用 + +接下来,使用 `Depends` 把 `oauth2_scheme` 传入依赖项。 + +```Python hl_lines="10" +{!../../../docs_src/security/tutorial001.py!} +``` + +该依赖项使用字符串(`str`)接收*路径操作函数*的参数 `token` 。 + +**FastAPI** 使用依赖项在 OpenAPI 概图(及 API 文档)中定义**安全方案**。 + +!!! info "技术细节" + + **FastAPI** 使用(在依赖项中声明的)类 `OAuth2PasswordBearer` 在 OpenAPI 中定义安全方案,这是因为它继承自 `fastapi.security.oauth2.OAuth2`,而该类又是继承自`fastapi.security.base.SecurityBase`。 + + 所有与 OpenAPI(及 API 文档)集成的安全工具都继承自 `SecurityBase`, 这就是为什么 **FastAPI** 能把它们集成至 OpenAPI 的原因。 + +## 实现的操作 + +FastAPI 校验请求中的 `Authorization` 请求头,核对请求头的值是不是由 `Bearer ` + 令牌组成, 并返回令牌字符串(`str`)。 + +如果没有找到 `Authorization` 请求头,或请求头的值不是 `Bearer ` + 令牌。FastAPI 直接返回 401 错误状态码(`UNAUTHORIZED`)。 + +开发者不需要检查错误信息,查看令牌是否存在,只要该函数能够执行,函数中就会包含令牌字符串。 + +正如下图所示,API 文档已经包含了这项功能: + + + +目前,暂时还没有实现验证令牌是否有效的功能,不过后文很快就会介绍的。 + +## 小结 + +看到了吧,只要多写三四行代码,就可以添加基础的安全表单。 diff --git a/docs/zh/mkdocs.yml b/docs/zh/mkdocs.yml index e70ec7698d0a0..9e8813d6c3a68 100644 --- a/docs/zh/mkdocs.yml +++ b/docs/zh/mkdocs.yml @@ -93,6 +93,7 @@ nav: - tutorial/dependencies/global-dependencies.md - 安全性: - tutorial/security/index.md + - tutorial/security/first-steps.md - tutorial/security/get-current-user.md - tutorial/security/simple-oauth2.md - tutorial/security/oauth2-jwt.md From 8fe80e81e11f3bc9a6be7ddfe63ded5e0160c916 Mon Sep 17 00:00:00 2001 From: AdmiralDesu <49198383+AdmiralDesu@users.noreply.github.com> Date: Thu, 18 Aug 2022 18:59:02 +0300 Subject: [PATCH 008/194] =?UTF-8?q?=F0=9F=8C=90=20Add=20Russian=20translat?= =?UTF-8?q?ion=20for=20`docs/ru/docs/tutorial/background-tasks.md`=20(#485?= =?UTF-8?q?4)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- docs/ru/docs/tutorial/background-tasks.md | 102 ++++++++++++++++++++++ docs/ru/mkdocs.yml | 4 + 2 files changed, 106 insertions(+) create mode 100644 docs/ru/docs/tutorial/background-tasks.md diff --git a/docs/ru/docs/tutorial/background-tasks.md b/docs/ru/docs/tutorial/background-tasks.md new file mode 100644 index 0000000000000..e608f6c8f3010 --- /dev/null +++ b/docs/ru/docs/tutorial/background-tasks.md @@ -0,0 +1,102 @@ +# Фоновые задачи + +Вы можете создавать фоновые задачи, которые будут выполнятся *после* возвращения ответа сервером. + +Это может быть полезно для функций, которые должны выполниться после получения запроса, но ожидание их выполнения необязательно для пользователя. + +К примеру: + +* Отправка писем на почту после выполнения каких-либо действий: + * Т.к. соединение с почтовым сервером и отправка письма идут достаточно "долго" (несколько секунд), вы можете отправить ответ пользователю, а отправку письма выполнить в фоне. +* Обработка данных: + * К примеру, если вы получаете файл, который должен пройти через медленный процесс, вы можете отправить ответ "Accepted" (HTTP 202) и отправить работу с файлом в фон. + +## Использование класса `BackgroundTasks` + +Сначала импортируйте `BackgroundTasks`, потом добавьте в функцию параметр с типом `BackgroundTasks`: + +```Python hl_lines="1 13" +{!../../../docs_src/background_tasks/tutorial001.py!} +``` + +**FastAPI** создаст объект класса `BackgroundTasks` для вас и запишет его в параметр. + +## Создание функции для фоновой задачи + +Создайте функцию, которую хотите запустить в фоне. + +Это совершенно обычная функция, которая может принимать параметры. + +Она может быть как асинхронной `async def`, так и обычной `def` функцией, **FastAPI** знает, как правильно ее выполнить. + +В нашем примере фоновая задача будет вести запись в файл (симулируя отправку письма). + +Так как операция записи не использует `async` и `await`, мы определим ее как обычную `def`: + +```Python hl_lines="6-9" +{!../../../docs_src/background_tasks/tutorial001.py!} +``` + +## Добавление фоновой задачи + +Внутри функции вызовите метод `.add_task()` у объекта *background tasks* и передайте ему функцию, которую хотите выполнить в фоне: + +```Python hl_lines="14" +{!../../../docs_src/background_tasks/tutorial001.py!} +``` + +`.add_task()` принимает следующие аргументы: + +* Функцию, которая будет выполнена в фоне (`write_notification`). Обратите внимание, что передается объект функции, без скобок. +* Любое упорядоченное количество аргументов, которые принимает функция (`email`). +* Любое количество именованных аргументов, которые принимает функция (`message="some notification"`). + +## Встраивание зависимостей + +Класс `BackgroundTasks` также работает с системой встраивания зависимостей, вы можете определить `BackgroundTasks` на разных уровнях: как параметр функции, как завимость, как подзависимость и так далее. + +**FastAPI** знает, что нужно сделать в каждом случае и как переиспользовать тот же объект `BackgroundTasks`, так чтобы все фоновые задачи собрались и запустились вместе в фоне: + +=== "Python 3.6 и выше" + + ```Python hl_lines="13 15 22 25" + {!> ../../../docs_src/background_tasks/tutorial002.py!} + ``` + +=== "Python 3.10 и выше" + + ```Python hl_lines="11 13 20 23" + {!> ../../../docs_src/background_tasks/tutorial002_py310.py!} + ``` + +В этом примере сообщения будут записаны в `log.txt` *после* того, как ответ сервера был отправлен. + +Если бы в запросе была очередь `q`, она бы первой записалась в `log.txt` фоновой задачей (потому что вызывается в зависимости `get_query`). + +После другая фоновая задача, которая была сгенерирована в функции, запишет сообщение из параметра `email`. + +## Технические детали + +Класс `BackgroundTasks` основан на `starlette.background`. + +Он интегрирован в FastAPI, так что вы можете импортировать его прямо из `fastapi` и избежать случайного импорта `BackgroundTask` (без `s` на конце) из `starlette.background`. + +При использовании `BackgroundTasks` (а не `BackgroundTask`), вам достаточно только определить параметр функции с типом `BackgroundTasks` и **FastAPI** сделает все за вас, также как при использовании объекта `Request`. + +Вы все равно можете использовать `BackgroundTask` из `starlette` в FastAPI, но вам придется самостоятельно создавать объект фоновой задачи и вручную обработать `Response` внутри него. + +Вы можете подробнее изучить его в Официальной документации Starlette для BackgroundTasks. + +## Предостережение + +Если вам нужно выполнить тяжелые вычисления в фоне, которым необязательно быть запущенными в одном процессе с приложением **FastAPI** (к примеру, вам не нужны обрабатываемые переменные или вы не хотите делиться памятью процесса и т.д.), вы можете использовать более серьезные инструменты, такие как Celery. + +Их тяжелее настраивать, также им нужен брокер сообщений наподобие RabbitMQ или Redis, но зато они позволяют вам запускать фоновые задачи в нескольких процессах и даже на нескольких серверах. + +Для примера, посмотрите [Project Generators](../project-generation.md){.internal-link target=_blank}, там есть проект с уже настроенным Celery. + +Но если вам нужен доступ к общим переменным и объектам вашего **FastAPI** приложения или вам нужно выполнять простые фоновые задачи (наподобие отправки письма из примера) вы можете просто использовать `BackgroundTasks`. + +## Резюме + +Для создания фоновых задач вам необходимо импортировать `BackgroundTasks` и добавить его в функцию, как параметр с типом `BackgroundTasks`. diff --git a/docs/ru/mkdocs.yml b/docs/ru/mkdocs.yml index 2150d5c19f80c..f70b436d29774 100644 --- a/docs/ru/mkdocs.yml +++ b/docs/ru/mkdocs.yml @@ -58,6 +58,10 @@ nav: - tr: /tr/ - uk: /uk/ - zh: /zh/ +- python-types.md +- Учебник - руководство пользователя: + - tutorial/background-tasks.md +- external-links.md - async.md markdown_extensions: - toc: From b862639ce9eebcd113d0d16806c3f63a036bdd34 Mon Sep 17 00:00:00 2001 From: Atiab Bin Zakaria <61742543+atiabbz@users.noreply.github.com> Date: Thu, 18 Aug 2022 23:59:50 +0800 Subject: [PATCH 009/194] =?UTF-8?q?=E2=9C=8F=20Fix=20typo=20in=20`docs/en/?= =?UTF-8?q?docs/python-types.md`=20(#5007)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/python-types.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/python-types.md b/docs/en/docs/python-types.md index 963fcaf1cd580..f170bb1ef4b1d 100644 --- a/docs/en/docs/python-types.md +++ b/docs/en/docs/python-types.md @@ -267,7 +267,7 @@ You can declare that a variable can be any of **several types**, for example, an In Python 3.6 and above (including Python 3.10) you can use the `Union` type from `typing` and put inside the square brackets the possible types to accept. -In Python 3.10 there's also an **alternative syntax** were you can put the possible types separated by a vertical bar (`|`). +In Python 3.10 there's also an **alternative syntax** where you can put the possible types separated by a vertical bar (`|`). === "Python 3.6 and above" From 65e4286bc9d00ccd640383f0cd265c6c534a7b30 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 18 Aug 2022 16:00:22 +0000 Subject: [PATCH 010/194] =?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 abbb1584b0f2f..976b96e22700f 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 🌐 Add Chinese translation for `docs/tutorial/security/first-steps.md`. PR [#3841](https://github.com/tiangolo/fastapi/pull/3841) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Japanese translation for `docs/ja/docs/advanced/nosql-databases.md`. PR [#4205](https://github.com/tiangolo/fastapi/pull/4205) by [@sUeharaE4](https://github.com/sUeharaE4). * 🌐 Add Indonesian translation for `docs/id/docs/tutorial/index.md`. PR [#4705](https://github.com/tiangolo/fastapi/pull/4705) by [@bas-baskara](https://github.com/bas-baskara). * 📝 Remove unneeded Django/Flask references from async topic intro. PR [#5280](https://github.com/tiangolo/fastapi/pull/5280) by [@carltongibson](https://github.com/carltongibson). From 48ca7a6368f7e5bf4d8a6eb3bf3cc321d6cf8b6d Mon Sep 17 00:00:00 2001 From: Ruidy Date: Thu, 18 Aug 2022 18:01:14 +0200 Subject: [PATCH 011/194] =?UTF-8?q?=F0=9F=8C=90=20Add=20French=20translati?= =?UTF-8?q?on=20for=20`docs/fr/docs/history-design-future.md`=20(#3451)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sam Courtemanche Co-authored-by: Arthur Rio Co-authored-by: Ruidy Co-authored-by: Ruidy --- docs/fr/docs/history-design-future.md | 79 +++++++++++++++++++++++++++ docs/fr/mkdocs.yml | 1 + 2 files changed, 80 insertions(+) create mode 100644 docs/fr/docs/history-design-future.md diff --git a/docs/fr/docs/history-design-future.md b/docs/fr/docs/history-design-future.md new file mode 100644 index 0000000000000..b77664be6c2c0 --- /dev/null +++ b/docs/fr/docs/history-design-future.md @@ -0,0 +1,79 @@ +# Histoire, conception et avenir + +Il y a quelque temps, un utilisateur de **FastAPI** a demandé : + +> Quelle est l'histoire de ce projet ? Il semble être sorti de nulle part et est devenu génial en quelques semaines [...]. + +Voici un petit bout de cette histoire. + +## Alternatives + +Je crée des API avec des exigences complexes depuis plusieurs années (Machine Learning, systèmes distribués, jobs asynchrones, bases de données NoSQL, etc), en dirigeant plusieurs équipes de développeurs. + +Dans ce cadre, j'ai dû étudier, tester et utiliser de nombreuses alternatives. + +L'histoire de **FastAPI** est en grande partie l'histoire de ses prédécesseurs. + +Comme dit dans la section [Alternatives](alternatives.md){.internal-link target=\_blank} : + +
+ +**FastAPI** n'existerait pas sans le travail antérieur d'autres personnes. + +Il y a eu de nombreux outils créés auparavant qui ont contribué à inspirer sa création. + +J'ai évité la création d'un nouveau framework pendant plusieurs années. J'ai d'abord essayé de résoudre toutes les fonctionnalités couvertes par **FastAPI** en utilisant de nombreux frameworks, plug-ins et outils différents. + +Mais à un moment donné, il n'y avait pas d'autre option que de créer quelque chose qui offre toutes ces fonctionnalités, en prenant les meilleures idées des outils précédents, et en les combinant de la meilleure façon possible, en utilisant des fonctionnalités du langage qui n'étaient même pas disponibles auparavant (annotations de type pour Python 3.6+). + +
+ +## Recherche + +En utilisant toutes les alternatives précédentes, j'ai eu la chance d'apprendre de toutes, de prendre des idées, et de les combiner de la meilleure façon que j'ai pu trouver pour moi-même et les équipes de développeurs avec lesquelles j'ai travaillé. + +Par exemple, il était clair que l'idéal était de se baser sur les annotations de type Python standard. + +De plus, la meilleure approche était d'utiliser des normes déjà existantes. + +Ainsi, avant même de commencer à coder **FastAPI**, j'ai passé plusieurs mois à étudier les spécifications d'OpenAPI, JSON Schema, OAuth2, etc. Comprendre leurs relations, leurs similarités et leurs différences. + +## Conception + +Ensuite, j'ai passé du temps à concevoir l'"API" de développeur que je voulais avoir en tant qu'utilisateur (en tant que développeur utilisant FastAPI). + +J'ai testé plusieurs idées dans les éditeurs Python les plus populaires : PyCharm, VS Code, les éditeurs basés sur Jedi. + +D'après la dernière Enquête Développeurs Python, cela couvre environ 80% des utilisateurs. + +Cela signifie que **FastAPI** a été spécifiquement testé avec les éditeurs utilisés par 80% des développeurs Python. Et comme la plupart des autres éditeurs ont tendance à fonctionner de façon similaire, tous ses avantages devraient fonctionner pour pratiquement tous les éditeurs. + +Ainsi, j'ai pu trouver les meilleurs moyens de réduire autant que possible la duplication du code, d'avoir la complétion partout, les contrôles de type et d'erreur, etc. + +Le tout de manière à offrir la meilleure expérience de développement à tous les développeurs. + +## Exigences + +Après avoir testé plusieurs alternatives, j'ai décidé que j'allais utiliser **Pydantic** pour ses avantages. + +J'y ai ensuite contribué, pour le rendre entièrement compatible avec JSON Schema, pour supporter différentes manières de définir les déclarations de contraintes, et pour améliorer le support des éditeurs (vérifications de type, autocomplétion) sur la base des tests effectués dans plusieurs éditeurs. + +Pendant le développement, j'ai également contribué à **Starlette**, l'autre exigence clé. + +## Développement + +Au moment où j'ai commencé à créer **FastAPI** lui-même, la plupart des pièces étaient déjà en place, la conception était définie, les exigences et les outils étaient prêts, et la connaissance des normes et des spécifications était claire et fraîche. + +## Futur + +À ce stade, il est déjà clair que **FastAPI** et ses idées sont utiles pour de nombreuses personnes. + +Elle a été préférée aux solutions précédentes parce qu'elle convient mieux à de nombreux cas d'utilisation. + +De nombreux développeurs et équipes dépendent déjà de **FastAPI** pour leurs projets (y compris moi et mon équipe). + +Mais il y a encore de nombreuses améliorations et fonctionnalités à venir. + +**FastAPI** a un grand avenir devant lui. + +Et [votre aide](help-fastapi.md){.internal-link target=\_blank} est grandement appréciée. diff --git a/docs/fr/mkdocs.yml b/docs/fr/mkdocs.yml index 53d1b2c587308..32ce30ef6d179 100644 --- a/docs/fr/mkdocs.yml +++ b/docs/fr/mkdocs.yml @@ -72,6 +72,7 @@ nav: - deployment/docker.md - project-generation.md - alternatives.md +- history-design-future.md - external-links.md markdown_extensions: - toc: From b489b327b8e753d8b17fc17dab86f5c78d17533b Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 18 Aug 2022 16:01:57 +0000 Subject: [PATCH 012/194] =?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 976b96e22700f..bad8aca0dfae6 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 🌐 Add Russian translation for `docs/ru/docs/tutorial/background-tasks.md`. PR [#4854](https://github.com/tiangolo/fastapi/pull/4854) by [@AdmiralDesu](https://github.com/AdmiralDesu). * 🌐 Add Chinese translation for `docs/tutorial/security/first-steps.md`. PR [#3841](https://github.com/tiangolo/fastapi/pull/3841) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Japanese translation for `docs/ja/docs/advanced/nosql-databases.md`. PR [#4205](https://github.com/tiangolo/fastapi/pull/4205) by [@sUeharaE4](https://github.com/sUeharaE4). * 🌐 Add Indonesian translation for `docs/id/docs/tutorial/index.md`. PR [#4705](https://github.com/tiangolo/fastapi/pull/4705) by [@bas-baskara](https://github.com/bas-baskara). From 5d0e2f58e711979175fa2793bbdf9d08b520730d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fernando=20Sim=C3=B5es?= <66239468+frnsimoes@users.noreply.github.com> Date: Thu, 18 Aug 2022 13:02:20 -0300 Subject: [PATCH 013/194] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`tutorial/handling-errors.md`=20(#4769)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Lucas <61513630+lsglucas@users.noreply.github.com> Co-authored-by: Sebastián Ramírez --- docs/pt/docs/tutorial/handling-errors.md | 251 +++++++++++++++++++++++ docs/pt/mkdocs.yml | 1 + 2 files changed, 252 insertions(+) create mode 100644 docs/pt/docs/tutorial/handling-errors.md diff --git a/docs/pt/docs/tutorial/handling-errors.md b/docs/pt/docs/tutorial/handling-errors.md new file mode 100644 index 0000000000000..97a2e3eac9531 --- /dev/null +++ b/docs/pt/docs/tutorial/handling-errors.md @@ -0,0 +1,251 @@ +# Manipulação de erros + +Há diversas situações em que você precisa notificar um erro a um cliente que está utilizando a sua API. + +Esse cliente pode ser um browser com um frontend, o código de outra pessoa, um dispositivo IoT, etc. + +Pode ser que você precise comunicar ao cliente que: + +* O cliente não tem direitos para realizar aquela operação. +* O cliente não tem acesso aquele recurso. +* O item que o cliente está tentando acessar não existe. +* etc. + + +Nesses casos, você normalmente retornaria um **HTTP status code** próximo ao status code na faixa do status code **400** (do 400 ao 499). + +Isso é bastante similar ao caso do HTTP status code 200 (do 200 ao 299). Esses "200" status codes significam que, de algum modo, houve sucesso na requisição. + +Os status codes na faixa dos 400 significam que houve um erro por parte do cliente. + +Você se lembra de todos aqueles erros (e piadas) a respeito do "**404 Not Found**"? + +## Use o `HTTPException` + +Para retornar ao cliente *responses* HTTP com erros, use o `HTTPException`. + +### Import `HTTPException` + +```Python hl_lines="1" +{!../../../docs_src/handling_errors/tutorial001.py!} +``` + +### Lance o `HTTPException` no seu código. + +`HTTPException`, ao fundo, nada mais é do que a conjunção entre uma exceção comum do Python e informações adicionais relevantes para APIs. + +E porque é uma exceção do Python, você não **retorna** (return) o `HTTPException`, você lança o (raise) no seu código. + +Isso também significa que, se você está escrevendo uma função de utilidade, a qual você está chamando dentro da sua função de operações de caminhos, e você lança o `HTTPException` dentro da função de utilidade, o resto do seu código não será executado dentro da função de operações de caminhos. Ao contrário, o `HTTPException` irá finalizar a requisição no mesmo instante e enviará o erro HTTP oriundo do `HTTPException` para o cliente. + +O benefício de lançar uma exceção em vez de retornar um valor ficará mais evidente na seção sobre Dependências e Segurança. + +Neste exemplo, quando o cliente pede, na requisição, por um item cujo ID não existe, a exceção com o status code `404` é lançada: + +```Python hl_lines="11" +{!../../../docs_src/handling_errors/tutorial001.py!} +``` + +### A response resultante + + +Se o cliente faz uma requisição para `http://example.com/items/foo` (um `item_id` `"foo"`), esse cliente receberá um HTTP status code 200, e uma resposta JSON: + + +``` +{ + "item": "The Foo Wrestlers" +} +``` + +Mas se o cliente faz uma requisição para `http://example.com/items/bar` (ou seja, um não existente `item_id "bar"`), esse cliente receberá um HTTP status code 404 (o erro "não encontrado" — *not found error*), e uma resposta JSON: + +```JSON +{ + "detail": "Item not found" +} +``` + +!!! tip "Dica" + Quando você lançar um `HTTPException`, você pode passar qualquer valor convertível em JSON como parâmetro de `detail`, e não apenas `str`. + + Você pode passar um `dict` ou um `list`, etc. + Esses tipos de dados são manipulados automaticamente pelo **FastAPI** e convertidos em JSON. + + +## Adicione headers customizados + +Há certas situações em que é bastante útil poder adicionar headers customizados no HTTP error. Exemplo disso seria adicionar headers customizados para tipos de segurança. + +Você provavelmente não precisará utilizar esses headers diretamente no seu código. + +Mas caso você precise, para um cenário mais complexo, você pode adicionar headers customizados: + +```Python hl_lines="14" +{!../../../docs_src/handling_errors/tutorial002.py!} +``` + +## Instalando manipuladores de exceções customizados + +Você pode adicionar manipuladores de exceção customizados com a mesma seção de utilidade de exceções presentes no Starlette + +Digamos que você tenha uma exceção customizada `UnicornException` que você (ou uma biblioteca que você use) precise lançar (`raise`). + +Nesse cenário, se você precisa manipular essa exceção de modo global com o FastAPI, você pode adicionar um manipulador de exceção customizada com `@app.exception_handler()`. + +```Python hl_lines="5-7 13-18 24" +{!../../../docs_src/handling_errors/tutorial003.py!} +``` + +Nesse cenário, se você fizer uma requisição para `/unicorns/yolo`, a *operação de caminho* vai lançar (`raise`) o `UnicornException`. + +Essa exceção será manipulada, contudo, pelo `unicorn_exception_handler`. + +Dessa forma você receberá um erro "limpo", com o HTTP status code `418` e um JSON com o conteúdo: + +```JSON +{"message": "Oops! yolo did something. There goes a rainbow..."} +``` + +!!! note "Detalhes Técnicos" + Você também pode usar `from starlette.requests import Request` and `from starlette.responses import JSONResponse`. + + **FastAPI** disponibiliza o mesmo `starlette.responses` através do `fastapi.responses` por conveniência ao desenvolvedor. Contudo, a maior parte das respostas disponíveis vem diretamente do Starlette. O mesmo acontece com o `Request`. + +## Sobrescreva o manipulador padrão de exceções + +**FastAPI** tem alguns manipuladores padrão de exceções. + +Esses manipuladores são os responsáveis por retornar o JSON padrão de respostas quando você lança (`raise`) o `HTTPException` e quando a requisição tem dados invalidos. + +Você pode sobrescrever esses manipuladores de exceção com os seus próprios manipuladores. + +## Sobrescreva exceções de validação da requisição + +Quando a requisição contém dados inválidos, **FastAPI** internamente lança para o `RequestValidationError`. + +Para sobrescrevê-lo, importe o `RequestValidationError` e use-o com o `@app.exception_handler(RequestValidationError)` para decorar o manipulador de exceções. + +```Python hl_lines="2 14-16" +{!../../../docs_src/handling_errors/tutorial004.py!} +``` + +Se você for ao `/items/foo`, em vez de receber o JSON padrão com o erro: + +```JSON +{ + "detail": [ + { + "loc": [ + "path", + "item_id" + ], + "msg": "value is not a valid integer", + "type": "type_error.integer" + } + ] +} +``` + +você receberá a versão em texto: + +``` +1 validation error +path -> item_id + value is not a valid integer (type=type_error.integer) +``` + +### `RequestValidationError` vs `ValidationError` + +!!! warning "Aviso" + Você pode pular estes detalhes técnicos caso eles não sejam importantes para você neste momento. + +`RequestValidationError` é uma subclasse do `ValidationError` existente no Pydantic. + +**FastAPI** faz uso dele para que você veja o erro no seu log, caso você utilize um modelo de Pydantic em `response_model`, e seus dados tenham erro. + +Contudo, o cliente ou usuário não terão acesso a ele. Ao contrário, o cliente receberá um "Internal Server Error" com o HTTP status code `500`. + +E assim deve ser porque seria um bug no seu código ter o `ValidationError` do Pydantic na sua *response*, ou em qualquer outro lugar do seu código (que não na requisição do cliente). + +E enquanto você conserta o bug, os clientes / usuários não deveriam ter acesso às informações internas do erro, porque, desse modo, haveria exposição de uma vulnerabilidade de segurança. + +Do mesmo modo, você pode sobreescrever o `HTTPException`. + +Por exemplo, você pode querer retornar uma *response* em *plain text* ao invés de um JSON para os seguintes erros: + +```Python hl_lines="3-4 9-11 22" +{!../../../docs_src/handling_errors/tutorial004.py!} +``` + +!!! note "Detalhes Técnicos" + Você pode usar `from starlette.responses import PlainTextResponse`. + + **FastAPI** disponibiliza o mesmo `starlette.responses` como `fastapi.responses`, como conveniência a você, desenvolvedor. Contudo, a maior parte das respostas disponíveis vem diretamente do Starlette. + + +### Use o body do `RequestValidationError`. + +O `RequestValidationError` contém o `body` que ele recebeu de dados inválidos. + +Você pode utilizá-lo enquanto desenvolve seu app para conectar o *body* e debugá-lo, e assim retorná-lo ao usuário, etc. + +Tente enviar um item inválido como este: + +```JSON +{ + "title": "towel", + "size": "XL" +} +``` + +Você receberá uma *response* informando-o de que a data é inválida, e contendo o *body* recebido: + +```JSON hl_lines="12-15" +{ + "detail": [ + { + "loc": [ + "body", + "size" + ], + "msg": "value is not a valid integer", + "type": "type_error.integer" + } + ], + "body": { + "title": "towel", + "size": "XL" + } +} +``` + +#### O `HTTPException` do FastAPI vs o `HTTPException` do Starlette. + +O **FastAPI** tem o seu próprio `HTTPException`. + +E a classe de erro `HTTPException` do **FastAPI** herda da classe de erro do `HTTPException` do Starlette. + +A diferença entre os dois é a de que o `HTTPException` do **FastAPI** permite que você adicione *headers* que serão incluídos nas *responses*. + +Esses *headers* são necessários/utilizados internamente pelo OAuth 2.0 e também por outras utilidades de segurança. + +Portanto, você pode continuar lançando o `HTTPException` do **FastAPI** normalmente no seu código. + +Porém, quando você registrar um manipulador de exceção, você deve registrá-lo através do `HTTPException` do Starlette. + +Dessa forma, se qualquer parte do código interno, extensão ou plug-in do Starlette lançar o `HTTPException`, o seu manipulador de exceção poderá capturar esse lançamento e tratá-lo. + +```Python +from starlette.exceptions import HTTPException as StarletteHTTPException +``` + +### Re-use os manipulares de exceção do **FastAPI** + +Se você quer usar a exceção em conjunto com o mesmo manipulador de exceção *default* do **FastAPI**, você pode importar e re-usar esses manipuladores de exceção do `fastapi.exception_handlers`: + +```Python hl_lines="2-5 15 21" +{!../../../docs_src/handling_errors/tutorial006.py!} +``` + +Nesse exemplo você apenas imprime (`print`) o erro com uma mensagem expressiva. Mesmo assim, dá para pegar a ideia. Você pode usar a exceção e então apenas re-usar o manipulador de exceção *default*. diff --git a/docs/pt/mkdocs.yml b/docs/pt/mkdocs.yml index 3fb834bed9982..5b1bdb45e8dd4 100644 --- a/docs/pt/mkdocs.yml +++ b/docs/pt/mkdocs.yml @@ -69,6 +69,7 @@ nav: - tutorial/extra-data-types.md - tutorial/query-params-str-validations.md - tutorial/cookie-params.md + - tutorial/handling-errors.md - Segurança: - tutorial/security/index.md - Guia de Usuário Avançado: From f9dcff1490bf3887d988589798ab42015d228d00 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 18 Aug 2022 16:02:28 +0000 Subject: [PATCH 014/194] =?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 bad8aca0dfae6..784917dc7924c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* ✏ Fix typo in `docs/en/docs/python-types.md`. PR [#5007](https://github.com/tiangolo/fastapi/pull/5007) by [@atiabbz](https://github.com/atiabbz). * 🌐 Add Russian translation for `docs/ru/docs/tutorial/background-tasks.md`. PR [#4854](https://github.com/tiangolo/fastapi/pull/4854) by [@AdmiralDesu](https://github.com/AdmiralDesu). * 🌐 Add Chinese translation for `docs/tutorial/security/first-steps.md`. PR [#3841](https://github.com/tiangolo/fastapi/pull/3841) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Japanese translation for `docs/ja/docs/advanced/nosql-databases.md`. PR [#4205](https://github.com/tiangolo/fastapi/pull/4205) by [@sUeharaE4](https://github.com/sUeharaE4). From e5eb56f0b536f96dd618d3dacac1772f0f53623c Mon Sep 17 00:00:00 2001 From: Ruidy Date: Thu, 18 Aug 2022 18:02:40 +0200 Subject: [PATCH 015/194] =?UTF-8?q?=F0=9F=8C=90=20=20Add=20French=20transl?= =?UTF-8?q?ation=20for=20`docs/fr/docs/deployment/index.md`=20(#3689)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Arthur Rio Co-authored-by: Ruidy Co-authored-by: Ruidy Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- docs/fr/docs/deployment/index.md | 28 ++++++++++++++++++++++++++++ docs/fr/mkdocs.yml | 1 + 2 files changed, 29 insertions(+) create mode 100644 docs/fr/docs/deployment/index.md diff --git a/docs/fr/docs/deployment/index.md b/docs/fr/docs/deployment/index.md new file mode 100644 index 0000000000000..e855adfa3c1ed --- /dev/null +++ b/docs/fr/docs/deployment/index.md @@ -0,0 +1,28 @@ +# Déploiement - Intro + +Le déploiement d'une application **FastAPI** est relativement simple. + +## Que signifie le déploiement + +**Déployer** une application signifie effectuer les étapes nécessaires pour la rendre **disponible pour les +utilisateurs**. + +Pour une **API Web**, cela implique normalement de la placer sur une **machine distante**, avec un **programme serveur** +qui offre de bonnes performances, une bonne stabilité, _etc._, afin que vos **utilisateurs** puissent **accéder** à +l'application efficacement et sans interruption ni problème. + +Ceci contraste avec les étapes de **développement**, où vous êtes constamment en train de modifier le code, de le casser +et de le réparer, d'arrêter et de redémarrer le serveur de développement, _etc._ + +## Stratégies de déploiement + +Il existe plusieurs façons de procéder, en fonction de votre cas d'utilisation spécifique et des outils que vous +utilisez. + +Vous pouvez **déployer un serveur** vous-même en utilisant une combinaison d'outils, vous pouvez utiliser un **service +cloud** qui fait une partie du travail pour vous, ou encore d'autres options possibles. + +Je vais vous montrer certains des principaux concepts que vous devriez probablement avoir à l'esprit lors du déploiement +d'une application **FastAPI** (bien que la plupart de ces concepts s'appliquent à tout autre type d'application web). + +Vous verrez plus de détails à avoir en tête et certaines des techniques pour le faire dans les sections suivantes. ✨ diff --git a/docs/fr/mkdocs.yml b/docs/fr/mkdocs.yml index 32ce30ef6d179..6bed7be73853e 100644 --- a/docs/fr/mkdocs.yml +++ b/docs/fr/mkdocs.yml @@ -69,6 +69,7 @@ nav: - tutorial/background-tasks.md - async.md - Déploiement: + - deployment/index.md - deployment/docker.md - project-generation.md - alternatives.md From d268eb201136d5e1ba188f5e9cff9b201aabb5cc Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 18 Aug 2022 16:03:07 +0000 Subject: [PATCH 016/194] =?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 784917dc7924c..be16414433f52 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 🌐 Add French translation for `docs/fr/docs/history-design-future.md`. PR [#3451](https://github.com/tiangolo/fastapi/pull/3451) by [@rjNemo](https://github.com/rjNemo). * ✏ Fix typo in `docs/en/docs/python-types.md`. PR [#5007](https://github.com/tiangolo/fastapi/pull/5007) by [@atiabbz](https://github.com/atiabbz). * 🌐 Add Russian translation for `docs/ru/docs/tutorial/background-tasks.md`. PR [#4854](https://github.com/tiangolo/fastapi/pull/4854) by [@AdmiralDesu](https://github.com/AdmiralDesu). * 🌐 Add Chinese translation for `docs/tutorial/security/first-steps.md`. PR [#3841](https://github.com/tiangolo/fastapi/pull/3841) by [@jaystone776](https://github.com/jaystone776). From 46f5091c9f2e3c029d4aaecb43f95d5e01df6f30 Mon Sep 17 00:00:00 2001 From: Marcelo Trylesinski Date: Thu, 18 Aug 2022 18:04:33 +0200 Subject: [PATCH 017/194] =?UTF-8?q?=E2=9C=8F=20Fix=20typo=20in=20`python-t?= =?UTF-8?q?ypes.md`=20(#5116)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/python-types.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/python-types.md b/docs/en/docs/python-types.md index f170bb1ef4b1d..3b0ee4cf6b1e4 100644 --- a/docs/en/docs/python-types.md +++ b/docs/en/docs/python-types.md @@ -326,7 +326,7 @@ If you are using a Python version below 3.10, here's a tip from my very **subjec Both are equivalent and underneath they are the same, but I would recommend `Union` instead of `Optional` because the word "**optional**" would seem to imply that the value is optional, and it actually means "it can be `None`", even if it's not optional and is still required. -I think `Union[str, SomeType]` is more explicit about what it means. +I think `Union[SomeType, None]` is more explicit about what it means. It's just about the words and names. But those words can affect how you and your teammates think about the code. From 441b72653757d5a4e3fb77ff2ed1f5e939b4c462 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 18 Aug 2022 16:05:11 +0000 Subject: [PATCH 018/194] =?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 be16414433f52..b57fa78bd78c7 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 🌐 Add Portuguese translation for `tutorial/handling-errors.md`. PR [#4769](https://github.com/tiangolo/fastapi/pull/4769) by [@frnsimoes](https://github.com/frnsimoes). * 🌐 Add French translation for `docs/fr/docs/history-design-future.md`. PR [#3451](https://github.com/tiangolo/fastapi/pull/3451) by [@rjNemo](https://github.com/rjNemo). * ✏ Fix typo in `docs/en/docs/python-types.md`. PR [#5007](https://github.com/tiangolo/fastapi/pull/5007) by [@atiabbz](https://github.com/atiabbz). * 🌐 Add Russian translation for `docs/ru/docs/tutorial/background-tasks.md`. PR [#4854](https://github.com/tiangolo/fastapi/pull/4854) by [@AdmiralDesu](https://github.com/AdmiralDesu). From 8afd291572c72d54e9daa353d0ccd0fc87cbb42f Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 18 Aug 2022 16:05:42 +0000 Subject: [PATCH 019/194] =?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 b57fa78bd78c7..8dfa6d1465e0e 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 🌐 Add French translation for `docs/fr/docs/deployment/index.md`. PR [#3689](https://github.com/tiangolo/fastapi/pull/3689) by [@rjNemo](https://github.com/rjNemo). * 🌐 Add Portuguese translation for `tutorial/handling-errors.md`. PR [#4769](https://github.com/tiangolo/fastapi/pull/4769) by [@frnsimoes](https://github.com/frnsimoes). * 🌐 Add French translation for `docs/fr/docs/history-design-future.md`. PR [#3451](https://github.com/tiangolo/fastapi/pull/3451) by [@rjNemo](https://github.com/rjNemo). * ✏ Fix typo in `docs/en/docs/python-types.md`. PR [#5007](https://github.com/tiangolo/fastapi/pull/5007) by [@atiabbz](https://github.com/atiabbz). From e90d53f6f4c455a4f2787a02a8f08b94b2b80cc0 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 18 Aug 2022 16:06:52 +0000 Subject: [PATCH 020/194] =?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 8dfa6d1465e0e..aca99264bf2e8 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* ✏ Fix typo in `python-types.md`. PR [#5116](https://github.com/tiangolo/fastapi/pull/5116) by [@Kludex](https://github.com/Kludex). * 🌐 Add French translation for `docs/fr/docs/deployment/index.md`. PR [#3689](https://github.com/tiangolo/fastapi/pull/3689) by [@rjNemo](https://github.com/rjNemo). * 🌐 Add Portuguese translation for `tutorial/handling-errors.md`. PR [#4769](https://github.com/tiangolo/fastapi/pull/4769) by [@frnsimoes](https://github.com/frnsimoes). * 🌐 Add French translation for `docs/fr/docs/history-design-future.md`. PR [#3451](https://github.com/tiangolo/fastapi/pull/3451) by [@rjNemo](https://github.com/rjNemo). From fb849ee7ef623c4a6f581a78d46b4d4bc583d189 Mon Sep 17 00:00:00 2001 From: zhangbo Date: Fri, 19 Aug 2022 00:09:38 +0800 Subject: [PATCH 021/194] =?UTF-8?q?=F0=9F=8C=90=20Add=20translation=20for?= =?UTF-8?q?=20`docs/zh/docs/advanced/response-cookies.md`=20(#4638)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: zhangbo --- docs/zh/docs/advanced/response-cookies.md | 47 +++++++++++++++++++++++ docs/zh/mkdocs.yml | 1 + 2 files changed, 48 insertions(+) create mode 100644 docs/zh/docs/advanced/response-cookies.md diff --git a/docs/zh/docs/advanced/response-cookies.md b/docs/zh/docs/advanced/response-cookies.md new file mode 100644 index 0000000000000..3e53c53191a4c --- /dev/null +++ b/docs/zh/docs/advanced/response-cookies.md @@ -0,0 +1,47 @@ +# 响应Cookies + +## 使用 `Response` 参数 + +你可以在 *路径函数* 中定义一个类型为 `Response`的参数,这样你就可以在这个临时响应对象中设置cookie了。 + +```Python hl_lines="1 8-9" +{!../../../docs_src/response_cookies/tutorial002.py!} +``` + +而且你还可以根据你的需要响应不同的对象,比如常用的 `dict`,数据库model等。 + +如果你定义了 `response_model`,程序会自动根据`response_model`来过滤和转换你响应的对象。 + +**FastAPI** 会使用这个 *临时* 响应对象去装在这些cookies信息 (同样还有headers和状态码等信息), 最终会将这些信息和通过`response_model`转化过的数据合并到最终的响应里。 + +你也可以在depend中定义`Response`参数,并设置cookie和header。 + +## 直接响应 `Response` + +你还可以在直接响应`Response`时直接创建cookies。 + +你可以参考[Return a Response Directly](response-directly.md){.internal-link target=_blank}来创建response + +然后设置Cookies,并返回: + +```Python hl_lines="10-12" +{!../../../docs_src/response_cookies/tutorial001.py!} +``` + +!!! tip + 需要注意,如果你直接反馈一个response对象,而不是使用`Response`入参,FastAPI则会直接反馈你封装的response对象。 + + 所以你需要确保你响应数据类型的正确性,如:你可以使用`JSONResponse`来兼容JSON的场景。 + + 同时,你也应当仅反馈通过`response_model`过滤过的数据。 + +### 更多信息 + +!!! note "技术细节" + 你也可以使用`from starlette.responses import Response` 或者 `from starlette.responses import JSONResponse`。 + + 为了方便开发者,**FastAPI** 封装了相同数据类型,如`starlette.responses` 和 `fastapi.responses`。不过大部分response对象都是直接引用自Starlette。 + + 因为`Response`对象可以非常便捷的设置headers和cookies,所以 **FastAPI** 同时也封装了`fastapi.Response`。 + +如果你想查看所有可用的参数和选项,可以参考 Starlette帮助文档 diff --git a/docs/zh/mkdocs.yml b/docs/zh/mkdocs.yml index 9e8813d6c3a68..b60a0b7a188b5 100644 --- a/docs/zh/mkdocs.yml +++ b/docs/zh/mkdocs.yml @@ -107,6 +107,7 @@ nav: - advanced/additional-status-codes.md - advanced/response-directly.md - advanced/custom-response.md + - advanced/response-cookies.md - contributing.md - help-fastapi.md - benchmarks.md From f79e6a48a19ef79d1b2368acadecd07ea309dcc5 Mon Sep 17 00:00:00 2001 From: Vini Sousa <101301034+FLAIR7@users.noreply.github.com> Date: Thu, 18 Aug 2022 13:10:25 -0300 Subject: [PATCH 022/194] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/tutorial/security/first-steps.md`?= =?UTF-8?q?=20(#4954)?= 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> --- docs/pt/docs/tutorial/security/first-steps.md | 181 ++++++++++++++++++ 1 file changed, 181 insertions(+) create mode 100644 docs/pt/docs/tutorial/security/first-steps.md diff --git a/docs/pt/docs/tutorial/security/first-steps.md b/docs/pt/docs/tutorial/security/first-steps.md new file mode 100644 index 0000000000000..ed07d1c963102 --- /dev/null +++ b/docs/pt/docs/tutorial/security/first-steps.md @@ -0,0 +1,181 @@ +# Segurança - Primeiros Passos + +Vamos imaginar que você tem a sua API **backend** em algum domínio. + +E você tem um **frontend** em outro domínio ou em um path diferente no mesmo domínio (ou em uma aplicação mobile). + +E você quer uma maneira de o frontend autenticar o backend, usando um **username** e **senha**. + +Nós podemos usar o **OAuth2** junto com o **FastAPI**. + +Mas, vamos poupar-lhe o tempo de ler toda a especificação apenas para achar as pequenas informações que você precisa. + +Vamos usar as ferramentas fornecidas pela **FastAPI** para lidar com segurança. + +## Como Parece + +Vamos primeiro usar o código e ver como funciona, e depois voltaremos para entender o que está acontecendo. + +## Crie um `main.py` +Copie o exemplo em um arquivo `main.py`: + +```Python +{!../../../docs_src/security/tutorial001.py!} +``` + +## Execute-o + +!!! informação + Primeiro, instale `python-multipart`. + + Ex: `pip install python-multipart`. + + Isso ocorre porque o **OAuth2** usa "dados de um formulário" para mandar o **username** e **senha**. + +Execute esse exemplo com: + +
+ +```console +$ uvicorn main:app --reload + +INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) +``` + +
+ +## Verifique-o + +Vá até a documentação interativa em: http://127.0.0.1:8000/docs. + +Você verá algo deste tipo: + + + +!!! marque o "botão de Autorizar!" + Você já tem um novo "botão de autorizar!". + + E seu *path operation* tem um pequeno cadeado no canto superior direito que você pode clicar. + +E se você clicar, você terá um pequeno formulário de autorização para digitar o `username` e `senha` (e outros campos opcionais): + + + +!!! nota + Não importa o que você digita no formulário, não vai funcionar ainda. Mas nós vamos chegar lá. + +Claro que este não é o frontend para os usuários finais, mas é uma ótima ferramenta automática para documentar interativamente toda sua API. + +Pode ser usado pelo time de frontend (que pode ser você no caso). + +Pode ser usado por aplicações e sistemas third party (de terceiros). + +E também pode ser usada por você mesmo, para debugar, checar e testar a mesma aplicação. + +## O Fluxo da `senha` + +Agora vamos voltar um pouco e entender o que é isso tudo. + +O "fluxo" da `senha` é um dos caminhos ("fluxos") definidos no OAuth2, para lidar com a segurança e autenticação. + +OAuth2 foi projetado para que o backend ou a API pudesse ser independente do servidor que autentica o usuário. + +Mas nesse caso, a mesma aplicação **FastAPI** irá lidar com a API e a autenticação. + +Então, vamos rever de um ponto de vista simplificado: + +* O usuário digita o `username` e a `senha` no frontend e aperta `Enter`. +* O frontend (rodando no browser do usuário) manda o `username` e a `senha` para uma URL específica na sua API (declarada com `tokenUrl="token"`). +* A API checa aquele `username` e `senha`, e responde com um "token" (nós não implementamos nada disso ainda). + * Um "token" é apenas uma string com algum conteúdo que nós podemos utilizar mais tarde para verificar o usuário. + * Normalmente, um token é definido para expirar depois de um tempo. + * Então, o usuário terá que se logar de novo depois de um tempo. + * E se o token for roubado, o risco é menor. Não é como se fosse uma chave permanente que vai funcionar para sempre (na maioria dos casos). + * O frontend armazena aquele token temporariamente em algum lugar. + * O usuário clica no frontend para ir à outra seção daquele frontend do aplicativo web. + * O frontend precisa buscar mais dados daquela API. + * Mas precisa de autenticação para aquele endpoint em específico. + * Então, para autenticar com nossa API, ele manda um header de `Autorização` com o valor `Bearer` mais o token. + * Se o token contém `foobar`, o conteúdo do header de `Autorização` será: `Bearer foobar`. + +## **FastAPI**'s `OAuth2PasswordBearer` + +**FastAPI** fornece várias ferramentas, em diferentes níveis de abstração, para implementar esses recursos de segurança. + +Neste exemplo, nós vamos usar o **OAuth2** com o fluxo de **Senha**, usando um token **Bearer**. Fazemos isso usando a classe `OAuth2PasswordBearer`. + +!!! informação + Um token "bearer" não é a única opção. + + Mas é a melhor no nosso caso. + + E talvez seja a melhor para a maioria dos casos, a não ser que você seja um especialista em OAuth2 e saiba exatamente o porquê de existir outras opções que se adequam melhor às suas necessidades. + + Nesse caso, **FastAPI** também fornece as ferramentas para construir. + +Quando nós criamos uma instância da classe `OAuth2PasswordBearer`, nós passamos pelo parâmetro `tokenUrl` Esse parâmetro contém a URL que o client (o frontend rodando no browser do usuário) vai usar para mandar o `username` e `senha` para obter um token. + +```Python hl_lines="6" +{!../../../docs_src/security/tutorial001.py!} +``` + +!!! dica + Esse `tokenUrl="token"` se refere a uma URL relativa que nós não criamos ainda. Como é uma URL relativa, é equivalente a `./token`. + + Porque estamos usando uma URL relativa, se sua API estava localizada em `https://example.com/`, então irá referir-se à `https://example.com/token`. Mas se sua API estava localizada em `https://example.com/api/v1/`, então irá referir-se à `https://example.com/api/v1/token`. + + Usar uma URL relativa é importante para garantir que sua aplicação continue funcionando, mesmo em um uso avançado tipo [Atrás de um Proxy](../../advanced/behind-a-proxy.md){.internal-link target=_blank}. + +Esse parâmetro não cria um endpoint / *path operation*, mas declara que a URL `/token` vai ser aquela que o client deve usar para obter o token. Essa informação é usada no OpenAPI, e depois na API Interativa de documentação de sistemas. + +Em breve também criaremos o atual path operation. + +!!! informação + Se você é um "Pythonista" muito rigoroso, você pode não gostar do estilo do nome do parâmetro `tokenUrl` em vez de `token_url`. + + Isso ocorre porque está utilizando o mesmo nome que está nas especificações do OpenAPI. Então, se você precisa investigar mais sobre qualquer um desses esquemas de segurança, você pode simplesmente copiar e colar para encontrar mais informações sobre isso. + +A variável `oauth2_scheme` é um instância de `OAuth2PasswordBearer`, mas também é um "callable". + +Pode ser chamada de: + +```Python +oauth2_scheme(some, parameters) +``` + +Então, pode ser usado com `Depends`. + +## Use-o + +Agora você pode passar aquele `oauth2_scheme` em uma dependência com `Depends`. + +```Python hl_lines="10" +{!../../../docs_src/security/tutorial001.py!} +``` + +Esse dependência vai fornecer uma `str` que é atribuído ao parâmetro `token da *função do path operation* + +A **FastAPI** saberá que pode usar essa dependência para definir um "esquema de segurança" no esquema da OpenAPI (e na documentação da API automática). + +!!! informação "Detalhes técnicos" + **FastAPI** saberá que pode usar a classe `OAuth2PasswordBearer` (declarada na dependência) para definir o esquema de segurança na OpenAPI porque herda de `fastapi.security.oauth2.OAuth2`, que por sua vez herda de `fastapi.security.base.Securitybase`. + + Todos os utilitários de segurança que se integram com OpenAPI (e na documentação da API automática) herdam de `SecurityBase`, é assim que **FastAPI** pode saber como integrá-los no OpenAPI. + +## O que ele faz + +Ele irá e olhará na requisição para aquele header de `Autorização`, verificará se o valor é `Bearer` mais algum token, e vai retornar o token como uma `str` + +Se ele não ver o header de `Autorização` ou o valor não tem um token `Bearer`, vai responder com um código de erro 401 (`UNAUTHORIZED`) diretamente. + +Você nem precisa verificar se o token existe para retornar um erro. Você pode ter certeza de que se a sua função for executada, ela terá um `str` nesse token. + +Você já pode experimentar na documentação interativa: + + + +Não estamos verificando a validade do token ainda, mas isso já é um começo + +## Recapitulando + +Então, em apenas 3 ou 4 linhas extras, você já tem alguma forma primitiva de segurança. From a9c2b8336b980da91e5d2a754a00c6e2fffed4d0 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 18 Aug 2022 16:11:55 +0000 Subject: [PATCH 023/194] =?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 aca99264bf2e8..0d2ed3d07a17d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 🌐 Add translation for `docs/zh/docs/advanced/response-cookies.md`. PR [#4638](https://github.com/tiangolo/fastapi/pull/4638) by [@zhangbo2012](https://github.com/zhangbo2012). * ✏ Fix typo in `python-types.md`. PR [#5116](https://github.com/tiangolo/fastapi/pull/5116) by [@Kludex](https://github.com/Kludex). * 🌐 Add French translation for `docs/fr/docs/deployment/index.md`. PR [#3689](https://github.com/tiangolo/fastapi/pull/3689) by [@rjNemo](https://github.com/rjNemo). * 🌐 Add Portuguese translation for `tutorial/handling-errors.md`. PR [#4769](https://github.com/tiangolo/fastapi/pull/4769) by [@frnsimoes](https://github.com/frnsimoes). From 30e7b6a34cf41c927979c595e90329acf9ecca7d Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 18 Aug 2022 16:12:24 +0000 Subject: [PATCH 024/194] =?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 0d2ed3d07a17d..88ec5566b426c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/security/first-steps.md`. PR [#4954](https://github.com/tiangolo/fastapi/pull/4954) by [@FLAIR7](https://github.com/FLAIR7). * 🌐 Add translation for `docs/zh/docs/advanced/response-cookies.md`. PR [#4638](https://github.com/tiangolo/fastapi/pull/4638) by [@zhangbo2012](https://github.com/zhangbo2012). * ✏ Fix typo in `python-types.md`. PR [#5116](https://github.com/tiangolo/fastapi/pull/5116) by [@Kludex](https://github.com/Kludex). * 🌐 Add French translation for `docs/fr/docs/deployment/index.md`. PR [#3689](https://github.com/tiangolo/fastapi/pull/3689) by [@rjNemo](https://github.com/rjNemo). From 73c6011ec47ebc2b08fd2b05c3a4acf03155d818 Mon Sep 17 00:00:00 2001 From: Bruno Artur Torres Lopes Pereira <33462923+batlopes@users.noreply.github.com> Date: Thu, 18 Aug 2022 13:13:12 -0300 Subject: [PATCH 025/194] =?UTF-8?q?=F0=9F=8C=90=20Add=20Portuguese=20trans?= =?UTF-8?q?lation=20for=20`docs/pt/docs/tutorial/query-params.md`=20(#4775?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs/pt/docs/tutorial/query-params.md | 224 ++++++++++++++++++++++++++ docs/pt/mkdocs.yml | 1 + 2 files changed, 225 insertions(+) create mode 100644 docs/pt/docs/tutorial/query-params.md diff --git a/docs/pt/docs/tutorial/query-params.md b/docs/pt/docs/tutorial/query-params.md new file mode 100644 index 0000000000000..1897243961b73 --- /dev/null +++ b/docs/pt/docs/tutorial/query-params.md @@ -0,0 +1,224 @@ +# Parâmetros de Consulta + +Quando você declara outros parâmetros na função que não fazem parte dos parâmetros da rota, esses parâmetros são automaticamente interpretados como parâmetros de "consulta". + +```Python hl_lines="9" +{!../../../docs_src/query_params/tutorial001.py!} +``` + +A consulta é o conjunto de pares chave-valor que vai depois de `?` na URL, separado pelo caractere `&`. + +Por exemplo, na URL: + +``` +http://127.0.0.1:8000/items/?skip=0&limit=10 +``` + +...os parâmetros da consulta são: + +* `skip`: com o valor `0` +* `limit`: com o valor `10` + +Como eles são parte da URL, eles são "naturalmente" strings. + +Mas quando você declara eles com os tipos do Python (no exemplo acima, como `int`), eles são convertidos para aquele tipo e validados em relação a ele. + +Todo o processo que era aplicado para parâmetros de rota também é aplicado para parâmetros de consulta: + +* Suporte do editor (obviamente) +* "Parsing" de dados +* Validação de dados +* Documentação automática + +## Valores padrão + +Como os parâmetros de consulta não são uma parte fixa da rota, eles podem ser opcionais e podem ter valores padrão. + +No exemplo acima eles tem valores padrão de `skip=0` e `limit=10`. + +Então, se você for até a URL: + +``` +http://127.0.0.1:8000/items/ +``` + +Seria o mesmo que ir para: + +``` +http://127.0.0.1:8000/items/?skip=0&limit=10 +``` + +Mas, se por exemplo você for para: + +``` +http://127.0.0.1:8000/items/?skip=20 +``` + +Os valores dos parâmetros na sua função serão: + +* `skip=20`: Por que você definiu isso na URL +* `limit=10`: Por que esse era o valor padrão + +## Parâmetros opcionais + +Da mesma forma, você pode declarar parâmetros de consulta opcionais, definindo o valor padrão para `None`: + +=== "Python 3.6 and above" + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params/tutorial002.py!} + ``` + +=== "Python 3.10 and above" + + ```Python hl_lines="7" + {!> ../../../docs_src/query_params/tutorial002_py310.py!} + ``` + +Nesse caso, o parâmetro da função `q` será opcional, e `None` será o padrão. + +!!! check "Verificar" + Você também pode notar que o **FastAPI** é esperto o suficiente para perceber que o parâmetro da rota `item_id` é um parâmetro da rota, e `q` não é, portanto, `q` é o parâmetro de consulta. + + +## Conversão dos tipos de parâmetros de consulta + +Você também pode declarar tipos `bool`, e eles serão convertidos: + +=== "Python 3.6 and above" + + ```Python hl_lines="9" + {!> ../../../docs_src/query_params/tutorial003.py!} + ``` + +=== "Python 3.10 and above" + + ```Python hl_lines="7" + {!> ../../../docs_src/query_params/tutorial003_py310.py!} + ``` + +Nesse caso, se você for para: + +``` +http://127.0.0.1:8000/items/foo?short=1 +``` + +ou + +``` +http://127.0.0.1:8000/items/foo?short=True +``` + +ou + +``` +http://127.0.0.1:8000/items/foo?short=true +``` + +ou + +``` +http://127.0.0.1:8000/items/foo?short=on +``` + +ou + +``` +http://127.0.0.1:8000/items/foo?short=yes +``` + +ou qualquer outra variação (tudo em maiúscula, primeira letra em maiúscula, etc), a sua função vai ver o parâmetro `short` com um valor `bool` de `True`. Caso contrário `False`. + +## Múltiplos parâmetros de rota e consulta + +Você pode declarar múltiplos parâmetros de rota e parâmetros de consulta ao mesmo tempo, o **FastAPI** vai saber o quê é o quê. + +E você não precisa declarar eles em nenhuma ordem específica. + +Eles serão detectados pelo nome: + +=== "Python 3.6 and above" + + ```Python hl_lines="8 10" + {!> ../../../docs_src/query_params/tutorial004.py!} + ``` + +=== "Python 3.10 and above" + + ```Python hl_lines="6 8" + {!> ../../../docs_src/query_params/tutorial004_py310.py!} + ``` + +## Parâmetros de consulta obrigatórios + +Quando você declara um valor padrão para parâmetros que não são de rota (até agora, nós vimos apenas parâmetros de consulta), então eles não são obrigatórios. + +Caso você não queira adicionar um valor específico mas queira apenas torná-lo opcional, defina o valor padrão como `None`. + +Porém, quando você quiser fazer com que o parâmetro de consulta seja obrigatório, você pode simplesmente não declarar nenhum valor como padrão. + +```Python hl_lines="6-7" +{!../../../docs_src/query_params/tutorial005.py!} +``` + +Aqui o parâmetro de consulta `needy` é um valor obrigatório, do tipo `str`. + +Se você abrir no seu navegador a URL: + +``` +http://127.0.0.1:8000/items/foo-item +``` + +... sem adicionar o parâmetro obrigatório `needy`, você verá um erro como: + +```JSON +{ + "detail": [ + { + "loc": [ + "query", + "needy" + ], + "msg": "field required", + "type": "value_error.missing" + } + ] +} +``` + +Como `needy` é um parâmetro obrigatório, você precisaria defini-lo na URL: + +``` +http://127.0.0.1:8000/items/foo-item?needy=sooooneedy +``` + +...isso deve funcionar: + +```JSON +{ + "item_id": "foo-item", + "needy": "sooooneedy" +} +``` + +E claro, você pode definir alguns parâmetros como obrigatórios, alguns possuindo um valor padrão, e outros sendo totalmente opcionais: + +=== "Python 3.6 and above" + + ```Python hl_lines="10" + {!> ../../../docs_src/query_params/tutorial006.py!} + ``` + +=== "Python 3.10 and above" + + ```Python hl_lines="8" + {!> ../../../docs_src/query_params/tutorial006_py310.py!} + ``` +Nesse caso, existem 3 parâmetros de consulta: + +* `needy`, um `str` obrigatório. +* `skip`, um `int` com o valor padrão `0`. +* `limit`, um `int` opcional. + +!!! tip "Dica" + Você também poderia usar `Enum` da mesma forma que com [Path Parameters](path-params.md#predefined-values){.internal-link target=_blank}. diff --git a/docs/pt/mkdocs.yml b/docs/pt/mkdocs.yml index 5b1bdb45e8dd4..c37b855d8a0b9 100644 --- a/docs/pt/mkdocs.yml +++ b/docs/pt/mkdocs.yml @@ -64,6 +64,7 @@ nav: - tutorial/index.md - tutorial/first-steps.md - tutorial/path-params.md + - tutorial/query-params.md - tutorial/body.md - tutorial/body-fields.md - tutorial/extra-data-types.md From 58848897f49ac61d0ac7fdabc473e1c93eb13950 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 18 Aug 2022 16:15:37 +0000 Subject: [PATCH 026/194] =?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 88ec5566b426c..0be6db642d4bc 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/query-params.md`. PR [#4775](https://github.com/tiangolo/fastapi/pull/4775) by [@batlopes](https://github.com/batlopes). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/security/first-steps.md`. PR [#4954](https://github.com/tiangolo/fastapi/pull/4954) by [@FLAIR7](https://github.com/FLAIR7). * 🌐 Add translation for `docs/zh/docs/advanced/response-cookies.md`. PR [#4638](https://github.com/tiangolo/fastapi/pull/4638) by [@zhangbo2012](https://github.com/zhangbo2012). * ✏ Fix typo in `python-types.md`. PR [#5116](https://github.com/tiangolo/fastapi/pull/5116) by [@Kludex](https://github.com/Kludex). From 38802eefeb7c1ef8c80373a7a07a7cb402946228 Mon Sep 17 00:00:00 2001 From: Yumihiki <41376154+Yumihiki@users.noreply.github.com> Date: Fri, 19 Aug 2022 01:16:54 +0900 Subject: [PATCH 027/194] =?UTF-8?q?=F0=9F=93=9D=20Quote=20`pip=20install`?= =?UTF-8?q?=20command=20for=20Zsh=20compatibility=20in=20multiple=20langua?= =?UTF-8?q?ges=20(#5214)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs/de/docs/index.md | 2 +- docs/es/docs/index.md | 2 +- docs/es/docs/tutorial/index.md | 4 ++-- docs/fr/docs/index.md | 2 +- docs/id/docs/index.md | 2 +- docs/it/docs/index.md | 2 +- docs/ja/docs/deployment/manually.md | 2 +- docs/ja/docs/index.md | 2 +- docs/ja/docs/tutorial/index.md | 4 ++-- docs/ko/docs/index.md | 2 +- docs/ko/docs/tutorial/index.md | 2 +- docs/pl/docs/index.md | 2 +- docs/pt/docs/deployment.md | 2 +- docs/pt/docs/index.md | 2 +- docs/pt/docs/tutorial/index.md | 4 ++-- docs/ru/docs/index.md | 2 +- docs/sq/docs/index.md | 2 +- docs/tr/docs/index.md | 2 +- docs/uk/docs/index.md | 2 +- docs/zh/docs/index.md | 2 +- docs/zh/docs/tutorial/index.md | 4 ++-- 21 files changed, 25 insertions(+), 25 deletions(-) diff --git a/docs/de/docs/index.md b/docs/de/docs/index.md index 9297544622de2..287c79cff6e1a 100644 --- a/docs/de/docs/index.md +++ b/docs/de/docs/index.md @@ -135,7 +135,7 @@ You will also need an ASGI server, for production such as ```console -$ pip install uvicorn[standard] +$ pip install "uvicorn[standard]" ---> 100% ``` diff --git a/docs/es/docs/index.md b/docs/es/docs/index.md index ef4850b56518c..44c59202aa6b6 100644 --- a/docs/es/docs/index.md +++ b/docs/es/docs/index.md @@ -130,7 +130,7 @@ También vas a necesitar un servidor ASGI para producción cómo ```console -$ pip install uvicorn[standard] +$ pip install "uvicorn[standard]" ---> 100% ``` diff --git a/docs/es/docs/tutorial/index.md b/docs/es/docs/tutorial/index.md index 9cbdb272759d2..e3671f381ef09 100644 --- a/docs/es/docs/tutorial/index.md +++ b/docs/es/docs/tutorial/index.md @@ -41,7 +41,7 @@ Para el tutorial, es posible que quieras instalarlo con todas las dependencias y
```console -$ pip install fastapi[all] +$ pip install "fastapi[all]" ---> 100% ``` @@ -62,7 +62,7 @@ $ pip install fastapi[all] También debes instalar `uvicorn` para que funcione como tu servidor: ``` - pip install uvicorn[standard] + pip install "uvicorn[standard]" ``` Y lo mismo para cada una de las dependencias opcionales que quieras utilizar. diff --git a/docs/fr/docs/index.md b/docs/fr/docs/index.md index f713ee96b386f..1307c063bbc8e 100644 --- a/docs/fr/docs/index.md +++ b/docs/fr/docs/index.md @@ -135,7 +135,7 @@ You will also need an ASGI server, for production such as ```console -$ pip install uvicorn[standard] +$ pip install "uvicorn[standard]" ---> 100% ``` diff --git a/docs/id/docs/index.md b/docs/id/docs/index.md index 0bb7b55e3b065..041e0b754f1c1 100644 --- a/docs/id/docs/index.md +++ b/docs/id/docs/index.md @@ -135,7 +135,7 @@ You will also need an ASGI server, for production such as ```console -$ pip install uvicorn[standard] +$ pip install "uvicorn[standard]" ---> 100% ``` diff --git a/docs/it/docs/index.md b/docs/it/docs/index.md index 6acf925528935..5cbe78a717bb7 100644 --- a/docs/it/docs/index.md +++ b/docs/it/docs/index.md @@ -135,7 +135,7 @@ You will also need an ASGI server, for production such as ```console -$ pip install uvicorn[standard] +$ pip install "uvicorn[standard]" ---> 100% ``` diff --git a/docs/ja/docs/deployment/manually.md b/docs/ja/docs/deployment/manually.md index dd4b568bdcd65..67010a66f489d 100644 --- a/docs/ja/docs/deployment/manually.md +++ b/docs/ja/docs/deployment/manually.md @@ -11,7 +11,7 @@
```console - $ pip install uvicorn[standard] + $ pip install "uvicorn[standard]" ---> 100% ``` diff --git a/docs/ja/docs/index.md b/docs/ja/docs/index.md index 5fca78a833ec3..51977037c2208 100644 --- a/docs/ja/docs/index.md +++ b/docs/ja/docs/index.md @@ -131,7 +131,7 @@ $ pip install fastapi
```console -$ pip install uvicorn[standard] +$ pip install "uvicorn[standard]" ---> 100% ``` diff --git a/docs/ja/docs/tutorial/index.md b/docs/ja/docs/tutorial/index.md index 29fc86f94bcd8..a2dd59c9b03cb 100644 --- a/docs/ja/docs/tutorial/index.md +++ b/docs/ja/docs/tutorial/index.md @@ -43,7 +43,7 @@ $ uvicorn main:app --reload
```console -$ pip install fastapi[all] +$ pip install "fastapi[all]" ---> 100% ``` @@ -64,7 +64,7 @@ $ pip install fastapi[all] また、サーバーとして動作するように`uvicorn` をインストールします: ``` - pip install uvicorn[standard] + pip install "uvicorn[standard]" ``` そして、使用したい依存関係をそれぞれ同様にインストールします。 diff --git a/docs/ko/docs/index.md b/docs/ko/docs/index.md index ec44229947b7c..5a258f47b2504 100644 --- a/docs/ko/docs/index.md +++ b/docs/ko/docs/index.md @@ -131,7 +131,7 @@ $ pip install fastapi
```console -$ pip install uvicorn[standard] +$ pip install "uvicorn[standard]" ---> 100% ``` diff --git a/docs/ko/docs/tutorial/index.md b/docs/ko/docs/tutorial/index.md index 622aad1aa6ac8..d6db525e8dbd6 100644 --- a/docs/ko/docs/tutorial/index.md +++ b/docs/ko/docs/tutorial/index.md @@ -43,7 +43,7 @@ $ uvicorn main:app --reload
```console -$ pip install fastapi[all] +$ pip install "fastapi[all]" ---> 100% ``` diff --git a/docs/pl/docs/index.md b/docs/pl/docs/index.md index bbe1b1ad15e0d..9cc99ba7200a0 100644 --- a/docs/pl/docs/index.md +++ b/docs/pl/docs/index.md @@ -130,7 +130,7 @@ Na serwerze produkcyjnym będziesz także potrzebował serwera ASGI, np. ```console -$ pip install uvicorn[standard] +$ pip install "uvicorn[standard]" ---> 100% ``` diff --git a/docs/pt/docs/deployment.md b/docs/pt/docs/deployment.md index cd820cbd3c97b..2272467fdea0c 100644 --- a/docs/pt/docs/deployment.md +++ b/docs/pt/docs/deployment.md @@ -336,7 +336,7 @@ Você apenas precisa instalar um servidor ASGI compatível como:
```console - $ pip install uvicorn[standard] + $ pip install "uvicorn[standard]" ---> 100% ``` diff --git a/docs/pt/docs/index.md b/docs/pt/docs/index.md index b1d0c89f2a813..51af486b97307 100644 --- a/docs/pt/docs/index.md +++ b/docs/pt/docs/index.md @@ -124,7 +124,7 @@ Você também precisará de um servidor ASGI para produção, tal como ```console -$ pip install uvicorn[standard] +$ pip install "uvicorn[standard]" ---> 100% ``` diff --git a/docs/pt/docs/tutorial/index.md b/docs/pt/docs/tutorial/index.md index f93fd8d75c74e..b1abd32bc19ab 100644 --- a/docs/pt/docs/tutorial/index.md +++ b/docs/pt/docs/tutorial/index.md @@ -43,7 +43,7 @@ Para o tutorial, você deve querer instalá-lo com todas as dependências e recu
```console -$ pip install fastapi[all] +$ pip install "fastapi[all]" ---> 100% ``` @@ -64,7 +64,7 @@ $ pip install fastapi[all] Também instale o `uvicorn` para funcionar como servidor: ``` - pip install uvicorn[standard] + pip install "uvicorn[standard]" ``` E o mesmo para cada dependência opcional que você quiser usar. diff --git a/docs/ru/docs/index.md b/docs/ru/docs/index.md index 9a3957d5f6efa..932bb21390ac6 100644 --- a/docs/ru/docs/index.md +++ b/docs/ru/docs/index.md @@ -135,7 +135,7 @@ You will also need an ASGI server, for production such as ```console -$ pip install uvicorn[standard] +$ pip install "uvicorn[standard]" ---> 100% ``` diff --git a/docs/sq/docs/index.md b/docs/sq/docs/index.md index 29f92e020a7a8..2b64003fe8d15 100644 --- a/docs/sq/docs/index.md +++ b/docs/sq/docs/index.md @@ -135,7 +135,7 @@ You will also need an ASGI server, for production such as ```console -$ pip install uvicorn[standard] +$ pip install "uvicorn[standard]" ---> 100% ``` diff --git a/docs/tr/docs/index.md b/docs/tr/docs/index.md index 5693029b528a1..0d5337c87462d 100644 --- a/docs/tr/docs/index.md +++ b/docs/tr/docs/index.md @@ -143,7 +143,7 @@ Uygulamanı kullanılabilir hale getirmek için ```console -$ pip install uvicorn[standard] +$ pip install "uvicorn[standard]" ---> 100% ``` diff --git a/docs/uk/docs/index.md b/docs/uk/docs/index.md index 29f92e020a7a8..2b64003fe8d15 100644 --- a/docs/uk/docs/index.md +++ b/docs/uk/docs/index.md @@ -135,7 +135,7 @@ You will also need an ASGI server, for production such as ```console -$ pip install uvicorn[standard] +$ pip install "uvicorn[standard]" ---> 100% ``` diff --git a/docs/zh/docs/index.md b/docs/zh/docs/index.md index 797032c865f22..3898beaee0677 100644 --- a/docs/zh/docs/index.md +++ b/docs/zh/docs/index.md @@ -131,7 +131,7 @@ $ pip install fastapi
```console -$ pip install uvicorn[standard] +$ pip install "uvicorn[standard]" ---> 100% ``` diff --git a/docs/zh/docs/tutorial/index.md b/docs/zh/docs/tutorial/index.md index 36495ec0b8fb8..6093caeb601ca 100644 --- a/docs/zh/docs/tutorial/index.md +++ b/docs/zh/docs/tutorial/index.md @@ -43,7 +43,7 @@ $ uvicorn main:app --reload
```console -$ pip install fastapi[all] +$ pip install "fastapi[all]" ---> 100% ``` @@ -64,7 +64,7 @@ $ pip install fastapi[all] 并且安装`uvicorn`来作为服务器: ``` - pip install uvicorn[standard] + pip install "uvicorn[standard]" ``` 然后对你想使用的每个可选依赖项也执行相同的操作。 From ea017c99198c73f0e4a67a758bc5113e2cca6102 Mon Sep 17 00:00:00 2001 From: Teofilo Zosa Date: Fri, 19 Aug 2022 05:12:34 +0900 Subject: [PATCH 028/194] =?UTF-8?q?=F0=9F=93=9D=20Add=20misc=20dependency?= =?UTF-8?q?=20installs=20to=20tutorial=20docs=20(#2126)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs/en/docs/advanced/websockets.md | 14 ++++++++++++++ docs/en/docs/tutorial/response-model.md | 6 ++++++ docs/en/docs/tutorial/sql-databases.md | 14 ++++++++++++++ docs/en/docs/tutorial/testing.md | 5 +++++ 4 files changed, 39 insertions(+) diff --git a/docs/en/docs/advanced/websockets.md b/docs/en/docs/advanced/websockets.md index 878ad37ddc31b..0e9bc5b06b378 100644 --- a/docs/en/docs/advanced/websockets.md +++ b/docs/en/docs/advanced/websockets.md @@ -2,6 +2,20 @@ You can use WebSockets with **FastAPI**. +## Install `WebSockets` + +First you need to install `WebSockets`: + +
+ +```console +$ pip install websockets + +---> 100% +``` + +
+ ## WebSockets client ### In production diff --git a/docs/en/docs/tutorial/response-model.md b/docs/en/docs/tutorial/response-model.md index e371e86e4abbb..2bbd4d4fd5090 100644 --- a/docs/en/docs/tutorial/response-model.md +++ b/docs/en/docs/tutorial/response-model.md @@ -61,6 +61,12 @@ Here we are declaring a `UserIn` model, it will contain a plaintext password: {!> ../../../docs_src/response_model/tutorial002_py310.py!} ``` +!!! info + To use `EmailStr`, first install `email_validator`. + + E.g. `pip install email-validator` + or `pip install pydantic[email]`. + And we are using this model to declare our input and the same model to declare our output: === "Python 3.6 and above" diff --git a/docs/en/docs/tutorial/sql-databases.md b/docs/en/docs/tutorial/sql-databases.md index 3436543a5e4f7..5ccaf05ecec96 100644 --- a/docs/en/docs/tutorial/sql-databases.md +++ b/docs/en/docs/tutorial/sql-databases.md @@ -80,6 +80,20 @@ The file `__init__.py` is just an empty file, but it tells Python that `sql_app` Now let's see what each file/module does. +## Install `SQLAlchemy` + +First you need to install `SQLAlchemy`: + +
+ +```console +$ pip install sqlalchemy + +---> 100% +``` + +
+ ## Create the SQLAlchemy parts Let's refer to the file `sql_app/database.py`. diff --git a/docs/en/docs/tutorial/testing.md b/docs/en/docs/tutorial/testing.md index fea5a54f5c2de..79ea2b1ab58b8 100644 --- a/docs/en/docs/tutorial/testing.md +++ b/docs/en/docs/tutorial/testing.md @@ -8,6 +8,11 @@ With it, you can use `requests`. + + E.g. `pip install requests`. + Import `TestClient`. Create a `TestClient` by passing your **FastAPI** application to it. From 3a3b61dc6e26717f824ffa4c7ace999ad96c07f0 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 18 Aug 2022 20:13:14 +0000 Subject: [PATCH 029/194] =?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 0be6db642d4bc..b2e73d4a3a6f3 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 📝 Add misc dependency installs to tutorial docs. PR [#2126](https://github.com/tiangolo/fastapi/pull/2126) by [@TeoZosa](https://github.com/TeoZosa). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/query-params.md`. PR [#4775](https://github.com/tiangolo/fastapi/pull/4775) by [@batlopes](https://github.com/batlopes). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/security/first-steps.md`. PR [#4954](https://github.com/tiangolo/fastapi/pull/4954) by [@FLAIR7](https://github.com/FLAIR7). * 🌐 Add translation for `docs/zh/docs/advanced/response-cookies.md`. PR [#4638](https://github.com/tiangolo/fastapi/pull/4638) by [@zhangbo2012](https://github.com/zhangbo2012). From e88089ec210dadb06311377ab203eabfbda3d830 Mon Sep 17 00:00:00 2001 From: Luca Repetti <39653693+klaa97@users.noreply.github.com> Date: Thu, 18 Aug 2022 22:31:19 +0200 Subject: [PATCH 030/194] =?UTF-8?q?=F0=9F=90=9B=20Fix=20edge=20case=20with?= =?UTF-8?q?=20repeated=20aliases=20names=20not=20shown=20in=20OpenAPI=20(#?= =?UTF-8?q?2351)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- fastapi/openapi/utils.py | 4 +- tests/test_repeated_parameter_alias.py | 100 +++++++++++++++++++++++++ 2 files changed, 103 insertions(+), 1 deletion(-) create mode 100644 tests/test_repeated_parameter_alias.py diff --git a/fastapi/openapi/utils.py b/fastapi/openapi/utils.py index 5d3d95c2442cd..4d5741f30de1c 100644 --- a/fastapi/openapi/utils.py +++ b/fastapi/openapi/utils.py @@ -223,7 +223,9 @@ def get_openapi_path( parameters.extend(operation_parameters) if parameters: operation["parameters"] = list( - {param["name"]: param for param in parameters}.values() + { + (param["in"], param["name"]): param for param in parameters + }.values() ) if method in METHODS_WITH_BODY: request_body_oai = get_openapi_operation_request_body( diff --git a/tests/test_repeated_parameter_alias.py b/tests/test_repeated_parameter_alias.py new file mode 100644 index 0000000000000..823f53a95a2cf --- /dev/null +++ b/tests/test_repeated_parameter_alias.py @@ -0,0 +1,100 @@ +from fastapi import FastAPI, Path, Query, status +from fastapi.testclient import TestClient + +app = FastAPI() + + +@app.get("/{repeated_alias}") +def get_parameters_with_repeated_aliases( + path: str = Path(..., alias="repeated_alias"), + query: str = Query(..., alias="repeated_alias"), +): + return {"path": path, "query": query} + + +client = TestClient(app) + +openapi_schema = { + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": {"$ref": "#/components/schemas/ValidationError"}, + "title": "Detail", + "type": "array", + } + }, + "title": "HTTPValidationError", + "type": "object", + }, + "ValidationError": { + "properties": { + "loc": { + "items": {"anyOf": [{"type": "string"}, {"type": "integer"}]}, + "title": "Location", + "type": "array", + }, + "msg": {"title": "Message", "type": "string"}, + "type": {"title": "Error Type", "type": "string"}, + }, + "required": ["loc", "msg", "type"], + "title": "ValidationError", + "type": "object", + }, + } + }, + "info": {"title": "FastAPI", "version": "0.1.0"}, + "openapi": "3.0.2", + "paths": { + "/{repeated_alias}": { + "get": { + "operationId": "get_parameters_with_repeated_aliases__repeated_alias__get", + "parameters": [ + { + "in": "path", + "name": "repeated_alias", + "required": True, + "schema": {"title": "Repeated Alias", "type": "string"}, + }, + { + "in": "query", + "name": "repeated_alias", + "required": True, + "schema": {"title": "Repeated Alias", "type": "string"}, + }, + ], + "responses": { + "200": { + "content": {"application/json": {"schema": {}}}, + "description": "Successful Response", + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error", + }, + }, + "summary": "Get Parameters With Repeated Aliases", + } + } + }, +} + + +def test_openapi_schema(): + response = client.get("/openapi.json") + assert response.status_code == status.HTTP_200_OK + actual_schema = response.json() + assert actual_schema == openapi_schema + + +def test_get_parameters(): + response = client.get("/test_path", params={"repeated_alias": "test_query"}) + assert response.status_code == 200, response.text + assert response.json() == {"path": "test_path", "query": "test_query"} From 8a9a117ec7f58711dc68d6d6633dd02d4289cd1d Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 18 Aug 2022 20:31:57 +0000 Subject: [PATCH 031/194] =?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 b2e73d4a3a6f3..cbe368772ad5d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 🐛 Fix edge case with repeated aliases names not shown in OpenAPI. PR [#2351](https://github.com/tiangolo/fastapi/pull/2351) by [@klaa97](https://github.com/klaa97). * 📝 Add misc dependency installs to tutorial docs. PR [#2126](https://github.com/tiangolo/fastapi/pull/2126) by [@TeoZosa](https://github.com/TeoZosa). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/query-params.md`. PR [#4775](https://github.com/tiangolo/fastapi/pull/4775) by [@batlopes](https://github.com/batlopes). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/security/first-steps.md`. PR [#4954](https://github.com/tiangolo/fastapi/pull/4954) by [@FLAIR7](https://github.com/FLAIR7). From eb2e1833612e67c9b9ffd2bb446a672d3dffccf4 Mon Sep 17 00:00:00 2001 From: Xavi Moreno Date: Fri, 19 Aug 2022 06:48:21 +1000 Subject: [PATCH 032/194] =?UTF-8?q?=F0=9F=90=9B=20Fix=20`jsonable=5Fencode?= =?UTF-8?q?r`=20using=20`include`=20and=20`exclude`=20parameters=20for=20n?= =?UTF-8?q?on-Pydantic=20objects=20(#2606)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- fastapi/encoders.py | 9 ++++++++- tests/test_jsonable_encoder.py | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/fastapi/encoders.py b/fastapi/encoders.py index 4b7ffe313fa6b..b1fde73ceb7fc 100644 --- a/fastapi/encoders.py +++ b/fastapi/encoders.py @@ -80,6 +80,11 @@ def jsonable_encoder( return obj if isinstance(obj, dict): encoded_dict = {} + allowed_keys = set(obj.keys()) + if include is not None: + allowed_keys &= set(include) + if exclude is not None: + allowed_keys -= set(exclude) for key, value in obj.items(): if ( ( @@ -88,7 +93,7 @@ def jsonable_encoder( or (not key.startswith("_sa")) ) and (value is not None or not exclude_none) - and ((include and key in include) or not exclude or key not in exclude) + and key in allowed_keys ): encoded_key = jsonable_encoder( key, @@ -144,6 +149,8 @@ def jsonable_encoder( raise ValueError(errors) return jsonable_encoder( data, + include=include, + exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, diff --git a/tests/test_jsonable_encoder.py b/tests/test_jsonable_encoder.py index ed35fd32e43f0..5e55f2f918467 100644 --- a/tests/test_jsonable_encoder.py +++ b/tests/test_jsonable_encoder.py @@ -93,16 +93,42 @@ class Config: return ModelWithPath(path=request.param("/foo", "bar")) +def test_encode_dict(): + pet = {"name": "Firulais", "owner": {"name": "Foo"}} + assert jsonable_encoder(pet) == {"name": "Firulais", "owner": {"name": "Foo"}} + assert jsonable_encoder(pet, include={"name"}) == {"name": "Firulais"} + assert jsonable_encoder(pet, exclude={"owner"}) == {"name": "Firulais"} + assert jsonable_encoder(pet, include={}) == {} + assert jsonable_encoder(pet, exclude={}) == { + "name": "Firulais", + "owner": {"name": "Foo"}, + } + + def test_encode_class(): person = Person(name="Foo") pet = Pet(owner=person, name="Firulais") assert jsonable_encoder(pet) == {"name": "Firulais", "owner": {"name": "Foo"}} + assert jsonable_encoder(pet, include={"name"}) == {"name": "Firulais"} + assert jsonable_encoder(pet, exclude={"owner"}) == {"name": "Firulais"} + assert jsonable_encoder(pet, include={}) == {} + assert jsonable_encoder(pet, exclude={}) == { + "name": "Firulais", + "owner": {"name": "Foo"}, + } def test_encode_dictable(): person = DictablePerson(name="Foo") pet = DictablePet(owner=person, name="Firulais") assert jsonable_encoder(pet) == {"name": "Firulais", "owner": {"name": "Foo"}} + assert jsonable_encoder(pet, include={"name"}) == {"name": "Firulais"} + assert jsonable_encoder(pet, exclude={"owner"}) == {"name": "Firulais"} + assert jsonable_encoder(pet, include={}) == {} + assert jsonable_encoder(pet, exclude={}) == { + "name": "Firulais", + "owner": {"name": "Foo"}, + } def test_encode_unsupported(): @@ -144,6 +170,14 @@ def test_encode_model_with_default(): assert jsonable_encoder(model, exclude_unset=True, exclude_defaults=True) == { "foo": "foo" } + assert jsonable_encoder(model, include={"foo"}) == {"foo": "foo"} + assert jsonable_encoder(model, exclude={"bla"}) == {"foo": "foo", "bar": "bar"} + assert jsonable_encoder(model, include={}) == {} + assert jsonable_encoder(model, exclude={}) == { + "foo": "foo", + "bar": "bar", + "bla": "bla", + } def test_custom_encoders(): From 74638fcf7cbdc836d46cfee398b781276860cd7b Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 18 Aug 2022 20:49:01 +0000 Subject: [PATCH 033/194] =?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 cbe368772ad5d..855bd7ec68ce0 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 🐛 Fix `jsonable_encoder` using `include` and `exclude` parameters for non-Pydantic objects. PR [#2606](https://github.com/tiangolo/fastapi/pull/2606) by [@xaviml](https://github.com/xaviml). * 🐛 Fix edge case with repeated aliases names not shown in OpenAPI. PR [#2351](https://github.com/tiangolo/fastapi/pull/2351) by [@klaa97](https://github.com/klaa97). * 📝 Add misc dependency installs to tutorial docs. PR [#2126](https://github.com/tiangolo/fastapi/pull/2126) by [@TeoZosa](https://github.com/TeoZosa). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/query-params.md`. PR [#4775](https://github.com/tiangolo/fastapi/pull/4775) by [@batlopes](https://github.com/batlopes). From 2f9c6ab36abff2f7c80b7c33cab92171c66a3cf9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Thu, 18 Aug 2022 22:57:02 +0200 Subject: [PATCH 034/194] =?UTF-8?q?=F0=9F=94=A7=20Update=20Jina=20sponsors?= =?UTF-8?q?hip=20(#5283)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- docs/en/data/sponsors.yml | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index a5e8cae22a3e7..326ad22795343 100644 --- a/README.md +++ b/README.md @@ -48,10 +48,10 @@ The key features are: + - diff --git a/docs/en/data/sponsors.yml b/docs/en/data/sponsors.yml index 7fbb933e030a3..af1f97818abb0 100644 --- a/docs/en/data/sponsors.yml +++ b/docs/en/data/sponsors.yml @@ -2,6 +2,9 @@ gold: - url: https://bit.ly/3dmXC5S title: The data structure for unstructured multimodal data img: https://fastapi.tiangolo.com/img/sponsors/docarray.svg + - url: https://bit.ly/3JJ7y5C + title: Build cross-modal and multimodal applications on the cloud + img: https://fastapi.tiangolo.com/img/sponsors/jina2.svg - url: https://cryptapi.io/ title: "CryptAPI: Your easy to use, secure and privacy oriented payment gateway." img: https://fastapi.tiangolo.com/img/sponsors/cryptapi.svg @@ -11,9 +14,6 @@ gold: - url: https://doist.com/careers/9B437B1615-wa-senior-backend-engineer-python title: Help us migrate doist to FastAPI img: https://fastapi.tiangolo.com/img/sponsors/doist.svg - - url: https://bit.ly/3JJ7y5C - title: Build cross-modal and multimodal applications on the cloud - img: https://fastapi.tiangolo.com/img/sponsors/jina2.svg silver: - url: https://www.deta.sh/?ref=fastapi title: The launchpad for all your (team's) ideas From 94bbb91ec2912dfbcababc77386abee6e3c02c1d Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 18 Aug 2022 20:57:50 +0000 Subject: [PATCH 035/194] =?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 855bd7ec68ce0..fe3aebbfc8653 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 🔧 Update Jina sponsorship. PR [#5283](https://github.com/tiangolo/fastapi/pull/5283) by [@tiangolo](https://github.com/tiangolo). * 🐛 Fix `jsonable_encoder` using `include` and `exclude` parameters for non-Pydantic objects. PR [#2606](https://github.com/tiangolo/fastapi/pull/2606) by [@xaviml](https://github.com/xaviml). * 🐛 Fix edge case with repeated aliases names not shown in OpenAPI. PR [#2351](https://github.com/tiangolo/fastapi/pull/2351) by [@klaa97](https://github.com/klaa97). * 📝 Add misc dependency installs to tutorial docs. PR [#2126](https://github.com/tiangolo/fastapi/pull/2126) by [@TeoZosa](https://github.com/TeoZosa). From 7f0e2f6cfa44d6710725a7950e8acd3235ad64af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Thu, 18 Aug 2022 23:04:30 +0200 Subject: [PATCH 036/194] =?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 | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index fe3aebbfc8653..1d267a97eaaf2 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,27 +2,38 @@ ## Latest Changes -* 🔧 Update Jina sponsorship. PR [#5283](https://github.com/tiangolo/fastapi/pull/5283) by [@tiangolo](https://github.com/tiangolo). +### Fixes + * 🐛 Fix `jsonable_encoder` using `include` and `exclude` parameters for non-Pydantic objects. PR [#2606](https://github.com/tiangolo/fastapi/pull/2606) by [@xaviml](https://github.com/xaviml). * 🐛 Fix edge case with repeated aliases names not shown in OpenAPI. PR [#2351](https://github.com/tiangolo/fastapi/pull/2351) by [@klaa97](https://github.com/klaa97). * 📝 Add misc dependency installs to tutorial docs. PR [#2126](https://github.com/tiangolo/fastapi/pull/2126) by [@TeoZosa](https://github.com/TeoZosa). + +### Docs + +* ✏ Fix typo in `python-types.md`. PR [#5116](https://github.com/tiangolo/fastapi/pull/5116) by [@Kludex](https://github.com/Kludex). +* ✏ Fix typo in `docs/en/docs/python-types.md`. PR [#5007](https://github.com/tiangolo/fastapi/pull/5007) by [@atiabbz](https://github.com/atiabbz). +* 📝 Remove unneeded Django/Flask references from async topic intro. PR [#5280](https://github.com/tiangolo/fastapi/pull/5280) by [@carltongibson](https://github.com/carltongibson). +* ✨ Add illustrations for Concurrent burgers and Parallel burgers. PR [#5277](https://github.com/tiangolo/fastapi/pull/5277) by [@tiangolo](https://github.com/tiangolo). Updated docs at: [Concurrency and Burgers](https://fastapi.tiangolo.com/async/#concurrency-and-burgers). + +### Translations + * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/query-params.md`. PR [#4775](https://github.com/tiangolo/fastapi/pull/4775) by [@batlopes](https://github.com/batlopes). * 🌐 Add Portuguese translation for `docs/pt/docs/tutorial/security/first-steps.md`. PR [#4954](https://github.com/tiangolo/fastapi/pull/4954) by [@FLAIR7](https://github.com/FLAIR7). * 🌐 Add translation for `docs/zh/docs/advanced/response-cookies.md`. PR [#4638](https://github.com/tiangolo/fastapi/pull/4638) by [@zhangbo2012](https://github.com/zhangbo2012). -* ✏ Fix typo in `python-types.md`. PR [#5116](https://github.com/tiangolo/fastapi/pull/5116) by [@Kludex](https://github.com/Kludex). * 🌐 Add French translation for `docs/fr/docs/deployment/index.md`. PR [#3689](https://github.com/tiangolo/fastapi/pull/3689) by [@rjNemo](https://github.com/rjNemo). * 🌐 Add Portuguese translation for `tutorial/handling-errors.md`. PR [#4769](https://github.com/tiangolo/fastapi/pull/4769) by [@frnsimoes](https://github.com/frnsimoes). * 🌐 Add French translation for `docs/fr/docs/history-design-future.md`. PR [#3451](https://github.com/tiangolo/fastapi/pull/3451) by [@rjNemo](https://github.com/rjNemo). -* ✏ Fix typo in `docs/en/docs/python-types.md`. PR [#5007](https://github.com/tiangolo/fastapi/pull/5007) by [@atiabbz](https://github.com/atiabbz). * 🌐 Add Russian translation for `docs/ru/docs/tutorial/background-tasks.md`. PR [#4854](https://github.com/tiangolo/fastapi/pull/4854) by [@AdmiralDesu](https://github.com/AdmiralDesu). * 🌐 Add Chinese translation for `docs/tutorial/security/first-steps.md`. PR [#3841](https://github.com/tiangolo/fastapi/pull/3841) by [@jaystone776](https://github.com/jaystone776). * 🌐 Add Japanese translation for `docs/ja/docs/advanced/nosql-databases.md`. PR [#4205](https://github.com/tiangolo/fastapi/pull/4205) by [@sUeharaE4](https://github.com/sUeharaE4). * 🌐 Add Indonesian translation for `docs/id/docs/tutorial/index.md`. PR [#4705](https://github.com/tiangolo/fastapi/pull/4705) by [@bas-baskara](https://github.com/bas-baskara). -* 📝 Remove unneeded Django/Flask references from async topic intro. PR [#5280](https://github.com/tiangolo/fastapi/pull/5280) by [@carltongibson](https://github.com/carltongibson). -* ✨ Add illustrations for Concurrent burgers and Parallel burgers. PR [#5277](https://github.com/tiangolo/fastapi/pull/5277) by [@tiangolo](https://github.com/tiangolo). +* 🌐 Add Persian translation for `docs/fa/docs/index.md` and tweak right-to-left CSS. PR [#2395](https://github.com/tiangolo/fastapi/pull/2395) by [@mohsen-mahmoodi](https://github.com/mohsen-mahmoodi). + +### Internal + +* 🔧 Update Jina sponsorship. PR [#5283](https://github.com/tiangolo/fastapi/pull/5283) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update Jina sponsorship. PR [#5272](https://github.com/tiangolo/fastapi/pull/5272) by [@tiangolo](https://github.com/tiangolo). * 🔧 Update sponsors, Striveworks badge. PR [#5179](https://github.com/tiangolo/fastapi/pull/5179) by [@tiangolo](https://github.com/tiangolo). -* 🌐 Add Persian translation for `docs/fa/docs/index.md` and tweak right-to-left CSS. PR [#2395](https://github.com/tiangolo/fastapi/pull/2395) by [@mohsen-mahmoodi](https://github.com/mohsen-mahmoodi). ## 0.79.0 From a21c31557464b477ea284f9bad635b5cbef19425 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Thu, 18 Aug 2022 23:11:39 +0200 Subject: [PATCH 037/194] =?UTF-8?q?=F0=9F=93=9D=20Add=20note=20giving=20cr?= =?UTF-8?q?edit=20for=20illustrations=20to=20Ketrina=20Thompson=20(#5284)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/async.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/en/docs/async.md b/docs/en/docs/async.md index 95d2f755a6d43..dc8e10bb840d1 100644 --- a/docs/en/docs/async.md +++ b/docs/en/docs/async.md @@ -136,6 +136,9 @@ You and your crush eat the burgers and have a nice time. ✨ +!!! info + Beautiful illustrations by Ketrina Thompson. 🎨 + --- Imagine you are the computer / program 🤖 in that story. @@ -196,6 +199,9 @@ You just eat them, and you are done. ⏹ There was not much talk or flirting as most of the time was spent waiting 🕙 in front of the counter. 😞 +!!! info + Beautiful illustrations by Ketrina Thompson. 🎨 + --- In this scenario of the parallel burgers, you are a computer / program 🤖 with two processors (you and your crush), both waiting 🕙 and dedicating their attention ⏯ to be "waiting on the counter" 🕙 for a long time. From 767df02814735b43898c05de016c976a144b38c5 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 18 Aug 2022 21:12:18 +0000 Subject: [PATCH 038/194] =?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 1d267a97eaaf2..01e01d5863467 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 📝 Add note giving credit for illustrations to Ketrina Thompson. PR [#5284](https://github.com/tiangolo/fastapi/pull/5284) by [@tiangolo](https://github.com/tiangolo). ### Fixes * 🐛 Fix `jsonable_encoder` using `include` and `exclude` parameters for non-Pydantic objects. PR [#2606](https://github.com/tiangolo/fastapi/pull/2606) by [@xaviml](https://github.com/xaviml). From 09381ba04256adbd86e440715dc80e79d90fe840 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Thu, 18 Aug 2022 23:13:19 +0200 Subject: [PATCH 039/194] =?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 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 01e01d5863467..54a4297d7ca20 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,7 +2,6 @@ ## Latest Changes -* 📝 Add note giving credit for illustrations to Ketrina Thompson. PR [#5284](https://github.com/tiangolo/fastapi/pull/5284) by [@tiangolo](https://github.com/tiangolo). ### Fixes * 🐛 Fix `jsonable_encoder` using `include` and `exclude` parameters for non-Pydantic objects. PR [#2606](https://github.com/tiangolo/fastapi/pull/2606) by [@xaviml](https://github.com/xaviml). @@ -11,6 +10,7 @@ ### Docs +* 📝 Add note giving credit for illustrations to [Ketrina Thompson](https://www.instagram.com/ketrinadrawsalot/). PR [#5284](https://github.com/tiangolo/fastapi/pull/5284) by [@tiangolo](https://github.com/tiangolo). * ✏ Fix typo in `python-types.md`. PR [#5116](https://github.com/tiangolo/fastapi/pull/5116) by [@Kludex](https://github.com/Kludex). * ✏ Fix typo in `docs/en/docs/python-types.md`. PR [#5007](https://github.com/tiangolo/fastapi/pull/5007) by [@atiabbz](https://github.com/atiabbz). * 📝 Remove unneeded Django/Flask references from async topic intro. PR [#5280](https://github.com/tiangolo/fastapi/pull/5280) by [@carltongibson](https://github.com/carltongibson). From ab8988ff7c5bb2ec25d41ba8c8687114962e0986 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Thu, 18 Aug 2022 23:14:07 +0200 Subject: [PATCH 040/194] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.79?= =?UTF-8?q?.1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 3 +++ fastapi/__init__.py | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 54a4297d7ca20..4b4ebee42bb08 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,9 @@ ## Latest Changes + +## 0.79.1 + ### Fixes * 🐛 Fix `jsonable_encoder` using `include` and `exclude` parameters for non-Pydantic objects. PR [#2606](https://github.com/tiangolo/fastapi/pull/2606) by [@xaviml](https://github.com/xaviml). diff --git a/fastapi/__init__.py b/fastapi/__init__.py index e5cdbeb09d4b8..abcb219a99420 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.79.0" +__version__ = "0.79.1" from starlette import status as status From eb80b79555d98bfbabe812676fae8296130874fd Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 22 Aug 2022 12:44:46 +0000 Subject: [PATCH 041/194] =?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 4b4ebee42bb08..8e1db01d354d6 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* Translated docs to ru `project_generator.md`, `features.md`, `help-fastapi.md`, upgrade `python-types.md`, `docs/ru/mkdocs.yml`.. PR [#4913](https://github.com/tiangolo/fastapi/pull/4913) by [@Xewus](https://github.com/Xewus). ## 0.79.1 From 6c16d6a4f9776fd61fbfe39d7365c611061c7213 Mon Sep 17 00:00:00 2001 From: Joona Yoon Date: Mon, 22 Aug 2022 23:52:50 +0900 Subject: [PATCH 042/194] =?UTF-8?q?=F0=9F=8C=90=20Add=20missing=20navigato?= =?UTF-8?q?r=20for=20`encoder.md`=20in=20Korean=20translation=20(#5238)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ko/mkdocs.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/ko/mkdocs.yml b/docs/ko/mkdocs.yml index 70cb419ba1d22..50931e134cf06 100644 --- a/docs/ko/mkdocs.yml +++ b/docs/ko/mkdocs.yml @@ -68,6 +68,7 @@ nav: - tutorial/response-status-code.md - tutorial/request-files.md - tutorial/request-forms-and-files.md + - tutorial/encoder.md markdown_extensions: - toc: permalink: true From 7953353a356bda1112fd60794365a32f72e9d4e3 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 22 Aug 2022 14:53:35 +0000 Subject: [PATCH 043/194] =?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 8e1db01d354d6..8ff0d33753780 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 🌐 Add missing navigator for `encoder.md` in Korean translation. PR [#5238](https://github.com/tiangolo/fastapi/pull/5238) by [@joonas-yoon](https://github.com/joonas-yoon). * Translated docs to ru `project_generator.md`, `features.md`, `help-fastapi.md`, upgrade `python-types.md`, `docs/ru/mkdocs.yml`.. PR [#4913](https://github.com/tiangolo/fastapi/pull/4913) by [@Xewus](https://github.com/Xewus). ## 0.79.1 From 1ff8df6e7fd5c80193c5f7344b6c82c7fc951911 Mon Sep 17 00:00:00 2001 From: 0xflotus <0xflotus@gmail.com> Date: Mon, 22 Aug 2022 20:33:10 +0200 Subject: [PATCH 044/194] =?UTF-8?q?=F0=9F=8C=90=20Fix=20typos=20in=20Germa?= =?UTF-8?q?n=20translation=20for=20`docs/de/docs/features.md`=20(#4533)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs/de/docs/features.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/de/docs/features.md b/docs/de/docs/features.md index d99ade4024bd0..f825472a9a940 100644 --- a/docs/de/docs/features.md +++ b/docs/de/docs/features.md @@ -97,7 +97,7 @@ Hierdurch werden Sie nie wieder einen falschen Schlüsselnamen benutzen und spar ### Kompakt -FastAPI nutzt für alles sinnvolle **Standard-Einstellungen**, welche optional überall konfiguriert werden können. Alle Parameter können ganz genau an Ihre Bedürfnisse angepasst werden, sodass sie genau die API definieren können, die sie brauchen. +FastAPI nutzt für alles sensible **Standard-Einstellungen**, welche optional überall konfiguriert werden können. Alle Parameter können ganz genau an Ihre Bedürfnisse angepasst werden, sodass sie genau die API definieren können, die sie brauchen. Aber standardmäßig, **"funktioniert einfach"** alles. @@ -119,9 +119,9 @@ Die gesamte Validierung übernimmt das etablierte und robuste **Pydantic**. ### Sicherheit und Authentifizierung -Sicherheit und Authentifizierung integriert. Ohne einen Kompromiss aufgrund einer Datenbank oder den Datenentitäten. +Integrierte Sicherheit und Authentifizierung. Ohne Kompromisse bei Datenbanken oder Datenmodellen. -Unterstützt alle von OpenAPI definierten Sicherheitsschemata, hierzu gehören: +Unterstützt werden alle von OpenAPI definierten Sicherheitsschemata, hierzu gehören: * HTTP Basis Authentifizierung. * **OAuth2** (auch mit **JWT Zugriffstokens**). Schauen Sie sich hierzu dieses Tutorial an: [OAuth2 mit JWT](tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. @@ -142,8 +142,8 @@ FastAPI enthält ein extrem einfaches, aber extrem mächtiges eines der schnellsten Python frameworks, auf Augenhöhe mit **NodeJS** und **Go**. +* Stark beeindruckende Performanz. Es ist eines der schnellsten Python Frameworks, auf Augenhöhe mit **NodeJS** und **Go**. * **WebSocket**-Unterstützung. * Hintergrundaufgaben im selben Prozess. * Ereignisse für das Starten und Herunterfahren. @@ -196,8 +196,8 @@ Mit **FastAPI** bekommen Sie alle Funktionen von **Pydantic** (da FastAPI für d * In Vergleichen ist Pydantic schneller als jede andere getestete Bibliothek. * Validierung von **komplexen Strukturen**: * Benutzung von hierachischen Pydantic Schemata, Python `typing`’s `List` und `Dict`, etc. - * Validierungen erlauben klare und einfache Datenschemadefinition, überprüft und dokumentiert als JSON Schema. + * Validierungen erlauben eine klare und einfache Datenschemadefinition, überprüft und dokumentiert als JSON Schema. * Sie können stark **verschachtelte JSON** Objekte haben und diese sind trotzdem validiert und annotiert. * **Erweiterbar**: - * Pydantic erlaubt die Definition von eigenen Datentypen oder Sie können die Validierung mit einer `validator` dekorierten Methode erweitern.. + * Pydantic erlaubt die Definition von eigenen Datentypen oder sie können die Validierung mit einer `validator` dekorierten Methode erweitern. * 100% Testabdeckung. From a6a39f300989f58062141d58c2581c55b0f0f9c3 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 22 Aug 2022 18:35:01 +0000 Subject: [PATCH 045/194] =?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 8ff0d33753780..f57512cc1c8bb 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 🌐 Fix typos in German translation for `docs/de/docs/features.md`. PR [#4533](https://github.com/tiangolo/fastapi/pull/4533) by [@0xflotus](https://github.com/0xflotus). * 🌐 Add missing navigator for `encoder.md` in Korean translation. PR [#5238](https://github.com/tiangolo/fastapi/pull/5238) by [@joonas-yoon](https://github.com/joonas-yoon). * Translated docs to ru `project_generator.md`, `features.md`, `help-fastapi.md`, upgrade `python-types.md`, `docs/ru/mkdocs.yml`.. PR [#4913](https://github.com/tiangolo/fastapi/pull/4913) by [@Xewus](https://github.com/Xewus). From e7b1b96a54af8e6327be1e0cc2172c81d052edda Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Mon, 22 Aug 2022 20:49:03 +0200 Subject: [PATCH 046/194] =?UTF-8?q?=F0=9F=8E=A8=20Update=20type=20annotati?= =?UTF-8?q?ons=20for=20`response=5Fmodel`,=20allow=20things=20like=20`Unio?= =?UTF-8?q?n[str,=20None]`=20(#5294)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/applications.py | 20 ++++++++++---------- fastapi/routing.py | 22 +++++++++++----------- 2 files changed, 21 insertions(+), 21 deletions(-) diff --git a/fastapi/applications.py b/fastapi/applications.py index 7530ddb9b8fef..ac6050ca4ff56 100644 --- a/fastapi/applications.py +++ b/fastapi/applications.py @@ -273,7 +273,7 @@ def add_api_route( path: str, endpoint: Callable[..., Coroutine[Any, Any, Response]], *, - response_model: Optional[Type[Any]] = None, + response_model: Any = None, status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[Depends]] = None, @@ -331,7 +331,7 @@ def api_route( self, path: str, *, - response_model: Optional[Type[Any]] = None, + response_model: Any = None, status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[Depends]] = None, @@ -434,7 +434,7 @@ def get( self, path: str, *, - response_model: Optional[Type[Any]] = None, + response_model: Any = None, status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[Depends]] = None, @@ -489,7 +489,7 @@ def put( self, path: str, *, - response_model: Optional[Type[Any]] = None, + response_model: Any = None, status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[Depends]] = None, @@ -544,7 +544,7 @@ def post( self, path: str, *, - response_model: Optional[Type[Any]] = None, + response_model: Any = None, status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[Depends]] = None, @@ -599,7 +599,7 @@ def delete( self, path: str, *, - response_model: Optional[Type[Any]] = None, + response_model: Any = None, status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[Depends]] = None, @@ -654,7 +654,7 @@ def options( self, path: str, *, - response_model: Optional[Type[Any]] = None, + response_model: Any = None, status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[Depends]] = None, @@ -709,7 +709,7 @@ def head( self, path: str, *, - response_model: Optional[Type[Any]] = None, + response_model: Any = None, status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[Depends]] = None, @@ -764,7 +764,7 @@ def patch( self, path: str, *, - response_model: Optional[Type[Any]] = None, + response_model: Any = None, status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[Depends]] = None, @@ -819,7 +819,7 @@ def trace( self, path: str, *, - response_model: Optional[Type[Any]] = None, + response_model: Any = None, status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[Depends]] = None, diff --git a/fastapi/routing.py b/fastapi/routing.py index 6f1a8e9000dd6..2e0d2e552aaf0 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -315,7 +315,7 @@ def __init__( path: str, endpoint: Callable[..., Any], *, - response_model: Optional[Type[Any]] = None, + response_model: Any = None, status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, @@ -511,7 +511,7 @@ def add_api_route( path: str, endpoint: Callable[..., Any], *, - response_model: Optional[Type[Any]] = None, + response_model: Any = None, status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, @@ -592,7 +592,7 @@ def api_route( self, path: str, *, - response_model: Optional[Type[Any]] = None, + response_model: Any = None, status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, @@ -787,7 +787,7 @@ def get( self, path: str, *, - response_model: Optional[Type[Any]] = None, + response_model: Any = None, status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, @@ -843,7 +843,7 @@ def put( self, path: str, *, - response_model: Optional[Type[Any]] = None, + response_model: Any = None, status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, @@ -899,7 +899,7 @@ def post( self, path: str, *, - response_model: Optional[Type[Any]] = None, + response_model: Any = None, status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, @@ -955,7 +955,7 @@ def delete( self, path: str, *, - response_model: Optional[Type[Any]] = None, + response_model: Any = None, status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, @@ -1011,7 +1011,7 @@ def options( self, path: str, *, - response_model: Optional[Type[Any]] = None, + response_model: Any = None, status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, @@ -1067,7 +1067,7 @@ def head( self, path: str, *, - response_model: Optional[Type[Any]] = None, + response_model: Any = None, status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, @@ -1123,7 +1123,7 @@ def patch( self, path: str, *, - response_model: Optional[Type[Any]] = None, + response_model: Any = None, status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, @@ -1179,7 +1179,7 @@ def trace( self, path: str, *, - response_model: Optional[Type[Any]] = None, + response_model: Any = None, status_code: Optional[int] = None, tags: Optional[List[Union[str, Enum]]] = None, dependencies: Optional[Sequence[params.Depends]] = None, From 12f60cac7a2262231374404c538f0b227f9b9496 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 22 Aug 2022 18:49:42 +0000 Subject: [PATCH 047/194] =?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 f57512cc1c8bb..f5ccf9b26bd0c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 🎨 Update type annotations for `response_model`, allow things like `Union[str, None]`. PR [#5294](https://github.com/tiangolo/fastapi/pull/5294) by [@tiangolo](https://github.com/tiangolo). * 🌐 Fix typos in German translation for `docs/de/docs/features.md`. PR [#4533](https://github.com/tiangolo/fastapi/pull/4533) by [@0xflotus](https://github.com/0xflotus). * 🌐 Add missing navigator for `encoder.md` in Korean translation. PR [#5238](https://github.com/tiangolo/fastapi/pull/5238) by [@joonas-yoon](https://github.com/joonas-yoon). * Translated docs to ru `project_generator.md`, `features.md`, `help-fastapi.md`, upgrade `python-types.md`, `docs/ru/mkdocs.yml`.. PR [#4913](https://github.com/tiangolo/fastapi/pull/4913) by [@Xewus](https://github.com/Xewus). From 634cf22584fc4fd9ee53cfdf0ad6d48a2830ac34 Mon Sep 17 00:00:00 2001 From: Taneli Hukkinen <3275109+hukkin@users.noreply.github.com> Date: Mon, 22 Aug 2022 22:17:45 +0300 Subject: [PATCH 048/194] =?UTF-8?q?=F0=9F=90=9B=20Fix=20`response=5Fmodel`?= =?UTF-8?q?=20not=20invalidating=20`None`=20(#2725)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Taneli Hukkinen Co-authored-by: Sebastián Ramírez --- fastapi/utils.py | 2 +- tests/test_validate_response.py | 34 ++++++++++++++++++++++++++++++++- 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/fastapi/utils.py b/fastapi/utils.py index 887d57c90258a..40750a5b35269 100644 --- a/fastapi/utils.py +++ b/fastapi/utils.py @@ -50,7 +50,7 @@ def create_response_field( type_: Type[Any], class_validators: Optional[Dict[str, Validator]] = None, default: Optional[Any] = None, - required: Union[bool, UndefinedType] = False, + required: Union[bool, UndefinedType] = True, model_config: Type[BaseConfig] = BaseConfig, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, diff --git a/tests/test_validate_response.py b/tests/test_validate_response.py index 45d303e20e8bb..62f51c960ded3 100644 --- a/tests/test_validate_response.py +++ b/tests/test_validate_response.py @@ -1,4 +1,4 @@ -from typing import List, Optional +from typing import List, Optional, Union import pytest from fastapi import FastAPI @@ -19,6 +19,19 @@ def get_invalid(): return {"name": "invalid", "price": "foo"} +@app.get("/items/invalidnone", response_model=Item) +def get_invalid_none(): + return None + + +@app.get("/items/validnone", response_model=Union[Item, None]) +def get_valid_none(send_none: bool = False): + if send_none: + return None + else: + return {"name": "invalid", "price": 3.2} + + @app.get("/items/innerinvalid", response_model=Item) def get_innerinvalid(): return {"name": "double invalid", "price": "foo", "owner_ids": ["foo", "bar"]} @@ -41,6 +54,25 @@ def test_invalid(): client.get("/items/invalid") +def test_invalid_none(): + with pytest.raises(ValidationError): + client.get("/items/invalidnone") + + +def test_valid_none_data(): + response = client.get("/items/validnone") + data = response.json() + assert response.status_code == 200 + assert data == {"name": "invalid", "price": 3.2, "owner_ids": None} + + +def test_valid_none_none(): + response = client.get("/items/validnone", params={"send_none": "true"}) + data = response.json() + assert response.status_code == 200 + assert data is None + + def test_double_invalid(): with pytest.raises(ValidationError): client.get("/items/innerinvalid") From 982911f08f11ceb10ad8bba34ec22095d6018856 Mon Sep 17 00:00:00 2001 From: github-actions Date: Mon, 22 Aug 2022 19:18:24 +0000 Subject: [PATCH 049/194] =?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 f5ccf9b26bd0c..0cab8220aaa8c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 🐛 Fix `response_model` not invalidating `None`. PR [#2725](https://github.com/tiangolo/fastapi/pull/2725) by [@hukkin](https://github.com/hukkin). * 🎨 Update type annotations for `response_model`, allow things like `Union[str, None]`. PR [#5294](https://github.com/tiangolo/fastapi/pull/5294) by [@tiangolo](https://github.com/tiangolo). * 🌐 Fix typos in German translation for `docs/de/docs/features.md`. PR [#4533](https://github.com/tiangolo/fastapi/pull/4533) by [@0xflotus](https://github.com/0xflotus). * 🌐 Add missing navigator for `encoder.md` in Korean translation. PR [#5238](https://github.com/tiangolo/fastapi/pull/5238) by [@joonas-yoon](https://github.com/joonas-yoon). From b993b4af287e63904b675ba2ee1c232e86f2b072 Mon Sep 17 00:00:00 2001 From: laggardkernel Date: Tue, 23 Aug 2022 21:30:24 +0800 Subject: [PATCH 050/194] =?UTF-8?q?=F0=9F=90=9B=20Fix=20cached=20dependenc?= =?UTF-8?q?ies=20when=20using=20a=20dependency=20in=20`Security()`=20and?= =?UTF-8?q?=20other=20places=20(e.g.=20`Depends()`)=20with=20different=20O?= =?UTF-8?q?Auth2=20scopes=20(#2945)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- fastapi/dependencies/utils.py | 10 +++++++--- tests/test_dependency_cache.py | 25 ++++++++++++++++++++++++- 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index f397e333c0928..f6151f6bd8a6a 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -161,7 +161,6 @@ def get_sub_dependant( ) if security_requirement: sub_dependant.security_requirements.append(security_requirement) - sub_dependant.security_scopes = security_scopes return sub_dependant @@ -278,7 +277,13 @@ def get_dependant( path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters - dependant = Dependant(call=call, name=name, path=path, use_cache=use_cache) + dependant = Dependant( + call=call, + name=name, + path=path, + security_scopes=security_scopes, + use_cache=use_cache, + ) for param_name, param in signature_params.items(): if isinstance(param.default, params.Depends): sub_dependant = get_param_sub_dependant( @@ -495,7 +500,6 @@ async def solve_dependencies( name=sub_dependant.name, security_scopes=sub_dependant.security_scopes, ) - use_sub_dependant.security_scopes = sub_dependant.security_scopes solved_result = await solve_dependencies( request=request, diff --git a/tests/test_dependency_cache.py b/tests/test_dependency_cache.py index 65ed7f946459e..08fb9b74f48de 100644 --- a/tests/test_dependency_cache.py +++ b/tests/test_dependency_cache.py @@ -1,4 +1,4 @@ -from fastapi import Depends, FastAPI +from fastapi import Depends, FastAPI, Security from fastapi.testclient import TestClient app = FastAPI() @@ -35,6 +35,19 @@ async def get_sub_counter_no_cache( return {"counter": count, "subcounter": subcount} +@app.get("/scope-counter") +async def get_scope_counter( + count: int = Security(dep_counter), + scope_count_1: int = Security(dep_counter, scopes=["scope"]), + scope_count_2: int = Security(dep_counter, scopes=["scope"]), +): + return { + "counter": count, + "scope_counter_1": scope_count_1, + "scope_counter_2": scope_count_2, + } + + client = TestClient(app) @@ -66,3 +79,13 @@ def test_sub_counter_no_cache(): response = client.get("/sub-counter-no-cache/") assert response.status_code == 200, response.text assert response.json() == {"counter": 4, "subcounter": 3} + + +def test_security_cache(): + counter_holder["counter"] = 0 + response = client.get("/scope-counter/") + assert response.status_code == 200, response.text + assert response.json() == {"counter": 1, "scope_counter_1": 2, "scope_counter_2": 2} + response = client.get("/scope-counter/") + assert response.status_code == 200, response.text + assert response.json() == {"counter": 3, "scope_counter_1": 4, "scope_counter_2": 4} From f8f5281ef5efa25e780fec97701ed35eec3bcc71 Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 23 Aug 2022 13:31:17 +0000 Subject: [PATCH 051/194] =?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 0cab8220aaa8c..f2c455e2fd924 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 🐛 Fix cached dependencies when using a dependency in `Security()` and other places (e.g. `Depends()`) with different OAuth2 scopes. PR [#2945](https://github.com/tiangolo/fastapi/pull/2945) by [@laggardkernel](https://github.com/laggardkernel). * 🐛 Fix `response_model` not invalidating `None`. PR [#2725](https://github.com/tiangolo/fastapi/pull/2725) by [@hukkin](https://github.com/hukkin). * 🎨 Update type annotations for `response_model`, allow things like `Union[str, None]`. PR [#5294](https://github.com/tiangolo/fastapi/pull/5294) by [@tiangolo](https://github.com/tiangolo). * 🌐 Fix typos in German translation for `docs/de/docs/features.md`. PR [#4533](https://github.com/tiangolo/fastapi/pull/4533) by [@0xflotus](https://github.com/0xflotus). From f6808e76dcb332aefe16abab37b0480b16e7cdb1 Mon Sep 17 00:00:00 2001 From: Andrey Semakin Date: Tue, 23 Aug 2022 18:47:19 +0500 Subject: [PATCH 052/194] =?UTF-8?q?=E2=99=BB=20Strip=20empty=20whitespace?= =?UTF-8?q?=20from=20description=20extracted=20from=20docstrings=20(#2821)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- fastapi/routing.py | 2 +- .../test_tutorial004.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/fastapi/routing.py b/fastapi/routing.py index 2e0d2e552aaf0..80bd53279a31f 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -409,7 +409,7 @@ def __init__( self.description = description or inspect.cleandoc(self.endpoint.__doc__ or "") # if a "form feed" character (page break) is found in the description text, # truncate description text to the content preceding the first "form feed" - self.description = self.description.split("\f")[0] + self.description = self.description.split("\f")[0].strip() response_fields = {} for additional_status_code, response in self.responses.items(): assert isinstance(response, dict), "An additional response must be a dict" diff --git a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial004.py b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial004.py index 456e509d5b76a..3de19833beb23 100644 --- a/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial004.py +++ b/tests/test_tutorial/test_path_operation_advanced_configurations/test_tutorial004.py @@ -31,7 +31,7 @@ }, }, "summary": "Create an item", - "description": "Create an item with all the information:\n\n- **name**: each item must have a name\n- **description**: a long description\n- **price**: required\n- **tax**: if the item doesn't have tax, you can omit this\n- **tags**: a set of unique tag strings for this item\n", + "description": "Create an item with all the information:\n\n- **name**: each item must have a name\n- **description**: a long description\n- **price**: required\n- **tax**: if the item doesn't have tax, you can omit this\n- **tags**: a set of unique tag strings for this item", "operationId": "create_item_items__post", "requestBody": { "content": { From 09acce4b2c7f50cdea7c487e9123b88c44a6724f Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 23 Aug 2022 13:48:07 +0000 Subject: [PATCH 053/194] =?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 f2c455e2fd924..58ba2fb2c444f 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* ♻ Strip empty whitespace from description extracted from docstrings. PR [#2821](https://github.com/tiangolo/fastapi/pull/2821) by [@and-semakin](https://github.com/and-semakin). * 🐛 Fix cached dependencies when using a dependency in `Security()` and other places (e.g. `Depends()`) with different OAuth2 scopes. PR [#2945](https://github.com/tiangolo/fastapi/pull/2945) by [@laggardkernel](https://github.com/laggardkernel). * 🐛 Fix `response_model` not invalidating `None`. PR [#2725](https://github.com/tiangolo/fastapi/pull/2725) by [@hukkin](https://github.com/hukkin). * 🎨 Update type annotations for `response_model`, allow things like `Union[str, None]`. PR [#5294](https://github.com/tiangolo/fastapi/pull/5294) by [@tiangolo](https://github.com/tiangolo). From ec072d75fe0aae16caec3a8aa3f57ca8d6f05de5 Mon Sep 17 00:00:00 2001 From: Teo Koon Peng Date: Tue, 23 Aug 2022 21:57:25 +0800 Subject: [PATCH 054/194] =?UTF-8?q?=E2=AC=86=20Upgrade=20Swagger=20UI=20co?= =?UTF-8?q?py=20of=20`oauth2-redirect.html`=20to=20include=20fixes=20for?= =?UTF-8?q?=20flavors=20of=20authorization=20code=20flows=20in=20Swagger?= =?UTF-8?q?=20UI=20(#3439)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- fastapi/openapi/docs.py | 43 +++++++++++++++++++++++++++-------------- 1 file changed, 28 insertions(+), 15 deletions(-) diff --git a/fastapi/openapi/docs.py b/fastapi/openapi/docs.py index d6af17a850e78..b7803b13bde81 100644 --- a/fastapi/openapi/docs.py +++ b/fastapi/openapi/docs.py @@ -115,12 +115,14 @@ def get_redoc_html( def get_swagger_ui_oauth2_redirect_html() -> HTMLResponse: + # copied from https://github.com/swagger-api/swagger-ui/blob/v4.14.0/dist/oauth2-redirect.html html = """ - + - - - + + Swagger UI: OAuth2 Redirect + + + + """ return HTMLResponse(content=html) From ad65e72d901c12edb5c69c1cded8994fa094f92f Mon Sep 17 00:00:00 2001 From: github-actions Date: Tue, 23 Aug 2022 13:58:06 +0000 Subject: [PATCH 055/194] =?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 58ba2fb2c444f..97748436f2639 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* ⬆ Upgrade Swagger UI copy of `oauth2-redirect.html` to include fixes for flavors of authorization code flows in Swagger UI. PR [#3439](https://github.com/tiangolo/fastapi/pull/3439) by [@koonpeng](https://github.com/koonpeng). * ♻ Strip empty whitespace from description extracted from docstrings. PR [#2821](https://github.com/tiangolo/fastapi/pull/2821) by [@and-semakin](https://github.com/and-semakin). * 🐛 Fix cached dependencies when using a dependency in `Security()` and other places (e.g. `Depends()`) with different OAuth2 scopes. PR [#2945](https://github.com/tiangolo/fastapi/pull/2945) by [@laggardkernel](https://github.com/laggardkernel). * 🐛 Fix `response_model` not invalidating `None`. PR [#2725](https://github.com/tiangolo/fastapi/pull/2725) by [@hukkin](https://github.com/hukkin). From 18819f9850007633f728fcf457db5170f7922001 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Tue, 23 Aug 2022 16:13:37 +0200 Subject: [PATCH 056/194] =?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 | 78 +++++++++++++++++++++++++++++++++-- 1 file changed, 75 insertions(+), 3 deletions(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 97748436f2639..524da6f42f64b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,14 +2,86 @@ ## Latest Changes -* ⬆ Upgrade Swagger UI copy of `oauth2-redirect.html` to include fixes for flavors of authorization code flows in Swagger UI. PR [#3439](https://github.com/tiangolo/fastapi/pull/3439) by [@koonpeng](https://github.com/koonpeng). +### Breaking Changes - Fixes + +* 🐛 Fix `response_model` not invalidating `None`. PR [#2725](https://github.com/tiangolo/fastapi/pull/2725) by [@hukkin](https://github.com/hukkin). + +If you are using `response_model` with some type that doesn't include `None` but the function is returning `None`, it will now raise an internal server error, because you are returning invalid data that violates the contract in `response_model`. Before this release it would allow breaking that contract returning `None`. + +For example, if you have an app like this: + +```Python +from fastapi import FastAPI +from pydantic import BaseModel + +class Item(BaseModel): + name: str + price: Optional[float] = None + owner_ids: Optional[List[int]] = None + +app = FastAPI() + +@app.get("/items/invalidnone", response_model=Item) +def get_invalid_none(): + return None +``` + +...calling the path `/items/invalidnone` will raise an error, because `None` is not a valid type for the `response_model` declared with `Item`. + +You could also be implicitly returning `None` without realizing, for example: + +```Python +from fastapi import FastAPI +from pydantic import BaseModel + +class Item(BaseModel): + name: str + price: Optional[float] = None + owner_ids: Optional[List[int]] = None + +app = FastAPI() + +@app.get("/items/invalidnone", response_model=Item) +def get_invalid_none(): + if flag: + return {"name": "foo"} + # if flag is False, at this point the function will implicitly return None +``` + +If you have *path operations* using `response_model` that need to be allowed to return `None`, make it explicit in `response_model` using `Union[Something, None]`: + +```Python +from typing import Union + +from fastapi import FastAPI +from pydantic import BaseModel + +class Item(BaseModel): + name: str + price: Optional[float] = None + owner_ids: Optional[List[int]] = None + +app = FastAPI() + +@app.get("/items/invalidnone", response_model=Union[Item, None]) +def get_invalid_none(): + return None +``` + +This way the data will be correctly validated, you won't have an internal server error, and the documentation will also reflect that this *path operation* could return `None` (or `null` in JSON). + +### Fixes + +* ⬆ Upgrade Swagger UI copy of `oauth2-redirect.html` to include fixes for flavors of authorization code flows in Swagger UI. PR [#3439](https://github.com/tiangolo/fastapi/pull/3439) initial PR by [@koonpeng](https://github.com/koonpeng). * ♻ Strip empty whitespace from description extracted from docstrings. PR [#2821](https://github.com/tiangolo/fastapi/pull/2821) by [@and-semakin](https://github.com/and-semakin). * 🐛 Fix cached dependencies when using a dependency in `Security()` and other places (e.g. `Depends()`) with different OAuth2 scopes. PR [#2945](https://github.com/tiangolo/fastapi/pull/2945) by [@laggardkernel](https://github.com/laggardkernel). -* 🐛 Fix `response_model` not invalidating `None`. PR [#2725](https://github.com/tiangolo/fastapi/pull/2725) by [@hukkin](https://github.com/hukkin). * 🎨 Update type annotations for `response_model`, allow things like `Union[str, None]`. PR [#5294](https://github.com/tiangolo/fastapi/pull/5294) by [@tiangolo](https://github.com/tiangolo). + +### Translations + * 🌐 Fix typos in German translation for `docs/de/docs/features.md`. PR [#4533](https://github.com/tiangolo/fastapi/pull/4533) by [@0xflotus](https://github.com/0xflotus). * 🌐 Add missing navigator for `encoder.md` in Korean translation. PR [#5238](https://github.com/tiangolo/fastapi/pull/5238) by [@joonas-yoon](https://github.com/joonas-yoon). -* Translated docs to ru `project_generator.md`, `features.md`, `help-fastapi.md`, upgrade `python-types.md`, `docs/ru/mkdocs.yml`.. PR [#4913](https://github.com/tiangolo/fastapi/pull/4913) by [@Xewus](https://github.com/Xewus). +* (Empty PR merge by accident) [#4913](https://github.com/tiangolo/fastapi/pull/4913). ## 0.79.1 From 7d6e70791d0d4c5cf271bcd231ba78d1a3c0f582 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Tue, 23 Aug 2022 16:14:48 +0200 Subject: [PATCH 057/194] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.80?= =?UTF-8?q?.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 3 +++ fastapi/__init__.py | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 524da6f42f64b..fc48bf7ddea58 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,9 @@ ## Latest Changes + +## 0.80.0 + ### Breaking Changes - Fixes * 🐛 Fix `response_model` not invalidating `None`. PR [#2725](https://github.com/tiangolo/fastapi/pull/2725) by [@hukkin](https://github.com/hukkin). diff --git a/fastapi/__init__.py b/fastapi/__init__.py index abcb219a99420..3dc86cadf0deb 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.79.1" +__version__ = "0.80.0" from starlette import status as status From 68f25120c51545d36832478e508d63fcacdb3903 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Wed, 24 Aug 2022 10:43:44 +0200 Subject: [PATCH 058/194] =?UTF-8?q?=F0=9F=8D=B1=20Update=20Jina=20banner,?= =?UTF-8?q?=20fix=20typo=20(#5301)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/img/sponsors/docarray-top-banner.svg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/img/sponsors/docarray-top-banner.svg b/docs/en/docs/img/sponsors/docarray-top-banner.svg index c48a3312b81a1..b2eca354437e6 100644 --- a/docs/en/docs/img/sponsors/docarray-top-banner.svg +++ b/docs/en/docs/img/sponsors/docarray-top-banner.svg @@ -1 +1 @@ - + From 2201f29be32fd6a584433bcfc7c6310ac043b7f3 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 24 Aug 2022 08:44:22 +0000 Subject: [PATCH 059/194] =?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 fc48bf7ddea58..6e17be1595049 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 🍱 Update Jina banner, fix typo. PR [#5301](https://github.com/tiangolo/fastapi/pull/5301) by [@tiangolo](https://github.com/tiangolo). ## 0.80.0 From 1835b3f76d6c72629500f971920730c645867168 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Wed, 24 Aug 2022 16:18:11 +0200 Subject: [PATCH 060/194] =?UTF-8?q?=F0=9F=93=9D=20Update=20docs=20for=20te?= =?UTF-8?q?sting,=20fix=20examples=20with=20relative=20imports=20(#5302)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/advanced/async-tests.md | 14 ++++++++-- docs/en/docs/tutorial/testing.md | 38 +++++++++++++++++++++++++--- 2 files changed, 47 insertions(+), 5 deletions(-) diff --git a/docs/en/docs/advanced/async-tests.md b/docs/en/docs/advanced/async-tests.md index d5116233f8c55..e34f48f1732fa 100644 --- a/docs/en/docs/advanced/async-tests.md +++ b/docs/en/docs/advanced/async-tests.md @@ -26,13 +26,23 @@ The important difference for us is that with HTTPX we are not limited to synchro ## Example -For a simple example, let's consider the following `main.py` module: +For a simple example, let's consider a file structure similar to the one described in [Bigger Applications](../tutorial/bigger-applications.md){.internal-link target=_blank} and [Testing](../tutorial/testing.md){.internal-link target=_blank}: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + +The file `main.py` would have: ```Python {!../../../docs_src/async_tests/main.py!} ``` -The `test_main.py` module that contains the tests for `main.py` could look like this now: +The file `test_main.py` would have the tests for `main.py`, it could look like this now: ```Python {!../../../docs_src/async_tests/test_main.py!} diff --git a/docs/en/docs/tutorial/testing.md b/docs/en/docs/tutorial/testing.md index 79ea2b1ab58b8..d2ccd7dc77d45 100644 --- a/docs/en/docs/tutorial/testing.md +++ b/docs/en/docs/tutorial/testing.md @@ -50,7 +50,17 @@ And your **FastAPI** application might also be composed of several files/modules ### **FastAPI** app file -Let's say you have a file `main.py` with your **FastAPI** app: +Let's say you have a file structure as described in [Bigger Applications](./bigger-applications.md){.internal-link target=_blank}: + +``` +. +├── app +│   ├── __init__.py +│   └── main.py +``` + +In the file `main.py` you have your **FastAPI** app: + ```Python {!../../../docs_src/app_testing/main.py!} @@ -58,18 +68,40 @@ Let's say you have a file `main.py` with your **FastAPI** app: ### Testing file -Then you could have a file `test_main.py` with your tests, and import your `app` from the `main` module (`main.py`): +Then you could have a file `test_main.py` with your tests. It could live on the same Python package (the same directory with a `__init__.py` file): -```Python +``` hl_lines="5" +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + +Because this file is in the same package, you can use relative imports to import the object `app` from the `main` module (`main.py`): + +```Python hl_lines="3" {!../../../docs_src/app_testing/test_main.py!} ``` +...and have the code for the tests just like before. + ## Testing: extended example Now let's extend this example and add more details to see how to test different parts. ### Extended **FastAPI** app file +Let's continue with the same file structure as before: + +``` +. +├── app +│   ├── __init__.py +│   ├── main.py +│   └── test_main.py +``` + Let's say that now the file `main.py` with your **FastAPI** app has some other **path operations**. It has a `GET` operation that could return an error. From f90465f5b4e83110722b096306057c54bb211ba7 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 24 Aug 2022 14:18:57 +0000 Subject: [PATCH 061/194] =?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 6e17be1595049..1b58067415358 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 📝 Update docs for testing, fix examples with relative imports. PR [#5302](https://github.com/tiangolo/fastapi/pull/5302) by [@tiangolo](https://github.com/tiangolo). * 🍱 Update Jina banner, fix typo. PR [#5301](https://github.com/tiangolo/fastapi/pull/5301) by [@tiangolo](https://github.com/tiangolo). ## 0.80.0 From 8c6ad3561534d69a2ccb0d3d0e9e60afc5b388de Mon Sep 17 00:00:00 2001 From: Kevin Tewouda Date: Wed, 24 Aug 2022 16:53:43 +0200 Subject: [PATCH 062/194] =?UTF-8?q?=F0=9F=93=9D=20Update=20docs=20for=20ha?= =?UTF-8?q?ndling=20HTTP=20Basic=20Auth=20with=20`secrets.compare=5Fdigest?= =?UTF-8?q?()`=20to=20account=20for=20non-ASCII=20characters=20(#3536)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: le_woudar Co-authored-by: Sebastián Ramírez --- docs/en/docs/advanced/security/http-basic-auth.md | 14 ++++++++++---- docs_src/security/tutorial007.py | 14 +++++++++++--- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/docs/en/docs/advanced/security/http-basic-auth.md b/docs/en/docs/advanced/security/http-basic-auth.md index 6c589cd9afe32..90c516808fc41 100644 --- a/docs/en/docs/advanced/security/http-basic-auth.md +++ b/docs/en/docs/advanced/security/http-basic-auth.md @@ -34,13 +34,19 @@ Here's a more complete example. Use a dependency to check if the username and password are correct. -For this, use the Python standard module `secrets` to check the username and password: +For this, use the Python standard module `secrets` to check the username and password. -```Python hl_lines="1 11-13" +`secrets.compare_digest()` needs to take `bytes` or a `str` that only contains ASCII characters (the ones in English), this means it wouldn't work with characters like `á`, as in `Sebastián`. + +To handle that, we first convert the `username` and `password` to `bytes` encoding them with UTF-8. + +Then we can use `secrets.compare_digest()` to ensure that `credentials.username` is `"stanleyjobson"`, and that `credentials.password` is `"swordfish"`. + +```Python hl_lines="1 11-21" {!../../../docs_src/security/tutorial007.py!} ``` -This will ensure that `credentials.username` is `"stanleyjobson"`, and that `credentials.password` is `"swordfish"`. This would be similar to: +This would be similar to: ```Python if not (credentials.username == "stanleyjobson") or not (credentials.password == "swordfish"): @@ -102,6 +108,6 @@ That way, using `secrets.compare_digest()` in your application code, it will be After detecting that the credentials are incorrect, return an `HTTPException` with a status code 401 (the same returned when no credentials are provided) and add the header `WWW-Authenticate` to make the browser show the login prompt again: -```Python hl_lines="15-19" +```Python hl_lines="23-27" {!../../../docs_src/security/tutorial007.py!} ``` diff --git a/docs_src/security/tutorial007.py b/docs_src/security/tutorial007.py index 90b9ac0546ff5..790ee10bc6b1d 100644 --- a/docs_src/security/tutorial007.py +++ b/docs_src/security/tutorial007.py @@ -9,9 +9,17 @@ def get_current_username(credentials: HTTPBasicCredentials = Depends(security)): - correct_username = secrets.compare_digest(credentials.username, "stanleyjobson") - correct_password = secrets.compare_digest(credentials.password, "swordfish") - if not (correct_username and correct_password): + current_username_bytes = credentials.username.encode("utf8") + correct_username_bytes = b"stanleyjobson" + is_correct_username = secrets.compare_digest( + current_username_bytes, correct_username_bytes + ) + current_password_bytes = credentials.password.encode("utf8") + correct_password_bytes = b"swordfish" + is_correct_password = secrets.compare_digest( + current_password_bytes, correct_password_bytes + ) + if not (is_correct_username and is_correct_password): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect email or password", From 39319a7ede38a57d8b2dbd1c376850fcf8ae5a17 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 24 Aug 2022 14:54:27 +0000 Subject: [PATCH 063/194] =?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 1b58067415358..8061271625c79 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 📝 Update docs for handling HTTP Basic Auth with `secrets.compare_digest()` to account for non-ASCII characters. PR [#3536](https://github.com/tiangolo/fastapi/pull/3536) by [@lewoudar](https://github.com/lewoudar). * 📝 Update docs for testing, fix examples with relative imports. PR [#5302](https://github.com/tiangolo/fastapi/pull/5302) by [@tiangolo](https://github.com/tiangolo). * 🍱 Update Jina banner, fix typo. PR [#5301](https://github.com/tiangolo/fastapi/pull/5301) by [@tiangolo](https://github.com/tiangolo). From 438656395afcc78e06ba2c7c0655e0156dfdc20d Mon Sep 17 00:00:00 2001 From: Caleb Renfroe <35737053+ccrenfroe@users.noreply.github.com> Date: Wed, 24 Aug 2022 17:35:30 -0400 Subject: [PATCH 064/194] =?UTF-8?q?=E2=9C=8F=20Reword=20confusing=20senten?= =?UTF-8?q?ce=20in=20docs=20file=20`typo-fix-path-params-numeric-validatio?= =?UTF-8?q?ns.md`=20(#3219)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs/en/docs/tutorial/path-params-numeric-validations.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/en/docs/tutorial/path-params-numeric-validations.md b/docs/en/docs/tutorial/path-params-numeric-validations.md index 29235c6e2863b..4b2e3f973813d 100644 --- a/docs/en/docs/tutorial/path-params-numeric-validations.md +++ b/docs/en/docs/tutorial/path-params-numeric-validations.md @@ -122,9 +122,9 @@ And you can also declare numeric validations: * `le`: `l`ess than or `e`qual !!! info - `Query`, `Path`, and others you will see later are subclasses of a common `Param` class (that you don't need to use). + `Query`, `Path`, and other classes you will see later are subclasses of a common `Param` class. - And all of them share the same all these same parameters of additional validation and metadata you have seen. + All of them share the same parameters for additional validation and metadata you have seen. !!! note "Technical Details" When you import `Query`, `Path` and others from `fastapi`, they are actually functions. From afaa0391a59e54ff59e1d3d1b49785aecd78ee11 Mon Sep 17 00:00:00 2001 From: github-actions Date: Wed, 24 Aug 2022 21:36:15 +0000 Subject: [PATCH 065/194] =?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 8061271625c79..7418fae6a811f 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* ✏ Reword confusing sentence in docs file `typo-fix-path-params-numeric-validations.md`. PR [#3219](https://github.com/tiangolo/fastapi/pull/3219) by [@ccrenfroe](https://github.com/ccrenfroe). * 📝 Update docs for handling HTTP Basic Auth with `secrets.compare_digest()` to account for non-ASCII characters. PR [#3536](https://github.com/tiangolo/fastapi/pull/3536) by [@lewoudar](https://github.com/lewoudar). * 📝 Update docs for testing, fix examples with relative imports. PR [#5302](https://github.com/tiangolo/fastapi/pull/5302) by [@tiangolo](https://github.com/tiangolo). * 🍱 Update Jina banner, fix typo. PR [#5301](https://github.com/tiangolo/fastapi/pull/5301) by [@tiangolo](https://github.com/tiangolo). From 9359a8d65fdff4460d01d652ccafd31507c6c426 Mon Sep 17 00:00:00 2001 From: Sidharth Ajithkumar Date: Thu, 25 Aug 2022 15:25:53 +0530 Subject: [PATCH 066/194] =?UTF-8?q?=E2=9C=A8=20Preserve=20`json.JSONDecode?= =?UTF-8?q?Error`=20information=20when=20handling=20invalid=20JSON=20in=20?= =?UTF-8?q?request=20body,=20to=20support=20custom=20exception=20handlers?= =?UTF-8?q?=20that=20use=20its=20information=20(#4057)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- fastapi/routing.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/fastapi/routing.py b/fastapi/routing.py index 80bd53279a31f..8f4d0fa7ef578 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -209,7 +209,9 @@ async def app(request: Request) -> Response: else: body = body_bytes except json.JSONDecodeError as e: - raise RequestValidationError([ErrorWrapper(e, ("body", e.pos))], body=e.doc) + raise RequestValidationError( + [ErrorWrapper(e, ("body", e.pos))], body=e.doc + ) from e except Exception as e: raise HTTPException( status_code=400, detail="There was an error parsing the body" From 5215b39d5081dab2145fb682d832a93649d26063 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 25 Aug 2022 09:56:40 +0000 Subject: [PATCH 067/194] =?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 7418fae6a811f..3371499721bcc 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* ✨ Preserve `json.JSONDecodeError` information when handling invalid JSON in request body, to support custom exception handlers that use its information. PR [#4057](https://github.com/tiangolo/fastapi/pull/4057) by [@UKnowWhoIm](https://github.com/UKnowWhoIm). * ✏ Reword confusing sentence in docs file `typo-fix-path-params-numeric-validations.md`. PR [#3219](https://github.com/tiangolo/fastapi/pull/3219) by [@ccrenfroe](https://github.com/ccrenfroe). * 📝 Update docs for handling HTTP Basic Auth with `secrets.compare_digest()` to account for non-ASCII characters. PR [#3536](https://github.com/tiangolo/fastapi/pull/3536) by [@lewoudar](https://github.com/lewoudar). * 📝 Update docs for testing, fix examples with relative imports. PR [#5302](https://github.com/tiangolo/fastapi/pull/5302) by [@tiangolo](https://github.com/tiangolo). From eb3ab337ab49d1904f027c0a523456cfe40d582d Mon Sep 17 00:00:00 2001 From: Andy Challis Date: Fri, 26 Aug 2022 07:44:40 +1000 Subject: [PATCH 068/194] =?UTF-8?q?=E2=9C=A8=20Allow=20custom=20middleware?= =?UTF-8?q?s=20to=20raise=20`HTTPException`s=20and=20propagate=20them=20(#?= =?UTF-8?q?2036)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- fastapi/routing.py | 2 + tests/test_custom_middleware_exception.py | 95 +++++++++++++++++++++++ 2 files changed, 97 insertions(+) create mode 100644 tests/test_custom_middleware_exception.py diff --git a/fastapi/routing.py b/fastapi/routing.py index 8f4d0fa7ef578..1ac4b38806347 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -212,6 +212,8 @@ async def app(request: Request) -> Response: raise RequestValidationError( [ErrorWrapper(e, ("body", e.pos))], body=e.doc ) from e + except HTTPException: + raise except Exception as e: raise HTTPException( status_code=400, detail="There was an error parsing the body" diff --git a/tests/test_custom_middleware_exception.py b/tests/test_custom_middleware_exception.py new file mode 100644 index 0000000000000..d9b81e7c2e74f --- /dev/null +++ b/tests/test_custom_middleware_exception.py @@ -0,0 +1,95 @@ +from pathlib import Path +from typing import Optional + +from fastapi import APIRouter, FastAPI, File, UploadFile +from fastapi.exceptions import HTTPException +from fastapi.testclient import TestClient + +app = FastAPI() + +router = APIRouter() + + +class ContentSizeLimitMiddleware: + """Content size limiting middleware for ASGI applications + Args: + app (ASGI application): ASGI application + max_content_size (optional): the maximum content size allowed in bytes, None for no limit + """ + + def __init__(self, app: APIRouter, max_content_size: Optional[int] = None): + self.app = app + self.max_content_size = max_content_size + + def receive_wrapper(self, receive): + received = 0 + + async def inner(): + nonlocal received + message = await receive() + if message["type"] != "http.request": + return message # pragma: no cover + + body_len = len(message.get("body", b"")) + received += body_len + if received > self.max_content_size: + raise HTTPException( + 422, + detail={ + "name": "ContentSizeLimitExceeded", + "code": 999, + "message": "File limit exceeded", + }, + ) + return message + + return inner + + async def __call__(self, scope, receive, send): + if scope["type"] != "http" or self.max_content_size is None: + await self.app(scope, receive, send) + return + + wrapper = self.receive_wrapper(receive) + await self.app(scope, wrapper, send) + + +@router.post("/middleware") +def run_middleware(file: UploadFile = File(..., description="Big File")): + return {"message": "OK"} + + +app.include_router(router) +app.add_middleware(ContentSizeLimitMiddleware, max_content_size=2**8) + + +client = TestClient(app) + + +def test_custom_middleware_exception(tmp_path: Path): + default_pydantic_max_size = 2**16 + path = tmp_path / "test.txt" + path.write_bytes(b"x" * (default_pydantic_max_size + 1)) + + with client: + with open(path, "rb") as file: + response = client.post("/middleware", files={"file": file}) + assert response.status_code == 422, response.text + assert response.json() == { + "detail": { + "name": "ContentSizeLimitExceeded", + "code": 999, + "message": "File limit exceeded", + } + } + + +def test_custom_middleware_exception_not_raised(tmp_path: Path): + path = tmp_path / "test.txt" + path.write_bytes(b"") + + with client: + with open(path, "rb") as file: + response = client.post("/middleware", files={"file": file}) + assert response.status_code == 200, response.text + assert response.json() == {"message": "OK"} From af3a6ef78b01fcef5060dad63da2f4ee22a0b618 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 25 Aug 2022 21:45:33 +0000 Subject: [PATCH 069/194] =?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 3371499721bcc..0d179cb31b35b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* ✨ Allow custom middlewares to raise `HTTPException`s and propagate them. PR [#2036](https://github.com/tiangolo/fastapi/pull/2036) by [@ghandic](https://github.com/ghandic). * ✨ Preserve `json.JSONDecodeError` information when handling invalid JSON in request body, to support custom exception handlers that use its information. PR [#4057](https://github.com/tiangolo/fastapi/pull/4057) by [@UKnowWhoIm](https://github.com/UKnowWhoIm). * ✏ Reword confusing sentence in docs file `typo-fix-path-params-numeric-validations.md`. PR [#3219](https://github.com/tiangolo/fastapi/pull/3219) by [@ccrenfroe](https://github.com/ccrenfroe). * 📝 Update docs for handling HTTP Basic Auth with `secrets.compare_digest()` to account for non-ASCII characters. PR [#3536](https://github.com/tiangolo/fastapi/pull/3536) by [@lewoudar](https://github.com/lewoudar). From ca2fae0588260f93f886aa59f689e3018e934a27 Mon Sep 17 00:00:00 2001 From: juntatalor Date: Fri, 26 Aug 2022 00:52:53 +0300 Subject: [PATCH 070/194] =?UTF-8?q?=E2=9C=A8=20Add=20support=20for=20`Froz?= =?UTF-8?q?enSet`=20in=20parameters=20(e.g.=20query)=20(#2938)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: saborisov Co-authored-by: Sebastián Ramírez --- fastapi/dependencies/utils.py | 2 ++ tests/main.py | 7 ++++++- tests/test_application.py | 35 +++++++++++++++++++++++++++++++++++ tests/test_query.py | 1 + 4 files changed, 44 insertions(+), 1 deletion(-) diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index f6151f6bd8a6a..d781fdb62525c 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -34,6 +34,7 @@ from pydantic.error_wrappers import ErrorWrapper from pydantic.errors import MissingError from pydantic.fields import ( + SHAPE_FROZENSET, SHAPE_LIST, SHAPE_SEQUENCE, SHAPE_SET, @@ -58,6 +59,7 @@ sequence_shapes = { SHAPE_LIST, SHAPE_SET, + SHAPE_FROZENSET, SHAPE_TUPLE, SHAPE_SEQUENCE, SHAPE_TUPLE_ELLIPSIS, diff --git a/tests/main.py b/tests/main.py index f70496db8e111..fce6657040bd8 100644 --- a/tests/main.py +++ b/tests/main.py @@ -1,5 +1,5 @@ import http -from typing import Optional +from typing import FrozenSet, Optional from fastapi import FastAPI, Path, Query @@ -192,3 +192,8 @@ def get_query_param_required_type(query: int = Query()): @app.get("/enum-status-code", status_code=http.HTTPStatus.CREATED) def get_enum_status_code(): return "foo bar" + + +@app.get("/query/frozenset") +def get_query_type_frozenset(query: FrozenSet[int] = Query(...)): + return ",".join(map(str, sorted(query))) diff --git a/tests/test_application.py b/tests/test_application.py index d9194c15c7313..b7d72f9ad176c 100644 --- a/tests/test_application.py +++ b/tests/test_application.py @@ -1090,6 +1090,41 @@ "operationId": "get_enum_status_code_enum_status_code_get", } }, + "/query/frozenset": { + "get": { + "summary": "Get Query Type Frozenset", + "operationId": "get_query_type_frozenset_query_frozenset_get", + "parameters": [ + { + "required": True, + "schema": { + "title": "Query", + "uniqueItems": True, + "type": "array", + "items": {"type": "integer"}, + }, + "name": "query", + "in": "query", + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + }, }, "components": { "schemas": { diff --git a/tests/test_query.py b/tests/test_query.py index cdbdd1ccdcd15..0c73eb665eda7 100644 --- a/tests/test_query.py +++ b/tests/test_query.py @@ -53,6 +53,7 @@ ("/query/param-required/int", 422, response_missing), ("/query/param-required/int?query=50", 200, "foo bar 50"), ("/query/param-required/int?query=foo", 422, response_not_valid_int), + ("/query/frozenset/?query=1&query=1&query=2", 200, "1,2"), ], ) def test_get_path(path, expected_status, expected_response): From 92181ef1822920c746009d035d53009be9bab65c Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 25 Aug 2022 21:53:36 +0000 Subject: [PATCH 071/194] =?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 0d179cb31b35b..56253c873e27f 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* ✨ Add support for `FrozenSet` in parameters (e.g. query). PR [#2938](https://github.com/tiangolo/fastapi/pull/2938) by [@juntatalor](https://github.com/juntatalor). * ✨ Allow custom middlewares to raise `HTTPException`s and propagate them. PR [#2036](https://github.com/tiangolo/fastapi/pull/2036) by [@ghandic](https://github.com/ghandic). * ✨ Preserve `json.JSONDecodeError` information when handling invalid JSON in request body, to support custom exception handlers that use its information. PR [#4057](https://github.com/tiangolo/fastapi/pull/4057) by [@UKnowWhoIm](https://github.com/UKnowWhoIm). * ✏ Reword confusing sentence in docs file `typo-fix-path-params-numeric-validations.md`. PR [#3219](https://github.com/tiangolo/fastapi/pull/3219) by [@ccrenfroe](https://github.com/ccrenfroe). From 880c8b37cf8ba88a7f4de40cf18dec49c9e71454 Mon Sep 17 00:00:00 2001 From: Ori Levari Date: Fri, 26 Aug 2022 02:26:20 -0700 Subject: [PATCH 072/194] =?UTF-8?q?=F0=9F=90=9B=20Fix=20support=20for=20ex?= =?UTF-8?q?tending=20`openapi=5Fextras`=20with=20parameter=20lists=20(#426?= =?UTF-8?q?7)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- fastapi/utils.py | 6 + .../test_openapi_query_parameter_extension.py | 127 ++++++++++++++++++ 2 files changed, 133 insertions(+) create mode 100644 tests/test_openapi_query_parameter_extension.py diff --git a/fastapi/utils.py b/fastapi/utils.py index 40750a5b35269..0163fd95fc62c 100644 --- a/fastapi/utils.py +++ b/fastapi/utils.py @@ -161,6 +161,12 @@ def deep_dict_update(main_dict: Dict[Any, Any], update_dict: Dict[Any, Any]) -> and isinstance(value, dict) ): deep_dict_update(main_dict[key], value) + elif ( + key in main_dict + and isinstance(main_dict[key], list) + and isinstance(update_dict[key], list) + ): + main_dict[key] = main_dict[key] + update_dict[key] else: main_dict[key] = value diff --git a/tests/test_openapi_query_parameter_extension.py b/tests/test_openapi_query_parameter_extension.py new file mode 100644 index 0000000000000..d3996f26ee417 --- /dev/null +++ b/tests/test_openapi_query_parameter_extension.py @@ -0,0 +1,127 @@ +from typing import Optional + +from fastapi import FastAPI +from fastapi.testclient import TestClient + +app = FastAPI() + + +@app.get( + "/", + openapi_extra={ + "parameters": [ + { + "required": False, + "schema": {"title": "Extra Param 1"}, + "name": "extra_param_1", + "in": "query", + }, + { + "required": True, + "schema": {"title": "Extra Param 2"}, + "name": "extra_param_2", + "in": "query", + }, + ] + }, +) +def route_with_extra_query_parameters(standard_query_param: Optional[int] = 50): + return {} + + +client = TestClient(app) + + +openapi_schema = { + "openapi": "3.0.2", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/": { + "get": { + "summary": "Route With Extra Query Parameters", + "operationId": "route_with_extra_query_parameters__get", + "parameters": [ + { + "required": False, + "schema": { + "title": "Standard Query Param", + "type": "integer", + "default": 50, + }, + "name": "standard_query_param", + "in": "query", + }, + { + "required": False, + "schema": {"title": "Extra Param 1"}, + "name": "extra_param_1", + "in": "query", + }, + { + "required": True, + "schema": {"title": "Extra Param 2"}, + "name": "extra_param_2", + "in": "query", + }, + ], + "responses": { + "200": { + "description": "Successful Response", + "content": {"application/json": {"schema": {}}}, + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": {"$ref": "#/components/schemas/ValidationError"}, + } + }, + }, + "ValidationError": { + "title": "ValidationError", + "required": ["loc", "msg", "type"], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": {"anyOf": [{"type": "string"}, {"type": "integer"}]}, + }, + "msg": {"title": "Message", "type": "string"}, + "type": {"title": "Error Type", "type": "string"}, + }, + }, + } + }, +} + + +def test_openapi(): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == openapi_schema + + +def test_get_route(): + response = client.get("/") + assert response.status_code == 200, response.text + assert response.json() == {} From 0968329ed7aa07e66b6a55f1f5f71e4232085f4a Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 26 Aug 2022 09:26:59 +0000 Subject: [PATCH 073/194] =?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 56253c873e27f..a30e397a5958b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 🐛 Fix support for extending `openapi_extras` with parameter lists. PR [#4267](https://github.com/tiangolo/fastapi/pull/4267) by [@orilevari](https://github.com/orilevari). * ✨ Add support for `FrozenSet` in parameters (e.g. query). PR [#2938](https://github.com/tiangolo/fastapi/pull/2938) by [@juntatalor](https://github.com/juntatalor). * ✨ Allow custom middlewares to raise `HTTPException`s and propagate them. PR [#2036](https://github.com/tiangolo/fastapi/pull/2036) by [@ghandic](https://github.com/ghandic). * ✨ Preserve `json.JSONDecodeError` information when handling invalid JSON in request body, to support custom exception handlers that use its information. PR [#4057](https://github.com/tiangolo/fastapi/pull/4057) by [@UKnowWhoIm](https://github.com/UKnowWhoIm). From d5c84594cb816bc17b044fd1063a3bda3f728726 Mon Sep 17 00:00:00 2001 From: James Curtin Date: Fri, 26 Aug 2022 05:41:23 -0400 Subject: [PATCH 074/194] =?UTF-8?q?=E2=AC=86=20Upgrade=20version=20pin=20a?= =?UTF-8?q?ccepted=20for=20Flake8,=20for=20internal=20code,=20to=20`flake8?= =?UTF-8?q?=20>=3D3.8.3,<6.0.0`=20(#4097)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- pyproject.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 5ffdf93ad371c..9263985ce0e3a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -49,7 +49,7 @@ test = [ "pytest >=6.2.4,<7.0.0", "pytest-cov >=2.12.0,<4.0.0", "mypy ==0.910", - "flake8 >=3.8.3,<4.0.0", + "flake8 >=3.8.3,<6.0.0", "black == 22.3.0", "isort >=5.0.6,<6.0.0", "requests >=2.24.0,<3.0.0", @@ -83,7 +83,7 @@ dev = [ "python-jose[cryptography] >=3.3.0,<4.0.0", "passlib[bcrypt] >=1.7.2,<2.0.0", "autoflake >=1.4.0,<2.0.0", - "flake8 >=3.8.3,<4.0.0", + "flake8 >=3.8.3,<6.0.0", "uvicorn[standard] >=0.12.0,<0.18.0", "pre-commit >=2.17.0,<3.0.0", ] From f928f3390ca3ff5fdb3575fb26f458cb93c7416c Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 26 Aug 2022 09:42:03 +0000 Subject: [PATCH 075/194] =?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 a30e397a5958b..a3186b1502c58 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* ⬆ Upgrade version pin accepted for Flake8, for internal code, to `flake8 >=3.8.3,<6.0.0`. PR [#4097](https://github.com/tiangolo/fastapi/pull/4097) by [@jamescurtin](https://github.com/jamescurtin). * 🐛 Fix support for extending `openapi_extras` with parameter lists. PR [#4267](https://github.com/tiangolo/fastapi/pull/4267) by [@orilevari](https://github.com/orilevari). * ✨ Add support for `FrozenSet` in parameters (e.g. query). PR [#2938](https://github.com/tiangolo/fastapi/pull/2938) by [@juntatalor](https://github.com/juntatalor). * ✨ Allow custom middlewares to raise `HTTPException`s and propagate them. PR [#2036](https://github.com/tiangolo/fastapi/pull/2036) by [@ghandic](https://github.com/ghandic). From bb53d0b0eaad0b16a7defa640291c1ef35c95e06 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joon=20Hwan=20=EA=B9=80=EC=A4=80=ED=99=98?= Date: Fri, 26 Aug 2022 22:04:48 +0900 Subject: [PATCH 076/194] =?UTF-8?q?=F0=9F=8E=A8=20Fix=20syntax=20highlight?= =?UTF-8?q?ing=20in=20docs=20for=20OpenAPI=20Callbacks=20(#4368)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs/en/docs/advanced/openapi-callbacks.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/en/docs/advanced/openapi-callbacks.md b/docs/en/docs/advanced/openapi-callbacks.md index 138c90dd7c435..656ddbb3f5abe 100644 --- a/docs/en/docs/advanced/openapi-callbacks.md +++ b/docs/en/docs/advanced/openapi-callbacks.md @@ -31,7 +31,7 @@ It will have a *path operation* that will receive an `Invoice` body, and a query This part is pretty normal, most of the code is probably already familiar to you: -```Python hl_lines="10-14 37-54" +```Python hl_lines="9-13 36-53" {!../../../docs_src/openapi_callbacks/tutorial001.py!} ``` @@ -83,7 +83,7 @@ So we are going to use that same knowledge to document how the *external API* sh First create a new `APIRouter` that will contain one or more callbacks. -```Python hl_lines="5 26" +```Python hl_lines="3 25" {!../../../docs_src/openapi_callbacks/tutorial001.py!} ``` @@ -96,7 +96,7 @@ It should look just like a normal FastAPI *path operation*: * It should probably have a declaration of the body it should receive, e.g. `body: InvoiceEvent`. * And it could also have a declaration of the response it should return, e.g. `response_model=InvoiceEventReceived`. -```Python hl_lines="17-19 22-23 29-33" +```Python hl_lines="16-18 21-22 28-32" {!../../../docs_src/openapi_callbacks/tutorial001.py!} ``` @@ -163,7 +163,7 @@ At this point you have the *callback path operation(s)* needed (the one(s) that Now use the parameter `callbacks` in *your API's path operation decorator* to pass the attribute `.routes` (that's actually just a `list` of routes/*path operations*) from that callback router: -```Python hl_lines="36" +```Python hl_lines="35" {!../../../docs_src/openapi_callbacks/tutorial001.py!} ``` From 75792eb82b47a3a6bb4a971d9694456cc2760865 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 26 Aug 2022 13:05:26 +0000 Subject: [PATCH 077/194] =?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 a3186b1502c58..bd4fa0ba4859b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 🎨 Fix syntax highlighting in docs for OpenAPI Callbacks. PR [#4368](https://github.com/tiangolo/fastapi/pull/4368) by [@xncbf](https://github.com/xncbf). * ⬆ Upgrade version pin accepted for Flake8, for internal code, to `flake8 >=3.8.3,<6.0.0`. PR [#4097](https://github.com/tiangolo/fastapi/pull/4097) by [@jamescurtin](https://github.com/jamescurtin). * 🐛 Fix support for extending `openapi_extras` with parameter lists. PR [#4267](https://github.com/tiangolo/fastapi/pull/4267) by [@orilevari](https://github.com/orilevari). * ✨ Add support for `FrozenSet` in parameters (e.g. query). PR [#2938](https://github.com/tiangolo/fastapi/pull/2938) by [@juntatalor](https://github.com/juntatalor). From c8124496fc34c024e411f293d3893219005d409f Mon Sep 17 00:00:00 2001 From: Muzaffer Cikay Date: Fri, 26 Aug 2022 16:16:17 +0300 Subject: [PATCH 078/194] =?UTF-8?q?=E2=99=BB=20Simplify=20conditional=20as?= =?UTF-8?q?signment=20in=20`fastapi/dependencies/utils.py`=20(#4597)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- fastapi/dependencies/utils.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index d781fdb62525c..d098b65f1a5f5 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -302,10 +302,7 @@ def get_dependant( assert is_scalar_field( field=param_field ), "Path params must be of one of the supported types" - if isinstance(param.default, params.Path): - ignore_default = False - else: - ignore_default = True + ignore_default = not isinstance(param.default, params.Path) param_field = get_param_field( param=param, param_name=param_name, From a64387c3fc03120e3424fb12bfa64df8d949da43 Mon Sep 17 00:00:00 2001 From: Guillermo Quintana Pelayo <36505071+GuilleQP@users.noreply.github.com> Date: Fri, 26 Aug 2022 15:16:44 +0200 Subject: [PATCH 079/194] =?UTF-8?q?=E2=99=BB=20Move=20internal=20variable?= =?UTF-8?q?=20for=20errors=20in=20`jsonable=5Fencoder`=20to=20put=20relate?= =?UTF-8?q?d=20code=20closer=20(#4560)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- fastapi/encoders.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fastapi/encoders.py b/fastapi/encoders.py index b1fde73ceb7fc..6f571edb261d7 100644 --- a/fastapi/encoders.py +++ b/fastapi/encoders.py @@ -137,10 +137,10 @@ def jsonable_encoder( if isinstance(obj, classes_tuple): return encoder(obj) - errors: List[Exception] = [] try: data = dict(obj) except Exception as e: + errors: List[Exception] = [] errors.append(e) try: data = vars(obj) From 923e0ac0c16b782f41bc906f4e883fa0b687fa06 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 26 Aug 2022 13:17:04 +0000 Subject: [PATCH 080/194] =?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 bd4fa0ba4859b..ed67fab04a0f8 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* ♻ Simplify conditional assignment in `fastapi/dependencies/utils.py`. PR [#4597](https://github.com/tiangolo/fastapi/pull/4597) by [@cikay](https://github.com/cikay). * 🎨 Fix syntax highlighting in docs for OpenAPI Callbacks. PR [#4368](https://github.com/tiangolo/fastapi/pull/4368) by [@xncbf](https://github.com/xncbf). * ⬆ Upgrade version pin accepted for Flake8, for internal code, to `flake8 >=3.8.3,<6.0.0`. PR [#4097](https://github.com/tiangolo/fastapi/pull/4097) by [@jamescurtin](https://github.com/jamescurtin). * 🐛 Fix support for extending `openapi_extras` with parameter lists. PR [#4267](https://github.com/tiangolo/fastapi/pull/4267) by [@orilevari](https://github.com/orilevari). From ae56590c515e0ece83de951c4656c5c7d7e523c2 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 26 Aug 2022 13:17:25 +0000 Subject: [PATCH 081/194] =?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 ed67fab04a0f8..74efd542ffc20 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* ♻ Move internal variable for errors in `jsonable_encoder` to put related code closer. PR [#4560](https://github.com/tiangolo/fastapi/pull/4560) by [@GuilleQP](https://github.com/GuilleQP). * ♻ Simplify conditional assignment in `fastapi/dependencies/utils.py`. PR [#4597](https://github.com/tiangolo/fastapi/pull/4597) by [@cikay](https://github.com/cikay). * 🎨 Fix syntax highlighting in docs for OpenAPI Callbacks. PR [#4368](https://github.com/tiangolo/fastapi/pull/4368) by [@xncbf](https://github.com/xncbf). * ⬆ Upgrade version pin accepted for Flake8, for internal code, to `flake8 >=3.8.3,<6.0.0`. PR [#4097](https://github.com/tiangolo/fastapi/pull/4097) by [@jamescurtin](https://github.com/jamescurtin). From 00bdf533ef387b85a85df298de8537992c7d7c45 Mon Sep 17 00:00:00 2001 From: Shahriyar Rzayev Date: Fri, 26 Aug 2022 17:23:25 +0400 Subject: [PATCH 082/194] =?UTF-8?q?=E2=99=BB=20Change=20a=20`dict()`=20for?= =?UTF-8?q?=20`{}`=20in=20`fastapi/utils.py`=20(#3138)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fastapi/utils.py b/fastapi/utils.py index 0163fd95fc62c..b7da3e484240c 100644 --- a/fastapi/utils.py +++ b/fastapi/utils.py @@ -87,7 +87,7 @@ def create_cloned_field( ) -> ModelField: # _cloned_types has already cloned types, to support recursive models if cloned_types is None: - cloned_types = dict() + cloned_types = {} original_type = field.type_ if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"): original_type = original_type.__pydantic_model__ From f3e9dcd891342c3818781ebccb72f43edd71d9a6 Mon Sep 17 00:00:00 2001 From: Micael Jarniac Date: Fri, 26 Aug 2022 10:24:04 -0300 Subject: [PATCH 083/194] =?UTF-8?q?=E2=9C=8F=20Fix=20typo=20in=20`docs/en/?= =?UTF-8?q?docs/python-types.md`=20(#4886)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs/en/docs/python-types.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/python-types.md b/docs/en/docs/python-types.md index 3b0ee4cf6b1e4..87fdd6d8d15cc 100644 --- a/docs/en/docs/python-types.md +++ b/docs/en/docs/python-types.md @@ -158,7 +158,7 @@ The syntax using `typing` is **compatible** with all versions, from Python 3.6 t As Python advances, **newer versions** come with improved support for these type annotations and in many cases you won't even need to import and use the `typing` module to declare the type annotations. -If you can chose a more recent version of Python for your project, you will be able to take advantage of that extra simplicity. See some examples below. +If you can choose a more recent version of Python for your project, you will be able to take advantage of that extra simplicity. See some examples below. #### List From 3df68694c01b4f897519c63dddf2cd230fc17e40 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 26 Aug 2022 13:24:10 +0000 Subject: [PATCH 084/194] =?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 74efd542ffc20..9e3dba5e8dcb5 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* ♻ Change a `dict()` for `{}` in `fastapi/utils.py`. PR [#3138](https://github.com/tiangolo/fastapi/pull/3138) by [@ShahriyarR](https://github.com/ShahriyarR). * ♻ Move internal variable for errors in `jsonable_encoder` to put related code closer. PR [#4560](https://github.com/tiangolo/fastapi/pull/4560) by [@GuilleQP](https://github.com/GuilleQP). * ♻ Simplify conditional assignment in `fastapi/dependencies/utils.py`. PR [#4597](https://github.com/tiangolo/fastapi/pull/4597) by [@cikay](https://github.com/cikay). * 🎨 Fix syntax highlighting in docs for OpenAPI Callbacks. PR [#4368](https://github.com/tiangolo/fastapi/pull/4368) by [@xncbf](https://github.com/xncbf). From 26097421d3aeef032cbc97b9117594fdd31af6a5 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 26 Aug 2022 13:24:42 +0000 Subject: [PATCH 085/194] =?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 9e3dba5e8dcb5..fc4523537c927 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* ✏ Fix typo in `docs/en/docs/python-types.md`. PR [#4886](https://github.com/tiangolo/fastapi/pull/4886) by [@MicaelJarniac](https://github.com/MicaelJarniac). * ♻ Change a `dict()` for `{}` in `fastapi/utils.py`. PR [#3138](https://github.com/tiangolo/fastapi/pull/3138) by [@ShahriyarR](https://github.com/ShahriyarR). * ♻ Move internal variable for errors in `jsonable_encoder` to put related code closer. PR [#4560](https://github.com/tiangolo/fastapi/pull/4560) by [@GuilleQP](https://github.com/GuilleQP). * ♻ Simplify conditional assignment in `fastapi/dependencies/utils.py`. PR [#4597](https://github.com/tiangolo/fastapi/pull/4597) by [@cikay](https://github.com/cikay). From 8cd8aa4b67f06255bb0016cb478b7541766a8e31 Mon Sep 17 00:00:00 2001 From: Michael Oliver Date: Fri, 26 Aug 2022 14:25:02 +0100 Subject: [PATCH 086/194] =?UTF-8?q?=F0=9F=94=A7=20Update=20mypy=20config,?= =?UTF-8?q?=20use=20`strict=20=3D=20true`=20instead=20of=20manual=20config?= =?UTF-8?q?s=20(#4605)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- pyproject.toml | 16 +--------------- 1 file changed, 1 insertion(+), 15 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 9263985ce0e3a..3b77b113b9217 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -104,21 +104,7 @@ profile = "black" known_third_party = ["fastapi", "pydantic", "starlette"] [tool.mypy] -# --strict -disallow_any_generics = true -disallow_subclassing_any = true -disallow_untyped_calls = true -disallow_untyped_defs = true -disallow_incomplete_defs = true -check_untyped_defs = true -disallow_untyped_decorators = true -no_implicit_optional = true -warn_redundant_casts = true -warn_unused_ignores = true -warn_return_any = true -implicit_reexport = false -strict_equality = true -# --strict end +strict = true [[tool.mypy.overrides]] module = "fastapi.concurrency" From afe44f0b258d44822e77f9a9db965933b38add05 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 26 Aug 2022 13:25:48 +0000 Subject: [PATCH 087/194] =?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 fc4523537c927..ff2a7120ae5ce 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 🔧 Update mypy config, use `strict = true` instead of manual configs. PR [#4605](https://github.com/tiangolo/fastapi/pull/4605) by [@michaeloliverx](https://github.com/michaeloliverx). * ✏ Fix typo in `docs/en/docs/python-types.md`. PR [#4886](https://github.com/tiangolo/fastapi/pull/4886) by [@MicaelJarniac](https://github.com/MicaelJarniac). * ♻ Change a `dict()` for `{}` in `fastapi/utils.py`. PR [#3138](https://github.com/tiangolo/fastapi/pull/3138) by [@ShahriyarR](https://github.com/ShahriyarR). * ♻ Move internal variable for errors in `jsonable_encoder` to put related code closer. PR [#4560](https://github.com/tiangolo/fastapi/pull/4560) by [@GuilleQP](https://github.com/GuilleQP). From e3c055ba8f1339faa1b0d931069c028b4e36fa17 Mon Sep 17 00:00:00 2001 From: Micael Jarniac Date: Fri, 26 Aug 2022 10:26:03 -0300 Subject: [PATCH 088/194] =?UTF-8?q?=F0=9F=93=9D=20Update=20docs,=20compare?= =?UTF-8?q?=20enums=20with=20identity=20instead=20of=20equality=20(#4905)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs_src/path_params/tutorial005.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs_src/path_params/tutorial005.py b/docs_src/path_params/tutorial005.py index 8e376774492ce..9a24a4963a188 100644 --- a/docs_src/path_params/tutorial005.py +++ b/docs_src/path_params/tutorial005.py @@ -14,7 +14,7 @@ class ModelName(str, Enum): @app.get("/models/{model_name}") async def get_model(model_name: ModelName): - if model_name == ModelName.alexnet: + if model_name is ModelName.alexnet: return {"model_name": model_name, "message": "Deep Learning FTW!"} if model_name.value == "lenet": From aaf5a380df524a3254f7acb70dd17e160220b5b4 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 26 Aug 2022 13:27:07 +0000 Subject: [PATCH 089/194] =?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 ff2a7120ae5ce..cab55390e8c31 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 📝 Update docs, compare enums with identity instead of equality. PR [#4905](https://github.com/tiangolo/fastapi/pull/4905) by [@MicaelJarniac](https://github.com/MicaelJarniac). * 🔧 Update mypy config, use `strict = true` instead of manual configs. PR [#4605](https://github.com/tiangolo/fastapi/pull/4605) by [@michaeloliverx](https://github.com/michaeloliverx). * ✏ Fix typo in `docs/en/docs/python-types.md`. PR [#4886](https://github.com/tiangolo/fastapi/pull/4886) by [@MicaelJarniac](https://github.com/MicaelJarniac). * ♻ Change a `dict()` for `{}` in `fastapi/utils.py`. PR [#3138](https://github.com/tiangolo/fastapi/pull/3138) by [@ShahriyarR](https://github.com/ShahriyarR). From 0539dd9cd35b7eb3b19945c19c1dc569440c0ec1 Mon Sep 17 00:00:00 2001 From: David Kim Date: Fri, 26 Aug 2022 22:29:50 +0900 Subject: [PATCH 090/194] =?UTF-8?q?=F0=9F=94=A7=20Fix=20Type=20hint=20of?= =?UTF-8?q?=20`auto=5Ferror`=20which=20does=20not=20need=20to=20be=20`Opti?= =?UTF-8?q?onal[bool]`=20(#4933)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/security/oauth2.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fastapi/security/oauth2.py b/fastapi/security/oauth2.py index 888208c1501fc..653c3010e58a3 100644 --- a/fastapi/security/oauth2.py +++ b/fastapi/security/oauth2.py @@ -119,7 +119,7 @@ def __init__( flows: Union[OAuthFlowsModel, Dict[str, Dict[str, Any]]] = OAuthFlowsModel(), scheme_name: Optional[str] = None, description: Optional[str] = None, - auto_error: Optional[bool] = True + auto_error: bool = True ): self.model = OAuth2Model(flows=flows, description=description) self.scheme_name = scheme_name or self.__class__.__name__ From 96c3f44a0e2063199d798c685f562b15422f61e2 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 26 Aug 2022 13:30:28 +0000 Subject: [PATCH 091/194] =?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 cab55390e8c31..e90ff24637ae3 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 🔧 Fix Type hint of `auto_error` which does not need to be `Optional[bool]`. PR [#4933](https://github.com/tiangolo/fastapi/pull/4933) by [@DavidKimDY](https://github.com/DavidKimDY). * 📝 Update docs, compare enums with identity instead of equality. PR [#4905](https://github.com/tiangolo/fastapi/pull/4905) by [@MicaelJarniac](https://github.com/MicaelJarniac). * 🔧 Update mypy config, use `strict = true` instead of manual configs. PR [#4605](https://github.com/tiangolo/fastapi/pull/4605) by [@michaeloliverx](https://github.com/michaeloliverx). * ✏ Fix typo in `docs/en/docs/python-types.md`. PR [#4886](https://github.com/tiangolo/fastapi/pull/4886) by [@MicaelJarniac](https://github.com/MicaelJarniac). From dde140d8e35e82d56f5aa0064942da1e6c9cf238 Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Fri, 26 Aug 2022 08:32:30 -0500 Subject: [PATCH 092/194] =?UTF-8?q?=F0=9F=93=9D=20Simplify=20example=20for?= =?UTF-8?q?=20docs=20for=20Additional=20Responses,=20remove=20unnecessary?= =?UTF-8?q?=20`else`=20(#4693)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/advanced/additional-responses.md | 2 +- docs_src/additional_responses/tutorial001.py | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/docs/en/docs/advanced/additional-responses.md b/docs/en/docs/advanced/additional-responses.md index 5d136da41b02c..dca5f6a985cc1 100644 --- a/docs/en/docs/advanced/additional-responses.md +++ b/docs/en/docs/advanced/additional-responses.md @@ -23,7 +23,7 @@ Each of those response `dict`s can have a key `model`, containing a Pydantic mod For example, to declare another response with a status code `404` and a Pydantic model `Message`, you can write: -```Python hl_lines="18 23" +```Python hl_lines="18 22" {!../../../docs_src/additional_responses/tutorial001.py!} ``` diff --git a/docs_src/additional_responses/tutorial001.py b/docs_src/additional_responses/tutorial001.py index 79dcc2efee601..ffa821b910a84 100644 --- a/docs_src/additional_responses/tutorial001.py +++ b/docs_src/additional_responses/tutorial001.py @@ -19,5 +19,4 @@ class Message(BaseModel): async def read_item(item_id: str): if item_id == "foo": return {"id": "foo", "value": "there goes my hero"} - else: - return JSONResponse(status_code=404, content={"message": "Item not found"}) + return JSONResponse(status_code=404, content={"message": "Item not found"}) From d80b065b5e696d65fbd139c539266276e0d0817d Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 26 Aug 2022 13:33:08 +0000 Subject: [PATCH 093/194] =?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 e90ff24637ae3..9c61b19d80e6c 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 📝 Simplify example for docs for Additional Responses, remove unnecessary `else`. PR [#4693](https://github.com/tiangolo/fastapi/pull/4693) by [@adriangb](https://github.com/adriangb). * 🔧 Fix Type hint of `auto_error` which does not need to be `Optional[bool]`. PR [#4933](https://github.com/tiangolo/fastapi/pull/4933) by [@DavidKimDY](https://github.com/DavidKimDY). * 📝 Update docs, compare enums with identity instead of equality. PR [#4905](https://github.com/tiangolo/fastapi/pull/4905) by [@MicaelJarniac](https://github.com/MicaelJarniac). * 🔧 Update mypy config, use `strict = true` instead of manual configs. PR [#4605](https://github.com/tiangolo/fastapi/pull/4605) by [@michaeloliverx](https://github.com/michaeloliverx). From a95212565a63c8fdfd75785fd3b88499697e2c02 Mon Sep 17 00:00:00 2001 From: LYK Date: Fri, 26 Aug 2022 22:44:02 +0900 Subject: [PATCH 094/194] =?UTF-8?q?=F0=9F=8C=90=20Update=20`ko/mkdocs.yml`?= =?UTF-8?q?=20for=20a=20missing=20link=20(#5020)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez From 1f2070af20f889c956b13aa79313532cf0956b71 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 26 Aug 2022 13:44:50 +0000 Subject: [PATCH 095/194] =?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 9c61b19d80e6c..fe3a0961b4f51 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 🌐 Update `ko/mkdocs.yml` for a missing link. PR [#5020](https://github.com/tiangolo/fastapi/pull/5020) by [@dalinaum](https://github.com/dalinaum). * 📝 Simplify example for docs for Additional Responses, remove unnecessary `else`. PR [#4693](https://github.com/tiangolo/fastapi/pull/4693) by [@adriangb](https://github.com/adriangb). * 🔧 Fix Type hint of `auto_error` which does not need to be `Optional[bool]`. PR [#4933](https://github.com/tiangolo/fastapi/pull/4933) by [@DavidKimDY](https://github.com/DavidKimDY). * 📝 Update docs, compare enums with identity instead of equality. PR [#4905](https://github.com/tiangolo/fastapi/pull/4905) by [@MicaelJarniac](https://github.com/MicaelJarniac). From dc10b81d05fc4438038d74543333661073bf7c8a Mon Sep 17 00:00:00 2001 From: pylounge <78209508+pylounge@users.noreply.github.com> Date: Fri, 26 Aug 2022 16:46:22 +0300 Subject: [PATCH 096/194] =?UTF-8?q?=E2=99=BB=20Simplify=20internal=20RegEx?= =?UTF-8?q?=20in=20`fastapi/utils.py`=20(#5057)?= 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> --- fastapi/utils.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/fastapi/utils.py b/fastapi/utils.py index b7da3e484240c..0ced0125223a4 100644 --- a/fastapi/utils.py +++ b/fastapi/utils.py @@ -140,14 +140,14 @@ def generate_operation_id_for_path( stacklevel=2, ) operation_id = name + path - operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) + operation_id = re.sub(r"\W", "_", operation_id) operation_id = operation_id + "_" + method.lower() return operation_id def generate_unique_id(route: "APIRoute") -> str: operation_id = route.name + route.path_format - operation_id = re.sub("[^0-9a-zA-Z_]", "_", operation_id) + operation_id = re.sub(r"\W", "_", operation_id) assert route.methods operation_id = operation_id + "_" + list(route.methods)[0].lower() return operation_id From 26c68c6e0d95ff7b915365c9e78c2da93538f011 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 26 Aug 2022 13:47:11 +0000 Subject: [PATCH 097/194] =?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 fe3a0961b4f51..bd2d78fa1677d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* ♻ Simplify internal RegEx in `fastapi/utils.py`. PR [#5057](https://github.com/tiangolo/fastapi/pull/5057) by [@pylounge](https://github.com/pylounge). * 🌐 Update `ko/mkdocs.yml` for a missing link. PR [#5020](https://github.com/tiangolo/fastapi/pull/5020) by [@dalinaum](https://github.com/dalinaum). * 📝 Simplify example for docs for Additional Responses, remove unnecessary `else`. PR [#4693](https://github.com/tiangolo/fastapi/pull/4693) by [@adriangb](https://github.com/adriangb). * 🔧 Fix Type hint of `auto_error` which does not need to be `Optional[bool]`. PR [#4933](https://github.com/tiangolo/fastapi/pull/4933) by [@DavidKimDY](https://github.com/DavidKimDY). From de6ccd77544b0c6e5bdcf2f470e6fd1a068344ef Mon Sep 17 00:00:00 2001 From: Erik Vroon Date: Fri, 26 Aug 2022 06:56:07 -0700 Subject: [PATCH 098/194] =?UTF-8?q?=E2=9C=A8=20Add=20ReDoc=20`
-
+
From 173b8916034d15bd96084e60b05f7713f3e92713 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 2 Sep 2022 09:53:06 +0000 Subject: [PATCH 141/194] =?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 1e5dd927f02a9..2423277870084 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 🔧 Update sponsors, disable ImgWhale. PR [#5338](https://github.com/tiangolo/fastapi/pull/5338) by [@tiangolo](https://github.com/tiangolo). * 📝 Update docs for `ORJSONResponse` with details about improving performance. PR [#2615](https://github.com/tiangolo/fastapi/pull/2615) by [@falkben](https://github.com/falkben). * 📝 Add docs for creating a custom Response class. PR [#5331](https://github.com/tiangolo/fastapi/pull/5331) by [@tiangolo](https://github.com/tiangolo). * 📝 Add tip about using alias for form data fields. PR [#5329](https://github.com/tiangolo/fastapi/pull/5329) by [@tiangolo](https://github.com/tiangolo). From 7250c194da6fae6155817c4b30bcdd112acce655 Mon Sep 17 00:00:00 2001 From: "abc.zxy" Date: Fri, 2 Sep 2022 18:17:31 +0800 Subject: [PATCH 142/194] =?UTF-8?q?=E2=9C=A8=20Update=20`ORJSONResponse`?= =?UTF-8?q?=20to=20support=20non=20`str`=20keys=20and=20serializing=20Nump?= =?UTF-8?q?y=20arrays=20(#3892)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- fastapi/responses.py | 4 +++- tests/test_orjson_response_class.py | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 tests/test_orjson_response_class.py diff --git a/fastapi/responses.py b/fastapi/responses.py index 6cd7931571fc9..88dba96e8f566 100644 --- a/fastapi/responses.py +++ b/fastapi/responses.py @@ -31,4 +31,6 @@ class ORJSONResponse(JSONResponse): def render(self, content: Any) -> bytes: assert orjson is not None, "orjson must be installed to use ORJSONResponse" - return orjson.dumps(content) + return orjson.dumps( + content, option=orjson.OPT_NON_STR_KEYS | orjson.OPT_SERIALIZE_NUMPY + ) diff --git a/tests/test_orjson_response_class.py b/tests/test_orjson_response_class.py new file mode 100644 index 0000000000000..6fe62daf97b4e --- /dev/null +++ b/tests/test_orjson_response_class.py @@ -0,0 +1,21 @@ +from fastapi import FastAPI +from fastapi.responses import ORJSONResponse +from fastapi.testclient import TestClient +from sqlalchemy.sql.elements import quoted_name + +app = FastAPI(default_response_class=ORJSONResponse) + + +@app.get("/orjson_non_str_keys") +def get_orjson_non_str_keys(): + key = quoted_name(value="msg", quote=False) + return {key: "Hello World", 1: 1} + + +client = TestClient(app) + + +def test_orjson_non_str_keys(): + with client: + response = client.get("/orjson_non_str_keys") + assert response.json() == {"msg": "Hello World", "1": 1} From b1d0f1e9703b8f163896864e1eef7faf4a7ce661 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 2 Sep 2022 10:18:09 +0000 Subject: [PATCH 143/194] =?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 2423277870084..7ce9a74e9bade 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* ✨ Update `ORJSONResponse` to support non `str` keys and serializing Numpy arrays. PR [#3892](https://github.com/tiangolo/fastapi/pull/3892) by [@baby5](https://github.com/baby5). * 🔧 Update sponsors, disable ImgWhale. PR [#5338](https://github.com/tiangolo/fastapi/pull/5338) by [@tiangolo](https://github.com/tiangolo). * 📝 Update docs for `ORJSONResponse` with details about improving performance. PR [#2615](https://github.com/tiangolo/fastapi/pull/2615) by [@falkben](https://github.com/falkben). * 📝 Add docs for creating a custom Response class. PR [#5331](https://github.com/tiangolo/fastapi/pull/5331) by [@tiangolo](https://github.com/tiangolo). From 30b3905ef38532c867036c1b650a9ceef5bfb1cc Mon Sep 17 00:00:00 2001 From: Marcelo Trylesinski Date: Fri, 2 Sep 2022 14:43:21 +0200 Subject: [PATCH 144/194] =?UTF-8?q?=E2=9C=A8=20Support=20Python=20internal?= =?UTF-8?q?=20description=20on=20Pydantic=20model's=20docstring=20(#3032)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- fastapi/utils.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/fastapi/utils.py b/fastapi/utils.py index 0ced0125223a4..89f54453b5a90 100644 --- a/fastapi/utils.py +++ b/fastapi/utils.py @@ -37,6 +37,8 @@ def get_model_definitions( ) definitions.update(m_definitions) model_name = model_name_map[model] + if "description" in m_schema: + m_schema["description"] = m_schema["description"].split("\f")[0] definitions[model_name] = m_schema return definitions From e7e6404faf41836bc74978714381c2587b53c0c3 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 2 Sep 2022 12:44:09 +0000 Subject: [PATCH 145/194] =?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 7ce9a74e9bade..7f2cc6df28b4d 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* ✨ Support Python internal description on Pydantic model's docstring. PR [#3032](https://github.com/tiangolo/fastapi/pull/3032) by [@Kludex](https://github.com/Kludex). * ✨ Update `ORJSONResponse` to support non `str` keys and serializing Numpy arrays. PR [#3892](https://github.com/tiangolo/fastapi/pull/3892) by [@baby5](https://github.com/baby5). * 🔧 Update sponsors, disable ImgWhale. PR [#5338](https://github.com/tiangolo/fastapi/pull/5338) by [@tiangolo](https://github.com/tiangolo). * 📝 Update docs for `ORJSONResponse` with details about improving performance. PR [#2615](https://github.com/tiangolo/fastapi/pull/2615) by [@falkben](https://github.com/falkben). From 52b5b08910356b22cb9837bda88f73f517dd8652 Mon Sep 17 00:00:00 2001 From: Junghoon Yang Date: Fri, 2 Sep 2022 22:36:00 +0900 Subject: [PATCH 146/194] =?UTF-8?q?=E2=99=BB=20Internal=20small=20refactor?= =?UTF-8?q?,=20move=20`operation=5Fid`=20parameter=20position=20in=20delet?= =?UTF-8?q?e=20method=20for=20consistency=20with=20the=20code=20(#4474)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- fastapi/applications.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fastapi/applications.py b/fastapi/applications.py index ac6050ca4ff56..a242c504c15db 100644 --- a/fastapi/applications.py +++ b/fastapi/applications.py @@ -635,10 +635,10 @@ def delete( response_description=response_description, responses=responses, deprecated=deprecated, + operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, - operation_id=operation_id, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, From fbe1a803fc98901a273177d06c4fa8ccb2bcd635 Mon Sep 17 00:00:00 2001 From: github-actions Date: Fri, 2 Sep 2022 13:36:48 +0000 Subject: [PATCH 147/194] =?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 7f2cc6df28b4d..7b956f3f7ea5f 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* ♻ Internal small refactor, move `operation_id` parameter position in delete method for consistency with the code. PR [#4474](https://github.com/tiangolo/fastapi/pull/4474) by [@hiel](https://github.com/hiel). * ✨ Support Python internal description on Pydantic model's docstring. PR [#3032](https://github.com/tiangolo/fastapi/pull/3032) by [@Kludex](https://github.com/Kludex). * ✨ Update `ORJSONResponse` to support non `str` keys and serializing Numpy arrays. PR [#3892](https://github.com/tiangolo/fastapi/pull/3892) by [@baby5](https://github.com/baby5). * 🔧 Update sponsors, disable ImgWhale. PR [#5338](https://github.com/tiangolo/fastapi/pull/5338) by [@tiangolo](https://github.com/tiangolo). From 56f887de15f25157114820d0d5c5ed5e606d53f0 Mon Sep 17 00:00:00 2001 From: Charlie DiGiovanna Date: Sat, 3 Sep 2022 13:12:41 -0400 Subject: [PATCH 148/194] =?UTF-8?q?=F0=9F=90=9B=20Make=20sure=20a=20parame?= =?UTF-8?q?ter=20defined=20as=20required=20is=20kept=20required=20in=20Ope?= =?UTF-8?q?nAPI=20even=20if=20defined=20as=20optional=20in=20another=20dep?= =?UTF-8?q?endency=20(#4319)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- fastapi/openapi/utils.py | 17 ++- tests/test_enforce_once_required_parameter.py | 111 ++++++++++++++++++ 2 files changed, 123 insertions(+), 5 deletions(-) create mode 100644 tests/test_enforce_once_required_parameter.py diff --git a/fastapi/openapi/utils.py b/fastapi/openapi/utils.py index 4d5741f30de1c..86e15b46d30a3 100644 --- a/fastapi/openapi/utils.py +++ b/fastapi/openapi/utils.py @@ -222,11 +222,18 @@ def get_openapi_path( ) parameters.extend(operation_parameters) if parameters: - operation["parameters"] = list( - { - (param["in"], param["name"]): param for param in parameters - }.values() - ) + all_parameters = { + (param["in"], param["name"]): param for param in parameters + } + required_parameters = { + (param["in"], param["name"]): param + for param in parameters + if param.get("required") + } + # Make sure required definitions of the same parameter take precedence + # over non-required definitions + all_parameters.update(required_parameters) + operation["parameters"] = list(all_parameters.values()) if method in METHODS_WITH_BODY: request_body_oai = get_openapi_operation_request_body( body_field=route.body_field, model_name_map=model_name_map diff --git a/tests/test_enforce_once_required_parameter.py b/tests/test_enforce_once_required_parameter.py new file mode 100644 index 0000000000000..ba8c7353fa97f --- /dev/null +++ b/tests/test_enforce_once_required_parameter.py @@ -0,0 +1,111 @@ +from typing import Optional + +from fastapi import Depends, FastAPI, Query, status +from fastapi.testclient import TestClient + +app = FastAPI() + + +def _get_client_key(client_id: str = Query(...)) -> str: + return f"{client_id}_key" + + +def _get_client_tag(client_id: Optional[str] = Query(None)) -> Optional[str]: + if client_id is None: + return None + return f"{client_id}_tag" + + +@app.get("/foo") +def foo_handler( + client_key: str = Depends(_get_client_key), + client_tag: Optional[str] = Depends(_get_client_tag), +): + return {"client_id": client_key, "client_tag": client_tag} + + +client = TestClient(app) + +expected_schema = { + "components": { + "schemas": { + "HTTPValidationError": { + "properties": { + "detail": { + "items": {"$ref": "#/components/schemas/ValidationError"}, + "title": "Detail", + "type": "array", + } + }, + "title": "HTTPValidationError", + "type": "object", + }, + "ValidationError": { + "properties": { + "loc": { + "items": {"anyOf": [{"type": "string"}, {"type": "integer"}]}, + "title": "Location", + "type": "array", + }, + "msg": {"title": "Message", "type": "string"}, + "type": {"title": "Error " "Type", "type": "string"}, + }, + "required": ["loc", "msg", "type"], + "title": "ValidationError", + "type": "object", + }, + } + }, + "info": {"title": "FastAPI", "version": "0.1.0"}, + "openapi": "3.0.2", + "paths": { + "/foo": { + "get": { + "operationId": "foo_handler_foo_get", + "parameters": [ + { + "in": "query", + "name": "client_id", + "required": True, + "schema": {"title": "Client Id", "type": "string"}, + }, + ], + "responses": { + "200": { + "content": {"application/json": {"schema": {}}}, + "description": "Successful " "Response", + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation " "Error", + }, + }, + "summary": "Foo Handler", + } + } + }, +} + + +def test_schema(): + response = client.get("/openapi.json") + assert response.status_code == status.HTTP_200_OK + actual_schema = response.json() + assert actual_schema == expected_schema + + +def test_get_invalid(): + response = client.get("/foo", params={"client_id": None}) + assert response.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY + + +def test_get_valid(): + response = client.get("/foo", params={"client_id": "bar"}) + assert response.status_code == 200 + assert response.json() == {"client_id": "bar_key", "client_tag": "bar_tag"} From dbb43da9c00380d4cfee6e6fb01853eb2dfb0189 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sat, 3 Sep 2022 17:13:24 +0000 Subject: [PATCH 149/194] =?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 7b956f3f7ea5f..8acf8d0048c01 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 🐛 Make sure a parameter defined as required is kept required in OpenAPI even if defined as optional in another dependency. PR [#4319](https://github.com/tiangolo/fastapi/pull/4319) by [@cd17822](https://github.com/cd17822). * ♻ Internal small refactor, move `operation_id` parameter position in delete method for consistency with the code. PR [#4474](https://github.com/tiangolo/fastapi/pull/4474) by [@hiel](https://github.com/hiel). * ✨ Support Python internal description on Pydantic model's docstring. PR [#3032](https://github.com/tiangolo/fastapi/pull/3032) by [@Kludex](https://github.com/Kludex). * ✨ Update `ORJSONResponse` to support non `str` keys and serializing Numpy arrays. PR [#3892](https://github.com/tiangolo/fastapi/pull/3892) by [@baby5](https://github.com/baby5). From 0e7478d39c503a6ed472503a24a06d7ec9bbf013 Mon Sep 17 00:00:00 2001 From: sjyothi54 <99384747+sjyothi54@users.noreply.github.com> Date: Sun, 4 Sep 2022 18:31:08 +0530 Subject: [PATCH 150/194] =?UTF-8?q?=F0=9F=93=9D=20Add=20link=20to=20New=20?= =?UTF-8?q?Relic=20article:=20"How=20to=20monitor=20FastAPI=20application?= =?UTF-8?q?=20performance=20using=20Python=20agent"=20(#5260)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs/en/data/external_links.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/en/data/external_links.yml b/docs/en/data/external_links.yml index e7bd0530bdcdd..e9c4ef2f247c3 100644 --- a/docs/en/data/external_links.yml +++ b/docs/en/data/external_links.yml @@ -1,5 +1,9 @@ articles: english: + - author: New Relic + author_link: https://newrelic.com + link: https://newrelic.com/instant-observability/fastapi/e559ec64-f765-4470-a15f-1901fcebb468 + title: How to monitor FastAPI application performance using Python agent - author: Jean-Baptiste Rocher author_link: https://hashnode.com/@jibrocher link: https://dev.indooroutdoor.io/series/fastapi-react-poll-app From fae28a9bd7f806d1bd2c01f053ea6c9a297fd4a6 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 4 Sep 2022 13:01:40 +0000 Subject: [PATCH 151/194] =?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 8acf8d0048c01..f9b90f05cf476 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 📝 Add link to New Relic article: "How to monitor FastAPI application performance using Python agent". PR [#5260](https://github.com/tiangolo/fastapi/pull/5260) by [@sjyothi54](https://github.com/sjyothi54). * 🐛 Make sure a parameter defined as required is kept required in OpenAPI even if defined as optional in another dependency. PR [#4319](https://github.com/tiangolo/fastapi/pull/4319) by [@cd17822](https://github.com/cd17822). * ♻ Internal small refactor, move `operation_id` parameter position in delete method for consistency with the code. PR [#4474](https://github.com/tiangolo/fastapi/pull/4474) by [@hiel](https://github.com/hiel). * ✨ Support Python internal description on Pydantic model's docstring. PR [#3032](https://github.com/tiangolo/fastapi/pull/3032) by [@Kludex](https://github.com/Kludex). From d3ff7c620aa7b07acec0eedd1139f24ffa86b97c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=9D=9E=E6=B3=95=E6=93=8D=E4=BD=9C?= Date: Sun, 4 Sep 2022 21:18:08 +0800 Subject: [PATCH 152/194] =?UTF-8?q?=E2=9C=8F=20Fix=20a=20small=20code=20hi?= =?UTF-8?q?ghlight=20line=20error=20(#5256)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/query-params-str-validations.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/tutorial/query-params-str-validations.md b/docs/en/docs/tutorial/query-params-str-validations.md index c5fc35b88aeff..060e1d58a4232 100644 --- a/docs/en/docs/tutorial/query-params-str-validations.md +++ b/docs/en/docs/tutorial/query-params-str-validations.md @@ -216,7 +216,7 @@ To do that, you can declare that `None` is a valid type but still use `default=. === "Python 3.6 and above" - ```Python hl_lines="8" + ```Python hl_lines="9" {!> ../../../docs_src/query_params_str_validations/tutorial006c.py!} ``` From c00e1ec6bff30c98201d823467c67db51d1479ea Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 4 Sep 2022 13:18:44 +0000 Subject: [PATCH 153/194] =?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 f9b90f05cf476..224ac9a52f555 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* ✏ Fix a small code highlight line error. PR [#5256](https://github.com/tiangolo/fastapi/pull/5256) by [@hjlarry](https://github.com/hjlarry). * 📝 Add link to New Relic article: "How to monitor FastAPI application performance using Python agent". PR [#5260](https://github.com/tiangolo/fastapi/pull/5260) by [@sjyothi54](https://github.com/sjyothi54). * 🐛 Make sure a parameter defined as required is kept required in OpenAPI even if defined as optional in another dependency. PR [#4319](https://github.com/tiangolo/fastapi/pull/4319) by [@cd17822](https://github.com/cd17822). * ♻ Internal small refactor, move `operation_id` parameter position in delete method for consistency with the code. PR [#4474](https://github.com/tiangolo/fastapi/pull/4474) by [@hiel](https://github.com/hiel). From 68e04f653143ea4836a2b536cd74d0b36af36693 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1rio=20Victor=20Ribeiro=20Silva?= Date: Sun, 4 Sep 2022 10:23:34 -0300 Subject: [PATCH 154/194] =?UTF-8?q?=F0=9F=8C=90=20Fix=20MkDocs=20file=20li?= =?UTF-8?q?ne=20for=20Portuguese=20translation=20of=20`background-task.md`?= =?UTF-8?q?=20(#5242)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- docs/pt/mkdocs.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/pt/mkdocs.yml b/docs/pt/mkdocs.yml index 5e4ceb66f8522..59ee3cc88aabe 100644 --- a/docs/pt/mkdocs.yml +++ b/docs/pt/mkdocs.yml @@ -74,6 +74,7 @@ nav: - tutorial/handling-errors.md - Segurança: - tutorial/security/index.md + - tutorial/background-tasks.md - Guia de Usuário Avançado: - advanced/index.md - Implantação: From 198b7ef2cb9bf6e5ab0b13819197b39aa80229ca Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 4 Sep 2022 13:24:23 +0000 Subject: [PATCH 155/194] =?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 224ac9a52f555..5d359dddc5d83 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 🌐 Fix MkDocs file line for Portuguese translation of `background-task.md`. PR [#5242](https://github.com/tiangolo/fastapi/pull/5242) by [@ComicShrimp](https://github.com/ComicShrimp). * ✏ Fix a small code highlight line error. PR [#5256](https://github.com/tiangolo/fastapi/pull/5256) by [@hjlarry](https://github.com/hjlarry). * 📝 Add link to New Relic article: "How to monitor FastAPI application performance using Python agent". PR [#5260](https://github.com/tiangolo/fastapi/pull/5260) by [@sjyothi54](https://github.com/sjyothi54). * 🐛 Make sure a parameter defined as required is kept required in OpenAPI even if defined as optional in another dependency. PR [#4319](https://github.com/tiangolo/fastapi/pull/4319) by [@cd17822](https://github.com/cd17822). From ae369d879af021fa3477a39155981f346578a078 Mon Sep 17 00:00:00 2001 From: MendyLanda <54242706+MendyLanda@users.noreply.github.com> Date: Sun, 4 Sep 2022 09:29:06 -0400 Subject: [PATCH 156/194] =?UTF-8?q?=F0=9F=93=9D=20Add=20note=20about=20Pyt?= =?UTF-8?q?hon=203.10=20`X=20|=20Y`=20operator=20in=20explanation=20about?= =?UTF-8?q?=20Response=20Models=20(#5307)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/tutorial/response-model.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/tutorial/response-model.md b/docs/en/docs/tutorial/response-model.md index 2bbd4d4fd5090..ab68314e851c9 100644 --- a/docs/en/docs/tutorial/response-model.md +++ b/docs/en/docs/tutorial/response-model.md @@ -168,7 +168,7 @@ Your response model could have default values, like: {!> ../../../docs_src/response_model/tutorial004_py310.py!} ``` -* `description: Union[str, None] = None` has a default of `None`. +* `description: Union[str, None] = None` (or `str | None = None` in Python 3.10) has a default of `None`. * `tax: float = 10.5` has a default of `10.5`. * `tags: List[str] = []` as a default of an empty list: `[]`. From 697ec94a7e90a0798cdcd3c83fa230aba0b2a3a2 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 4 Sep 2022 13:29:46 +0000 Subject: [PATCH 157/194] =?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 5d359dddc5d83..ab431c379f8cb 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 📝 Add note about Python 3.10 `X | Y` operator in explanation about Response Models. PR [#5307](https://github.com/tiangolo/fastapi/pull/5307) by [@MendyLanda](https://github.com/MendyLanda). * 🌐 Fix MkDocs file line for Portuguese translation of `background-task.md`. PR [#5242](https://github.com/tiangolo/fastapi/pull/5242) by [@ComicShrimp](https://github.com/ComicShrimp). * ✏ Fix a small code highlight line error. PR [#5256](https://github.com/tiangolo/fastapi/pull/5256) by [@hjlarry](https://github.com/hjlarry). * 📝 Add link to New Relic article: "How to monitor FastAPI application performance using Python agent". PR [#5260](https://github.com/tiangolo/fastapi/pull/5260) by [@sjyothi54](https://github.com/sjyothi54). From f266dc17d7a3e6e9d2de0ff3d5b54bea8b7874ba Mon Sep 17 00:00:00 2001 From: Peter Fackeldey Date: Sun, 4 Sep 2022 15:37:47 +0200 Subject: [PATCH 158/194] =?UTF-8?q?=E2=9C=8F=20Tweak=20wording=20in=20`doc?= =?UTF-8?q?s/en/docs/advanced/dataclasses.md`=20(#3698)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/advanced/dataclasses.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/en/docs/advanced/dataclasses.md b/docs/en/docs/advanced/dataclasses.md index 80a063bb875a2..72daca06ad9f7 100644 --- a/docs/en/docs/advanced/dataclasses.md +++ b/docs/en/docs/advanced/dataclasses.md @@ -8,7 +8,7 @@ But FastAPI also supports using internal support for `dataclasses`. +This is still supported thanks to **Pydantic**, as it has internal support for `dataclasses`. So, even with the code above that doesn't use Pydantic explicitly, FastAPI is using Pydantic to convert those standard dataclasses to Pydantic's own flavor of dataclasses. From 89839eb83470b42b96cd285c2764577b9409aade Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 4 Sep 2022 13:38:49 +0000 Subject: [PATCH 159/194] =?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 ab431c379f8cb..9f3e2f7b5f095 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* ✏ Tweak wording in `docs/en/docs/advanced/dataclasses.md`. PR [#3698](https://github.com/tiangolo/fastapi/pull/3698) by [@pfackeldey](https://github.com/pfackeldey). * 📝 Add note about Python 3.10 `X | Y` operator in explanation about Response Models. PR [#5307](https://github.com/tiangolo/fastapi/pull/5307) by [@MendyLanda](https://github.com/MendyLanda). * 🌐 Fix MkDocs file line for Portuguese translation of `background-task.md`. PR [#5242](https://github.com/tiangolo/fastapi/pull/5242) by [@ComicShrimp](https://github.com/ComicShrimp). * ✏ Fix a small code highlight line error. PR [#5256](https://github.com/tiangolo/fastapi/pull/5256) by [@hjlarry](https://github.com/hjlarry). From 0d43b6552b30bb81d2f62536cc4faa5aa4251e64 Mon Sep 17 00:00:00 2001 From: Zssaer <45691504+Zssaer@users.noreply.github.com> Date: Sun, 4 Sep 2022 21:39:06 +0800 Subject: [PATCH 160/194] =?UTF-8?q?=F0=9F=8C=90=20Add=20Chinese=20translat?= =?UTF-8?q?ion=20for=20`docs/zh/docs/tutorial/encoder.md`=20(#4969)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/zh/docs/tutorial/encoder.md | 42 ++++++++++++++++++++++++++++++++ docs/zh/mkdocs.yml | 1 + 2 files changed, 43 insertions(+) create mode 100644 docs/zh/docs/tutorial/encoder.md diff --git a/docs/zh/docs/tutorial/encoder.md b/docs/zh/docs/tutorial/encoder.md new file mode 100644 index 0000000000000..cb813940ce252 --- /dev/null +++ b/docs/zh/docs/tutorial/encoder.md @@ -0,0 +1,42 @@ +# JSON 兼容编码器 + +在某些情况下,您可能需要将数据类型(如Pydantic模型)转换为与JSON兼容的数据类型(如`dict`、`list`等)。 + +比如,如果您需要将其存储在数据库中。 + +对于这种要求, **FastAPI**提供了`jsonable_encoder()`函数。 + +## 使用`jsonable_encoder` + +让我们假设你有一个数据库名为`fake_db`,它只能接收与JSON兼容的数据。 + +例如,它不接收`datetime`这类的对象,因为这些对象与JSON不兼容。 + +因此,`datetime`对象必须将转换为包含ISO格式化的`str`类型对象。 + +同样,这个数据库也不会接收Pydantic模型(带有属性的对象),而只接收`dict`。 + +对此你可以使用`jsonable_encoder`。 + +它接收一个对象,比如Pydantic模型,并会返回一个JSON兼容的版本: + +=== "Python 3.6 and above" + + ```Python hl_lines="5 22" + {!> ../../../docs_src/encoder/tutorial001.py!} + ``` + +=== "Python 3.10 and above" + + ```Python hl_lines="4 21" + {!> ../../../docs_src/encoder/tutorial001_py310.py!} + ``` + +在这个例子中,它将Pydantic模型转换为`dict`,并将`datetime`转换为`str`。 + +调用它的结果后就可以使用Python标准编码中的`json.dumps()`。 + +这个操作不会返回一个包含JSON格式(作为字符串)数据的庞大的`str`。它将返回一个Python标准数据结构(例如`dict`),其值和子值都与JSON兼容。 + +!!! note + `jsonable_encoder`实际上是FastAPI内部用来转换数据的。但是它在许多其他场景中也很有用。 diff --git a/docs/zh/mkdocs.yml b/docs/zh/mkdocs.yml index b60a0b7a188b5..ac8679dc0d2e2 100644 --- a/docs/zh/mkdocs.yml +++ b/docs/zh/mkdocs.yml @@ -85,6 +85,7 @@ nav: - tutorial/request-forms-and-files.md - tutorial/handling-errors.md - tutorial/path-operation-configuration.md + - tutorial/encoder.md - tutorial/body-updates.md - 依赖项: - tutorial/dependencies/index.md From fc559b5fcdfb0676e4534fb47a319f015db3cb43 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 4 Sep 2022 13:39:50 +0000 Subject: [PATCH 161/194] =?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 9f3e2f7b5f095..755f315dc40ff 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 🌐 Add Chinese translation for `docs/zh/docs/tutorial/encoder.md`. PR [#4969](https://github.com/tiangolo/fastapi/pull/4969) by [@Zssaer](https://github.com/Zssaer). * ✏ Tweak wording in `docs/en/docs/advanced/dataclasses.md`. PR [#3698](https://github.com/tiangolo/fastapi/pull/3698) by [@pfackeldey](https://github.com/pfackeldey). * 📝 Add note about Python 3.10 `X | Y` operator in explanation about Response Models. PR [#5307](https://github.com/tiangolo/fastapi/pull/5307) by [@MendyLanda](https://github.com/MendyLanda). * 🌐 Fix MkDocs file line for Portuguese translation of `background-task.md`. PR [#5242](https://github.com/tiangolo/fastapi/pull/5242) by [@ComicShrimp](https://github.com/ComicShrimp). From dc1534736d37a03b352eedd22e5d76e55209fb49 Mon Sep 17 00:00:00 2001 From: ASpathfinder <31813636+ASpathfinder@users.noreply.github.com> Date: Sun, 4 Sep 2022 21:40:14 +0800 Subject: [PATCH 162/194] =?UTF-8?q?=F0=9F=8C=90=20Update=20Chinese=20trans?= =?UTF-8?q?lation=20for=20`docs/zh/docs/tutorial/request-files.md`=20(#452?= =?UTF-8?q?9)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: KellyAlsa-massive-win Co-authored-by: Sebastián Ramírez --- docs/zh/docs/tutorial/request-files.md | 63 +++++++++++++++++++++----- 1 file changed, 52 insertions(+), 11 deletions(-) diff --git a/docs/zh/docs/tutorial/request-files.md b/docs/zh/docs/tutorial/request-files.md index 25657d93bd74a..e18d6fc9f3b60 100644 --- a/docs/zh/docs/tutorial/request-files.md +++ b/docs/zh/docs/tutorial/request-files.md @@ -44,9 +44,9 @@ 不过,很多情况下,`UploadFile` 更好用。 -## 含 `UploadFile` 的 `File` 参数 +## 含 `UploadFile` 的文件参数 -定义 `File` 参数时使用 `UploadFile`: +定义文件参数时使用 `UploadFile`: ```Python hl_lines="12" {!../../../docs_src/request_files/tutorial001.py!} @@ -94,7 +94,7 @@ contents = myfile.file.read() !!! note "`async` 技术细节" - 使用 `async` 方法时,**FastAPI** 在线程池中执行文件方法,并 `awiat` 操作完成。 + 使用 `async` 方法时,**FastAPI** 在线程池中执行文件方法,并 `await` 操作完成。 !!! note "Starlette 技术细节" @@ -120,6 +120,30 @@ contents = myfile.file.read() 这不是 **FastAPI** 的问题,而是 HTTP 协议的规定。 +## 可选文件上传 + +您可以通过使用标准类型注解并将 None 作为默认值的方式将一个文件参数设为可选: + +=== "Python 3.6 及以上版本" + + ```Python hl_lines="9 17" + {!> ../../../docs_src/request_files/tutorial001_02.py!} + ``` + +=== "Python 3.9 及以上版本" + + ```Python hl_lines="7 14" + {!> ../../../docs_src/request_files/tutorial001_02_py310.py!} + ``` + +## 带有额外元数据的 `UploadFile` + +您也可以将 `File()` 与 `UploadFile` 一起使用,例如,设置额外的元数据: + +```Python hl_lines="13" +{!../../../docs_src/request_files/tutorial001_03.py!} +``` + ## 多文件上传 FastAPI 支持同时上传多个文件。 @@ -128,19 +152,20 @@ FastAPI 支持同时上传多个文件。 上传多个文件时,要声明含 `bytes` 或 `UploadFile` 的列表(`List`): -```Python hl_lines="10 15" -{!../../../docs_src/request_files/tutorial002.py!} -``` +=== "Python 3.6 及以上版本" -接收的也是含 `bytes` 或 `UploadFile` 的列表(`list`)。 + ```Python hl_lines="10 15" + {!> ../../../docs_src/request_files/tutorial002.py!} + ``` -!!! note "笔记" +=== "Python 3.9 及以上版本" - 注意,截至 2019 年 4 月 14 日,Swagger UI 不支持在同一个表单字段中上传多个文件。详见 #4276#3641. + ```Python hl_lines="8 13" + {!> ../../../docs_src/request_files/tutorial002_py39.py!} + ``` - 不过,**FastAPI** 已通过 OpenAPI 标准与之兼容。 +接收的也是含 `bytes` 或 `UploadFile` 的列表(`list`)。 - 因此,只要 Swagger UI 或任何其他支持 OpenAPI 的工具支持多文件上传,都将与 **FastAPI** 兼容。 !!! note "技术细节" @@ -148,6 +173,22 @@ FastAPI 支持同时上传多个文件。 `fastapi.responses` 其实与 `starlette.responses` 相同,只是为了方便开发者调用。实际上,大多数 **FastAPI** 的响应都直接从 Starlette 调用。 +### 带有额外元数据的多文件上传 + +和之前的方式一样, 您可以为 `File()` 设置额外参数, 即使是 `UploadFile`: + +=== "Python 3.6 及以上版本" + + ```Python hl_lines="18" + {!> ../../../docs_src/request_files/tutorial003.py!} + ``` + +=== "Python 3.9 及以上版本" + + ```Python hl_lines="16" + {!> ../../../docs_src/request_files/tutorial003_py39.py!} + ``` + ## 小结 本节介绍了如何用 `File` 把上传文件声明为(表单数据的)输入参数。 From 5a79564dabff2850b04e747ad85b38ecd15e0718 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 4 Sep 2022 13:40:56 +0000 Subject: [PATCH 163/194] =?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 755f315dc40ff..7a74b7f92a534 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 🌐 Update Chinese translation for `docs/zh/docs/tutorial/request-files.md`. PR [#4529](https://github.com/tiangolo/fastapi/pull/4529) by [@ASpathfinder](https://github.com/ASpathfinder). * 🌐 Add Chinese translation for `docs/zh/docs/tutorial/encoder.md`. PR [#4969](https://github.com/tiangolo/fastapi/pull/4969) by [@Zssaer](https://github.com/Zssaer). * ✏ Tweak wording in `docs/en/docs/advanced/dataclasses.md`. PR [#3698](https://github.com/tiangolo/fastapi/pull/3698) by [@pfackeldey](https://github.com/pfackeldey). * 📝 Add note about Python 3.10 `X | Y` operator in explanation about Response Models. PR [#5307](https://github.com/tiangolo/fastapi/pull/5307) by [@MendyLanda](https://github.com/MendyLanda). From ee035dfa9a245669115dffe0c39e42234c4b1472 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Sun, 4 Sep 2022 15:59:46 +0200 Subject: [PATCH 164/194] =?UTF-8?q?=E2=AC=86=20[pre-commit.ci]=20pre-commi?= =?UTF-8?q?t=20autoupdate=20(#5318)?= 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> --- .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 6e51622e706bf..237feb083882f 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -19,7 +19,7 @@ repos: - --py3-plus - --keep-runtime-typing - repo: https://github.com/myint/autoflake - rev: v1.4 + rev: v1.5.1 hooks: - id: autoflake args: From a3a8d68715bbc344a2b8b8ac6c6f49272c09ce9c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 4 Sep 2022 15:59:59 +0200 Subject: [PATCH 165/194] =?UTF-8?q?=E2=AC=86=20Bump=20dawidd6/action-downl?= =?UTF-8?q?oad-artifact=20from=202.22.0=20to=202.23.0=20(#5321)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/preview-docs.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/preview-docs.yml b/.github/workflows/preview-docs.yml index a4bf322f48fd2..d42b0854312b9 100644 --- a/.github/workflows/preview-docs.yml +++ b/.github/workflows/preview-docs.yml @@ -12,7 +12,7 @@ jobs: steps: - uses: actions/checkout@v3 - name: Download Artifact Docs - uses: dawidd6/action-download-artifact@v2.22.0 + uses: dawidd6/action-download-artifact@v2.23.0 with: github_token: ${{ secrets.GITHUB_TOKEN }} workflow: build-docs.yml From 94b7527dfd3e65903a6b34dea9a71c6e54e9c978 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 4 Sep 2022 14:00:22 +0000 Subject: [PATCH 166/194] =?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 7a74b7f92a534..ddbc9605d9c4a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#5318](https://github.com/tiangolo/fastapi/pull/5318) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/request-files.md`. PR [#4529](https://github.com/tiangolo/fastapi/pull/4529) by [@ASpathfinder](https://github.com/ASpathfinder). * 🌐 Add Chinese translation for `docs/zh/docs/tutorial/encoder.md`. PR [#4969](https://github.com/tiangolo/fastapi/pull/4969) by [@Zssaer](https://github.com/Zssaer). * ✏ Tweak wording in `docs/en/docs/advanced/dataclasses.md`. PR [#3698](https://github.com/tiangolo/fastapi/pull/3698) by [@pfackeldey](https://github.com/pfackeldey). From 7dd4a4f435b5381af379284af186862bd9f99712 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 4 Sep 2022 14:00:36 +0000 Subject: [PATCH 167/194] =?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 ddbc9605d9c4a..0da899c00a270 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* ⬆ Bump dawidd6/action-download-artifact from 2.22.0 to 2.23.0. PR [#5321](https://github.com/tiangolo/fastapi/pull/5321) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#5318](https://github.com/tiangolo/fastapi/pull/5318) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/request-files.md`. PR [#4529](https://github.com/tiangolo/fastapi/pull/4529) by [@ASpathfinder](https://github.com/ASpathfinder). * 🌐 Add Chinese translation for `docs/zh/docs/tutorial/encoder.md`. PR [#4969](https://github.com/tiangolo/fastapi/pull/4969) by [@Zssaer](https://github.com/Zssaer). From 81967f8f9340d9288b11e48c0fa0ad415ec6b5ac Mon Sep 17 00:00:00 2001 From: Vladislav Kramorenko <85196001+Xewus@users.noreply.github.com> Date: Sun, 4 Sep 2022 17:27:48 +0300 Subject: [PATCH 168/194] =?UTF-8?q?=F0=9F=8C=90=20Add=20Russian=20translat?= =?UTF-8?q?ion=20for=20`docs/ru/docs/features.md`=20(#5315)?= 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: Sebastián Ramírez --- docs/ru/docs/features.md | 203 +++++++++++++++++++++++++++++++++++++++ docs/ru/mkdocs.yml | 1 + 2 files changed, 204 insertions(+) create mode 100644 docs/ru/docs/features.md diff --git a/docs/ru/docs/features.md b/docs/ru/docs/features.md new file mode 100644 index 0000000000000..0cec4eee2a012 --- /dev/null +++ b/docs/ru/docs/features.md @@ -0,0 +1,203 @@ +# Основные свойства + +## Основные свойства FastAPI + +**FastAPI** предлагает вам следующее: + +### Использование открытых стандартов + +* OpenAPI для создания API, включая объявления операций пути, параметров, тела запроса, безопасности и т.д. + + +* Автоматическое документирование моделей данных в соответствии с JSON Schema (так как спецификация OpenAPI сама основана на JSON Schema). +* Разработан, придерживаясь этих стандартов, после тщательного их изучения. Эти стандарты изначально включены во фреймфорк, а не являются дополнительной надстройкой. +* Это также позволяет использовать автоматическую **генерацию клиентского кода** на многих языках. + +### Автоматически генерируемая документация + +Интерактивная документация для API и исследования пользовательских веб-интерфейсов. Поскольку этот фреймворк основан на OpenAPI, существует несколько вариантов документирования, 2 из которых включены по умолчанию. + +* Swagger UI, с интерактивным взаимодействием, вызывает и тестирует ваш API прямо из браузера. + +![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png) + +* Альтернативная документация API в ReDoc. + +![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png) + +### Только современный Python + +Все эти возможности основаны на стандартных **аннотациях типов Python 3.6** (благодаря Pydantic). Не нужно изучать новый синтаксис. Только лишь стандартный современный Python. + +Если вам нужно освежить знания, как использовать аннотации типов в Python (даже если вы не используете FastAPI), выделите 2 минуты и просмотрите краткое руководство: [Введение в аннотации типов Python¶ +](python-types.md){.internal-link target=_blank}. + +Вы пишете на стандартном Python с аннотациями типов: + +```Python +from datetime import date + +from pydantic import BaseModel + +# Объявляем параметр user_id с типом `str` +# и получаем поддержку редактора внутри функции +def main(user_id: str): + return user_id + + +# Модель Pydantic +class User(BaseModel): + id: int + name: str + joined: date +``` + +Это можно использовать так: + +```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) +``` + +!!! Информация + `**second_user_data` означает: + + Передать ключи и значения словаря `second_user_data`, в качестве аргументов типа "ключ-значение", это эквивалентно: `User(id=4, name="Mary", joined="2018-11-30")` . + +### Поддержка редакторов (IDE) + +Весь фреймворк был продуман так, чтобы быть простым и интуитивно понятным в использовании, все решения были проверены на множестве редакторов еще до начала разработки, чтобы обеспечить наилучшие условия при написании кода. + +В опросе Python-разработчиков было выяснено, что наиболее часто используемой функцией редакторов, является "автодополнение". + +Вся структура **FastAPI** основана на удовлетворении этой возможности. Автодополнение работает везде. + +Вам редко нужно будет возвращаться к документации. + +Вот как ваш редактор может вам помочь: + +* в Visual Studio Code: + +![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png) + +* в PyCharm: + +![editor support](https://fastapi.tiangolo.com/img/pycharm-completion.png) + +Вы будете получать автодополнение кода даже там, где вы считали это невозможным раньше. +Как пример, ключ `price` внутри тела JSON (который может быть вложенным), приходящего в запросе. + +Больше никаких неправильных имён ключей, метания по документации или прокручивания кода вверх и вниз, в попытках узнать - использовали вы ранее `username` или `user_name`. + +### Краткость +FastAPI имеет продуманные значения **по умолчанию** для всего, с произвольными настройками везде. Все параметры могут быть тонко подстроены так, чтобы делать то, что вам нужно и определять необходимый вам API. + +Но, по умолчанию, всё это **"и так работает"**. + +### Проверка значений + +* Проверка значений для большинства (или всех?) **типов данных** Python, включая: + * Объекты JSON (`dict`). + * Массивы JSON (`list`) с установленными типами элементов. + * Строковые (`str`) поля с ограничением минимальной и максимальной длины. + * Числа (`int`, `float`) с минимальными и максимальными значениями и т.п. + +* Проверка для более экзотических типов, таких как: + * URL. + * Email. + * UUID. + * ...и другие. + +Все проверки обрабатываются хорошо зарекомендовавшим себя и надежным **Pydantic**. + +### Безопасность и аутентификация + +Встроеные функции безопасности и аутентификации. Без каких-либо компромиссов с базами данных или моделями данных. + +Все схемы безопасности, определённые в OpenAPI, включая: + +* HTTP Basic. +* **OAuth2** (также с **токенами JWT**). Ознакомьтесь с руководством [OAuth2 с JWT](tutorial/security/oauth2-jwt.md){.internal-link target=_blank}. +* Ключи API в: + * Заголовках. + * Параметрах запросов. + * Cookies и т.п. + +Вдобавок все функции безопасности от Starlette (включая **сессионные cookies**). + +Все инструменты и компоненты спроектированы для многократного использования и легко интегрируются с вашими системами, хранилищами данных, реляционными и NoSQL базами данных и т. д. + +### Внедрение зависимостей + +FastAPI включает в себя чрезвычайно простую в использовании, но чрезвычайно мощную систему Внедрения зависимостей. + +* Даже зависимости могут иметь зависимости, создавая иерархию или **"графы" зависимостей**. +* Всё **автоматически обрабатывается** фреймворком. +* Все зависимости могут запрашивать данные из запросов и **дополнять операции пути** ограничениями и автоматической документацией. +* **Автоматическая проверка** даже для параметров *операций пути*, определенных в зависимостях. +* Поддержка сложных систем аутентификации пользователей, **соединений с базами данных** и т.д. +* **Никаких компромиссов** с базами данных, интерфейсами и т.д. Но легкая интеграция со всеми ними. + +### Нет ограничений на "Плагины" + +Или, другими словами, нет сложностей с ними, импортируйте и используйте нужный вам код. + +Любая интеграция разработана настолько простой в использовании (с зависимостями), что вы можете создать "плагин" для своего приложения в пару строк кода, используя ту же структуру и синтаксис, что и для ваших *операций пути*. + +### Проверен + +* 100% покрытие тестами. +* 100% аннотирование типов в кодовой базе. +* Используется в реально работающих приложениях. + +## Основные свойства Starlette + +**FastAPI** основан на Starlette и полностью совместим с ним. Так что, любой дополнительный код Starlette, который у вас есть, будет также работать. + +На самом деле, `FastAPI` - это класс, унаследованный от `Starlette`. Таким образом, если вы уже знаете или используете Starlette, большая часть функционала будет работать так же. + +С **FastAPI** вы получаете все возможности **Starlette** (так как FastAPI это всего лишь Starlette на стероидах): + +* Серьёзно впечатляющая производительность. Это один из самых быстрых фреймворков на Python, наравне с приложениями использующими **NodeJS** или **Go**. +* Поддержка **WebSocket**. +* Фоновые задачи для процессов. +* События запуска и выключения. +* Тестовый клиент построен на библиотеке `requests`. +* **CORS**, GZip, статические файлы, потоковые ответы. +* Поддержка **сессий и cookie**. +* 100% покрытие тестами. +* 100% аннотирование типов в кодовой базе. + +## Особенности и возможности Pydantic + +**FastAPI** основан на Pydantic и полностью совместим с ним. Так что, любой дополнительный код Pydantic, который у вас есть, будет также работать. + +Включая внешние библиотеки, также основанные на Pydantic, такие как: ORM'ы, ODM'ы для баз данных. + +Это также означает, что во многих случаях вы можете передавать тот же объект, который получили из запроса, **непосредственно в базу данных**, так как всё проверяется автоматически. + +И наоборот, во многих случаях вы можете просто передать объект, полученный из базы данных, **непосредственно клиенту**. + +С **FastAPI** вы получаете все возможности **Pydantic** (так как, FastAPI основан на Pydantic, для обработки данных): + +* **Никакой нервотрёпки** : + * Не нужно изучать новых схем в микроязыках. + * Если вы знаете аннотации типов в Python, вы знаете, как использовать Pydantic. +* Прекрасно сочетается с вашими **IDE/linter/мозгом**: + * Потому что структуры данных pydantic - это всего лишь экземпляры классов, определённых вами. Автодополнение, проверка кода, mypy и ваша интуиция - всё будет работать с вашими проверенными данными. +* **Быстродействие**: + * В тестовых замерах Pydantic быстрее, чем все другие проверенные библиотеки. +* Проверка **сложных структур**: + * Использование иерархических моделей Pydantic; `List`, `Dict` и т.п. из модуля `typing` (входит в стандартную библиотеку Python). + * Валидаторы позволяют четко и легко определять, проверять и документировать сложные схемы данных в виде JSON Schema. + * У вас могут быть глубоко **вложенные объекты JSON** и все они будут проверены и аннотированы. +* **Расширяемость**: + * Pydantic позволяет определять пользовательские типы данных или расширять проверку методами модели, с помощью проверочных декораторов. +* 100% покрытие тестами. diff --git a/docs/ru/mkdocs.yml b/docs/ru/mkdocs.yml index 2cb5eb8e01e04..381775ac6d849 100644 --- a/docs/ru/mkdocs.yml +++ b/docs/ru/mkdocs.yml @@ -58,6 +58,7 @@ nav: - tr: /tr/ - uk: /uk/ - zh: /zh/ +- features.md - python-types.md - Учебник - руководство пользователя: - tutorial/background-tasks.md From 9df22ab86475ddd507985fe74d199bd80b1da42a Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 4 Sep 2022 14:28:31 +0000 Subject: [PATCH 169/194] =?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 0da899c00a270..dcf629f8162b7 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 🌐 Add Russian translation for `docs/ru/docs/features.md`. PR [#5315](https://github.com/tiangolo/fastapi/pull/5315) by [@Xewus](https://github.com/Xewus). * ⬆ Bump dawidd6/action-download-artifact from 2.22.0 to 2.23.0. PR [#5321](https://github.com/tiangolo/fastapi/pull/5321) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#5318](https://github.com/tiangolo/fastapi/pull/5318) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/request-files.md`. PR [#4529](https://github.com/tiangolo/fastapi/pull/4529) by [@ASpathfinder](https://github.com/ASpathfinder). From 0ae8d091892242954b12d129b627c60517c9cd1e Mon Sep 17 00:00:00 2001 From: baconfield <65581433+baconfield@users.noreply.github.com> Date: Sun, 4 Sep 2022 09:56:29 -0500 Subject: [PATCH 170/194] =?UTF-8?q?=E2=9C=8F=20Update=20Hypercorn=20link,?= =?UTF-8?q?=20now=20pointing=20to=20GitHub=20(#5346)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- README.md | 2 +- docs/en/docs/index.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 590abf17ea55e..bc00d9ed9ab86 100644 --- a/README.md +++ b/README.md @@ -131,7 +131,7 @@ $ pip install fastapi
-You will also need an ASGI server, for production such as Uvicorn or Hypercorn. +You will also need an ASGI server, for production such as Uvicorn or Hypercorn.
diff --git a/docs/en/docs/index.md b/docs/en/docs/index.md index 24ce14e235e98..97ec0ffcff746 100644 --- a/docs/en/docs/index.md +++ b/docs/en/docs/index.md @@ -128,7 +128,7 @@ $ pip install fastapi
-You will also need an ASGI server, for production such as Uvicorn or Hypercorn. +You will also need an ASGI server, for production such as Uvicorn or Hypercorn.
From 0195bb57062106e44b7d17bc88e91538d9249b2b Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 4 Sep 2022 14:57:04 +0000 Subject: [PATCH 171/194] =?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 dcf629f8162b7..af4b36dde1bdb 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* ✏ Update Hypercorn link, now pointing to GitHub. PR [#5346](https://github.com/tiangolo/fastapi/pull/5346) by [@baconfield](https://github.com/baconfield). * 🌐 Add Russian translation for `docs/ru/docs/features.md`. PR [#5315](https://github.com/tiangolo/fastapi/pull/5315) by [@Xewus](https://github.com/Xewus). * ⬆ Bump dawidd6/action-download-artifact from 2.22.0 to 2.23.0. PR [#5321](https://github.com/tiangolo/fastapi/pull/5321) by [@dependabot[bot]](https://github.com/apps/dependabot). * ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#5318](https://github.com/tiangolo/fastapi/pull/5318) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). From 4cff206ebb925acfa4904bb5ddf62c6748f8b15f Mon Sep 17 00:00:00 2001 From: Irfanuddin Shafi Ahmed Date: Sun, 4 Sep 2022 20:37:12 +0530 Subject: [PATCH 172/194] =?UTF-8?q?=F0=9F=90=9B=20Fix=20FastAPI=20People?= =?UTF-8?q?=20GitHub=20Action:=20set=20HTTPX=20timeout=20for=20GraphQL=20q?= =?UTF-8?q?uery=20request=20(#5222)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Irfanuddin Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Sebastián Ramírez --- .github/actions/people/app/main.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/actions/people/app/main.py b/.github/actions/people/app/main.py index 1455d01caeee5..cdf423b97baa8 100644 --- a/.github/actions/people/app/main.py +++ b/.github/actions/people/app/main.py @@ -260,6 +260,7 @@ class Settings(BaseSettings): input_token: SecretStr input_standard_token: SecretStr github_repository: str + httpx_timeout: int = 30 def get_graphql_response( @@ -270,9 +271,10 @@ def get_graphql_response( response = httpx.post( github_graphql_url, headers=headers, + timeout=settings.httpx_timeout, json={"query": query, "variables": variables, "operationName": "Q"}, ) - if not response.status_code == 200: + if response.status_code != 200: logging.error(f"Response was not 200, after: {after}") logging.error(response.text) raise RuntimeError(response.text) From dd2f759bac14b1ecf259c5d9cafe72e211c0e69e Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 4 Sep 2022 15:07:46 +0000 Subject: [PATCH 173/194] =?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 af4b36dde1bdb..34183c14079f5 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 🐛 Fix FastAPI People GitHub Action: set HTTPX timeout for GraphQL query request. PR [#5222](https://github.com/tiangolo/fastapi/pull/5222) by [@iudeen](https://github.com/iudeen). * ✏ Update Hypercorn link, now pointing to GitHub. PR [#5346](https://github.com/tiangolo/fastapi/pull/5346) by [@baconfield](https://github.com/baconfield). * 🌐 Add Russian translation for `docs/ru/docs/features.md`. PR [#5315](https://github.com/tiangolo/fastapi/pull/5315) by [@Xewus](https://github.com/Xewus). * ⬆ Bump dawidd6/action-download-artifact from 2.22.0 to 2.23.0. PR [#5321](https://github.com/tiangolo/fastapi/pull/5321) by [@dependabot[bot]](https://github.com/apps/dependabot). From dacb68929082060b46848c237a3a23085eab947b Mon Sep 17 00:00:00 2001 From: Mateusz Nowak Date: Sun, 4 Sep 2022 17:12:10 +0200 Subject: [PATCH 174/194] =?UTF-8?q?=E2=9C=A8=20Export=20`WebSocketState`?= =?UTF-8?q?=20in=20`fastapi.websockets`=20(#4376)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fastapi/websockets.py | 1 + 1 file changed, 1 insertion(+) diff --git a/fastapi/websockets.py b/fastapi/websockets.py index bed672acff5f2..55a4ac4a1a918 100644 --- a/fastapi/websockets.py +++ b/fastapi/websockets.py @@ -1,2 +1,3 @@ from starlette.websockets import WebSocket as WebSocket # noqa from starlette.websockets import WebSocketDisconnect as WebSocketDisconnect # noqa +from starlette.websockets import WebSocketState as WebSocketState # noqa From 80d68a6eda93dd1e89725aca6d38fa9bb8db4f73 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 4 Sep 2022 15:12:59 +0000 Subject: [PATCH 175/194] =?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 34183c14079f5..327175a76525b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* ✨ Export `WebSocketState` in `fastapi.websockets`. PR [#4376](https://github.com/tiangolo/fastapi/pull/4376) by [@matiuszka](https://github.com/matiuszka). * 🐛 Fix FastAPI People GitHub Action: set HTTPX timeout for GraphQL query request. PR [#5222](https://github.com/tiangolo/fastapi/pull/5222) by [@iudeen](https://github.com/iudeen). * ✏ Update Hypercorn link, now pointing to GitHub. PR [#5346](https://github.com/tiangolo/fastapi/pull/5346) by [@baconfield](https://github.com/baconfield). * 🌐 Add Russian translation for `docs/ru/docs/features.md`. PR [#5315](https://github.com/tiangolo/fastapi/pull/5315) by [@Xewus](https://github.com/Xewus). From c70fab38e74039d9564da175f3d42c34f9581de8 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 4 Sep 2022 15:16:00 +0000 Subject: [PATCH 176/194] =?UTF-8?q?=F0=9F=91=A5=20Update=20FastAPI=20Peopl?= =?UTF-8?q?e=20(#5347)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: github-actions Co-authored-by: Sebastián Ramírez --- docs/en/data/github_sponsors.yml | 182 +++++++++++++++++-------------- docs/en/data/people.yml | 180 +++++++++++++++--------------- 2 files changed, 188 insertions(+), 174 deletions(-) diff --git a/docs/en/data/github_sponsors.yml b/docs/en/data/github_sponsors.yml index 6c1efcbbd96ba..891a990a420b0 100644 --- a/docs/en/data/github_sponsors.yml +++ b/docs/en/data/github_sponsors.yml @@ -1,25 +1,19 @@ sponsors: -- - login: github - avatarUrl: https://avatars.githubusercontent.com/u/9919?v=4 - url: https://github.com/github +- - login: jina-ai + avatarUrl: https://avatars.githubusercontent.com/u/60539444?v=4 + url: https://github.com/jina-ai - - login: Doist avatarUrl: https://avatars.githubusercontent.com/u/2565372?v=4 url: https://github.com/Doist - login: cryptapi avatarUrl: https://avatars.githubusercontent.com/u/44925437?u=61369138589bc7fee6c417f3fbd50fbd38286cc4&v=4 url: https://github.com/cryptapi - - login: BLUE-DEVIL1134 - avatarUrl: https://avatars.githubusercontent.com/u/55914808?u=f283d674fce31be7fb3ed2665b0f20d89958e541&v=4 - url: https://github.com/BLUE-DEVIL1134 - - login: jina-ai - avatarUrl: https://avatars.githubusercontent.com/u/60539444?v=4 - url: https://github.com/jina-ai - - login: DropbaseHQ - avatarUrl: https://avatars.githubusercontent.com/u/85367855?v=4 - url: https://github.com/DropbaseHQ - - login: ObliviousAI avatarUrl: https://avatars.githubusercontent.com/u/65656077?v=4 url: https://github.com/ObliviousAI + - login: Lovage-Labs + avatarUrl: https://avatars.githubusercontent.com/u/71685552?v=4 + url: https://github.com/Lovage-Labs - login: chaserowbotham avatarUrl: https://avatars.githubusercontent.com/u/97751084?v=4 url: https://github.com/chaserowbotham @@ -47,9 +41,9 @@ sponsors: - - login: SendCloud avatarUrl: https://avatars.githubusercontent.com/u/7831959?v=4 url: https://github.com/SendCloud - - login: qaas - avatarUrl: https://avatars.githubusercontent.com/u/8503759?u=10a6b4391ad6ab4cf9487ce54e3fcb61322d1efc&v=4 - url: https://github.com/qaas + - login: mercedes-benz + avatarUrl: https://avatars.githubusercontent.com/u/34240465?v=4 + url: https://github.com/mercedes-benz - login: xoflare avatarUrl: https://avatars.githubusercontent.com/u/74335107?v=4 url: https://github.com/xoflare @@ -59,10 +53,10 @@ sponsors: - login: BoostryJP avatarUrl: https://avatars.githubusercontent.com/u/57932412?v=4 url: https://github.com/BoostryJP -- - login: nnfuzzy - avatarUrl: https://avatars.githubusercontent.com/u/687670?v=4 - url: https://github.com/nnfuzzy - - login: johnadjei + - login: Jonathanjwp + avatarUrl: https://avatars.githubusercontent.com/u/110426978?u=5e6ed4984022cb8886c4fdfdc0c59f55c48a2f1d&v=4 + url: https://github.com/Jonathanjwp +- - login: johnadjei avatarUrl: https://avatars.githubusercontent.com/u/767860?v=4 url: https://github.com/johnadjei - login: HiredScore @@ -71,6 +65,9 @@ sponsors: - login: wdwinslow avatarUrl: https://avatars.githubusercontent.com/u/11562137?u=dc01daafb354135603a263729e3d26d939c0c452&v=4 url: https://github.com/wdwinslow + - login: khalidelboray + avatarUrl: https://avatars.githubusercontent.com/u/37024839?u=9a4b19123b5a1ba39dc581f8e4e1bc53fafdda2e&v=4 + url: https://github.com/khalidelboray - - login: moellenbeck avatarUrl: https://avatars.githubusercontent.com/u/169372?v=4 url: https://github.com/moellenbeck @@ -80,27 +77,39 @@ sponsors: - login: tizz98 avatarUrl: https://avatars.githubusercontent.com/u/5739698?u=f095a3659e3a8e7c69ccd822696990b521ea25f9&v=4 url: https://github.com/tizz98 + - login: Vikka + avatarUrl: https://avatars.githubusercontent.com/u/9381120?u=4bfc7032a824d1ed1994aa8256dfa597c8f187ad&v=4 + url: https://github.com/Vikka - login: jmaralc avatarUrl: https://avatars.githubusercontent.com/u/21101214?u=b15a9f07b7cbf6c9dcdbcb6550bbd2c52f55aa50&v=4 url: https://github.com/jmaralc - - login: marutoraman + - login: takashi-yoneya avatarUrl: https://avatars.githubusercontent.com/u/33813153?u=2d0522bceba0b8b69adf1f2db866503bd96f944e&v=4 - url: https://github.com/marutoraman + url: https://github.com/takashi-yoneya - login: leynier avatarUrl: https://avatars.githubusercontent.com/u/36774373?u=2284831c821307de562ebde5b59014d5416c7e0d&v=4 url: https://github.com/leynier - login: mainframeindustries avatarUrl: https://avatars.githubusercontent.com/u/55092103?v=4 url: https://github.com/mainframeindustries - - login: A-Edge - avatarUrl: https://avatars.githubusercontent.com/u/59514131?v=4 - url: https://github.com/A-Edge - login: DelfinaCare avatarUrl: https://avatars.githubusercontent.com/u/83734439?v=4 url: https://github.com/DelfinaCare - - login: povilasb avatarUrl: https://avatars.githubusercontent.com/u/1213442?u=b11f58ed6ceea6e8297c9b310030478ebdac894d&v=4 url: https://github.com/povilasb + - login: primer-io + avatarUrl: https://avatars.githubusercontent.com/u/62146168?v=4 + url: https://github.com/primer-io +- - login: ekpyrosis + avatarUrl: https://avatars.githubusercontent.com/u/60075?v=4 + url: https://github.com/ekpyrosis + - login: ryangrose + avatarUrl: https://avatars.githubusercontent.com/u/24993976?u=052f346aa859f3e52c21bd2c1792f61a98cfbacf&v=4 + url: https://github.com/ryangrose + - login: A-Edge + avatarUrl: https://avatars.githubusercontent.com/u/59514131?v=4 + url: https://github.com/A-Edge - - login: Kludex avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex @@ -116,6 +125,9 @@ sponsors: - login: kamalgill avatarUrl: https://avatars.githubusercontent.com/u/133923?u=0df9181d97436ce330e9acf90ab8a54b7022efe7&v=4 url: https://github.com/kamalgill + - login: dekoza + avatarUrl: https://avatars.githubusercontent.com/u/210980?u=c03c78a8ae1039b500dfe343665536ebc51979b2&v=4 + url: https://github.com/dekoza - login: deserat avatarUrl: https://avatars.githubusercontent.com/u/299332?v=4 url: https://github.com/deserat @@ -164,12 +176,18 @@ sponsors: - login: zsinx6 avatarUrl: https://avatars.githubusercontent.com/u/3532625?u=ba75a5dc744d1116ccfeaaf30d41cb2fe81fe8dd&v=4 url: https://github.com/zsinx6 + - login: aacayaco + avatarUrl: https://avatars.githubusercontent.com/u/3634801?u=eaadda178c964178fcb64886f6c732172c8f8219&v=4 + url: https://github.com/aacayaco - login: anomaly avatarUrl: https://avatars.githubusercontent.com/u/3654837?v=4 url: https://github.com/anomaly - login: peterHoburg avatarUrl: https://avatars.githubusercontent.com/u/3860655?u=f55f47eb2d6a9b495e806ac5a044e3ae01ccc1fa&v=4 url: https://github.com/peterHoburg + - login: jgreys + avatarUrl: https://avatars.githubusercontent.com/u/4136890?u=b579fd97033269a5e703ab509c7d5478b146cc2d&v=4 + url: https://github.com/jgreys - login: gorhack avatarUrl: https://avatars.githubusercontent.com/u/4141690?u=ec119ebc4bdf00a7bc84657a71aa17834f4f27f3&v=4 url: https://github.com/gorhack @@ -188,9 +206,6 @@ sponsors: - login: ennui93 avatarUrl: https://avatars.githubusercontent.com/u/5300907?u=5b5452725ddb391b2caaebf34e05aba873591c3a&v=4 url: https://github.com/ennui93 - - login: MacroPower - avatarUrl: https://avatars.githubusercontent.com/u/5648814?u=e13991efd1e03c44c911f919872e750530ded633&v=4 - url: https://github.com/MacroPower - login: Yaleesa avatarUrl: https://avatars.githubusercontent.com/u/6135475?v=4 url: https://github.com/Yaleesa @@ -203,9 +218,6 @@ sponsors: - login: pkucmus avatarUrl: https://avatars.githubusercontent.com/u/6347418?u=98f5918b32e214a168a2f5d59b0b8ebdf57dca0d&v=4 url: https://github.com/pkucmus - - login: ioalloc - avatarUrl: https://avatars.githubusercontent.com/u/6737824?u=6c3a31449f1c92064287171aa9ebe6363a0c9b7b&v=4 - url: https://github.com/ioalloc - login: s3ich4n avatarUrl: https://avatars.githubusercontent.com/u/6926298?u=ba3025d698e1c986655e776ae383a3d60d9d578e&v=4 url: https://github.com/s3ich4n @@ -218,9 +230,6 @@ sponsors: - login: Shackelford-Arden avatarUrl: https://avatars.githubusercontent.com/u/7362263?v=4 url: https://github.com/Shackelford-Arden - - login: Vikka - avatarUrl: https://avatars.githubusercontent.com/u/9381120?u=4bfc7032a824d1ed1994aa8256dfa597c8f187ad&v=4 - url: https://github.com/Vikka - login: Ge0f3 avatarUrl: https://avatars.githubusercontent.com/u/11887760?u=ccd80f1ac36dcb8517ef5c4e702e8cc5a80cad2f&v=4 url: https://github.com/Ge0f3 @@ -242,9 +251,6 @@ sponsors: - login: wedwardbeck avatarUrl: https://avatars.githubusercontent.com/u/19333237?u=1de4ae2bf8d59eb4c013f21d863cbe0f2010575f&v=4 url: https://github.com/wedwardbeck - - login: stradivari96 - avatarUrl: https://avatars.githubusercontent.com/u/19752586?u=255f5f06a768f518b20cebd6963e840ac49294fd&v=4 - url: https://github.com/stradivari96 - login: RedCarpetUp avatarUrl: https://avatars.githubusercontent.com/u/20360440?v=4 url: https://github.com/RedCarpetUp @@ -266,9 +272,9 @@ sponsors: - login: veprimk avatarUrl: https://avatars.githubusercontent.com/u/29689749?u=f8cb5a15a286e522e5b189bc572d5a1a90217fb2&v=4 url: https://github.com/veprimk - - login: meysam81 - avatarUrl: https://avatars.githubusercontent.com/u/30233243?u=64dc9fc62d039892c6fb44d804251cad5537132b&v=4 - url: https://github.com/meysam81 + - login: BrettskiPy + avatarUrl: https://avatars.githubusercontent.com/u/30988215?u=d8a94a67e140d5ee5427724b292cc52d8827087a&v=4 + url: https://github.com/BrettskiPy - login: mauroalejandrojm avatarUrl: https://avatars.githubusercontent.com/u/31569442?u=cdada990a1527926a36e95f62c30a8b48bbc49a1&v=4 url: https://github.com/mauroalejandrojm @@ -281,18 +287,12 @@ sponsors: - login: ProteinQure avatarUrl: https://avatars.githubusercontent.com/u/33707203?v=4 url: https://github.com/ProteinQure - - login: guligon90 - avatarUrl: https://avatars.githubusercontent.com/u/35070513?u=b48c05f669d1ea1d329f90dc70e45f10b569ef55&v=4 - url: https://github.com/guligon90 - login: ybressler avatarUrl: https://avatars.githubusercontent.com/u/40807730?u=41e2c00f1eebe3c402635f0325e41b4e6511462c&v=4 url: https://github.com/ybressler - login: ddilidili avatarUrl: https://avatars.githubusercontent.com/u/42176885?u=c0a849dde06987434653197b5f638d3deb55fc6c&v=4 url: https://github.com/ddilidili - - login: dbanty - avatarUrl: https://avatars.githubusercontent.com/u/43723790?u=9bcce836bbce55835291c5b2ac93a4e311f4b3c3&v=4 - url: https://github.com/dbanty - login: VictorCalderon avatarUrl: https://avatars.githubusercontent.com/u/44529243?u=cea69884f826a29aff1415493405209e0706d07a&v=4 url: https://github.com/VictorCalderon @@ -302,27 +302,27 @@ sponsors: - login: rafsaf avatarUrl: https://avatars.githubusercontent.com/u/51059348?u=f8f0d6d6e90fac39fa786228158ba7f013c74271&v=4 url: https://github.com/rafsaf + - login: yezz123 + avatarUrl: https://avatars.githubusercontent.com/u/52716203?u=636b4f79645176df4527dd45c12d5dbb5a4193cf&v=4 + url: https://github.com/yezz123 - login: dudikbender avatarUrl: https://avatars.githubusercontent.com/u/53487583?u=494f85229115076121b3639a3806bbac1c6ae7f6&v=4 url: https://github.com/dudikbender - - login: daisuke8000 - avatarUrl: https://avatars.githubusercontent.com/u/55035595?u=23a3f2f2925ad3efc27c7420041622b7f5fd2b79&v=4 - url: https://github.com/daisuke8000 - login: dazeddd avatarUrl: https://avatars.githubusercontent.com/u/59472056?u=7a1b668449bf8b448db13e4c575576d24d7d658b&v=4 url: https://github.com/dazeddd - login: yakkonaut avatarUrl: https://avatars.githubusercontent.com/u/60633704?u=90a71fd631aa998ba4a96480788f017c9904e07b&v=4 url: https://github.com/yakkonaut - - login: primer-io - avatarUrl: https://avatars.githubusercontent.com/u/62146168?v=4 - url: https://github.com/primer-io - - login: around - avatarUrl: https://avatars.githubusercontent.com/u/62425723?v=4 - url: https://github.com/around + - login: patsatsia + avatarUrl: https://avatars.githubusercontent.com/u/61111267?u=419516384f798a35e9d9e2dd81282cc46c151b58&v=4 + url: https://github.com/patsatsia - login: predictionmachine avatarUrl: https://avatars.githubusercontent.com/u/63719559?v=4 url: https://github.com/predictionmachine + - login: minsau + avatarUrl: https://avatars.githubusercontent.com/u/64386242?u=7e45f24b2958caf946fa3546ea33bacf5cd886f8&v=4 + url: https://github.com/minsau - login: daverin avatarUrl: https://avatars.githubusercontent.com/u/70378377?u=6d1814195c0de7162820eaad95a25b423a3869c0&v=4 url: https://github.com/daverin @@ -335,11 +335,14 @@ sponsors: - login: pyt3h avatarUrl: https://avatars.githubusercontent.com/u/99658549?v=4 url: https://github.com/pyt3h +- - login: raestrada95 + avatarUrl: https://avatars.githubusercontent.com/u/34411704?u=f32b7e8f57a3f7e2a99e2bc115356f89f094f340&v=4 + url: https://github.com/raestrada95 - - login: linux-china avatarUrl: https://avatars.githubusercontent.com/u/46711?v=4 url: https://github.com/linux-china - login: ddanier - avatarUrl: https://avatars.githubusercontent.com/u/113563?v=4 + avatarUrl: https://avatars.githubusercontent.com/u/113563?u=ed1dc79de72f93bd78581f88ebc6952b62f472da&v=4 url: https://github.com/ddanier - login: jhb avatarUrl: https://avatars.githubusercontent.com/u/142217?v=4 @@ -350,6 +353,9 @@ sponsors: - login: bryanculbertson avatarUrl: https://avatars.githubusercontent.com/u/144028?u=defda4f90e93429221cc667500944abde60ebe4a&v=4 url: https://github.com/bryanculbertson + - login: hhatto + avatarUrl: https://avatars.githubusercontent.com/u/150309?u=3e8f63c27bf996bfc68464b0ce3f7a3e40e6ea7f&v=4 + url: https://github.com/hhatto - login: yourkin avatarUrl: https://avatars.githubusercontent.com/u/178984?u=fa7c3503b47bf16405b96d21554bc59f07a65523&v=4 url: https://github.com/yourkin @@ -369,7 +375,7 @@ sponsors: avatarUrl: https://avatars.githubusercontent.com/u/388564?v=4 url: https://github.com/dmig - login: rinckd - avatarUrl: https://avatars.githubusercontent.com/u/546002?u=1fcc7e664dc86524a0af6837a0c222829c3fd4e5&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/546002?u=8ec88ab721a5636346f19dcd677a6f323058be8b&v=4 url: https://github.com/rinckd - login: securancy avatarUrl: https://avatars.githubusercontent.com/u/606673?v=4 @@ -393,7 +399,7 @@ sponsors: avatarUrl: https://avatars.githubusercontent.com/u/1430522?u=169dba3bfbc04ed214a914640ff435969f19ddb3&v=4 url: https://github.com/Pytlicek - login: allen0125 - avatarUrl: https://avatars.githubusercontent.com/u/1448456?u=d4feb3d06a61baa4a69857ce371cc53fb4dffd2c&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/1448456?u=dc2ad819497eef494b88688a1796e0adb87e7cae&v=4 url: https://github.com/allen0125 - login: WillHogan avatarUrl: https://avatars.githubusercontent.com/u/1661551?u=7036c064cf29781470573865264ec8e60b6b809f&v=4 @@ -404,6 +410,9 @@ sponsors: - login: rglsk avatarUrl: https://avatars.githubusercontent.com/u/2768101?u=e349c88673f2155fe021331377c656a9d74bcc25&v=4 url: https://github.com/rglsk + - login: Debakel + avatarUrl: https://avatars.githubusercontent.com/u/2857237?u=07df6d11c8feef9306d071cb1c1005a2dd596585&v=4 + url: https://github.com/Debakel - login: paul121 avatarUrl: https://avatars.githubusercontent.com/u/3116995?u=6e2d8691cc345e63ee02e4eb4d7cef82b1fcbedc&v=4 url: https://github.com/paul121 @@ -413,6 +422,9 @@ sponsors: - login: anthonycorletti avatarUrl: https://avatars.githubusercontent.com/u/3477132?v=4 url: https://github.com/anthonycorletti + - login: jonathanhle + avatarUrl: https://avatars.githubusercontent.com/u/3851599?u=76b9c5d2fecd6c3a16e7645231878c4507380d4d&v=4 + url: https://github.com/jonathanhle - login: pawamoy avatarUrl: https://avatars.githubusercontent.com/u/3999221?u=b030e4c89df2f3a36bc4710b925bdeb6745c9856&v=4 url: https://github.com/pawamoy @@ -425,9 +437,15 @@ sponsors: - login: unredundant avatarUrl: https://avatars.githubusercontent.com/u/5607577?u=57dd0023365bec03f4fc566df6b81bc0a264a47d&v=4 url: https://github.com/unredundant + - login: Baghdady92 + avatarUrl: https://avatars.githubusercontent.com/u/5708590?v=4 + url: https://github.com/Baghdady92 - login: holec avatarUrl: https://avatars.githubusercontent.com/u/6438041?u=f5af71ec85b3a9d7b8139cb5af0512b02fa9ab1e&v=4 url: https://github.com/holec + - login: hcristea + avatarUrl: https://avatars.githubusercontent.com/u/7814406?u=61d7a4fcf846983a4606788eac25e1c6c1209ba8&v=4 + url: https://github.com/hcristea - login: moonape1226 avatarUrl: https://avatars.githubusercontent.com/u/8532038?u=d9f8b855a429fff9397c3833c2ff83849ebf989d&v=4 url: https://github.com/moonape1226 @@ -449,12 +467,18 @@ sponsors: - login: satwikkansal avatarUrl: https://avatars.githubusercontent.com/u/10217535?u=b12d6ef74ea297de9e46da6933b1a5b7ba9e6a61&v=4 url: https://github.com/satwikkansal + - login: mntolia + avatarUrl: https://avatars.githubusercontent.com/u/10390224?v=4 + url: https://github.com/mntolia - login: pheanex avatarUrl: https://avatars.githubusercontent.com/u/10408624?u=5b6bab6ee174aa6e991333e06eb29f628741013d&v=4 url: https://github.com/pheanex - login: JimFawkes avatarUrl: https://avatars.githubusercontent.com/u/12075115?u=dc58ecfd064d72887c34bf500ddfd52592509acd&v=4 url: https://github.com/JimFawkes + - login: giuliano-oliveira + avatarUrl: https://avatars.githubusercontent.com/u/13181797?u=0ef2dfbf7fc9a9726d45c21d32b5d1038a174870&v=4 + url: https://github.com/giuliano-oliveira - login: logan-connolly avatarUrl: https://avatars.githubusercontent.com/u/16244943?u=8ae66dfbba936463cc8aa0dd7a6d2b4c0cc757eb&v=4 url: https://github.com/logan-connolly @@ -467,9 +491,6 @@ sponsors: - login: cdsre avatarUrl: https://avatars.githubusercontent.com/u/16945936?v=4 url: https://github.com/cdsre - - login: aprilcoskun - avatarUrl: https://avatars.githubusercontent.com/u/17393603?u=29145243b4c7fadc80c7099471309cc2c04b6bcc&v=4 - url: https://github.com/aprilcoskun - login: jangia avatarUrl: https://avatars.githubusercontent.com/u/17927101?u=9261b9bb0c3e3bb1ecba43e8915dc58d8c9a077e&v=4 url: https://github.com/jangia @@ -485,15 +506,12 @@ sponsors: - login: mertguvencli avatarUrl: https://avatars.githubusercontent.com/u/29762151?u=16a906d90df96c8cff9ea131a575c4bc171b1523&v=4 url: https://github.com/mertguvencli - - login: elisoncrum - avatarUrl: https://avatars.githubusercontent.com/u/30413278?u=531190845bb0935dbc1e4f017cda3cb7b4dd0e54&v=4 - url: https://github.com/elisoncrum + - login: ruizdiazever + avatarUrl: https://avatars.githubusercontent.com/u/29817086?u=2df54af55663d246e3a4dc8273711c37f1adb117&v=4 + url: https://github.com/ruizdiazever - login: HosamAlmoghraby avatarUrl: https://avatars.githubusercontent.com/u/32025281?u=aa1b09feabccbf9dc506b81c71155f32d126cefa&v=4 url: https://github.com/HosamAlmoghraby - - login: kitaramu0401 - avatarUrl: https://avatars.githubusercontent.com/u/33246506?u=929e6efa2c518033b8097ba524eb5347a069bb3b&v=4 - url: https://github.com/kitaramu0401 - login: engineerjoe440 avatarUrl: https://avatars.githubusercontent.com/u/33275230?u=eb223cad27017bb1e936ee9b429b450d092d0236&v=4 url: https://github.com/engineerjoe440 @@ -516,11 +534,11 @@ sponsors: avatarUrl: https://avatars.githubusercontent.com/u/42189572?u=a2d6121bac4d125d92ec207460fa3f1842d37e66&v=4 url: https://github.com/ilias-ant - login: arrrrrmin - avatarUrl: https://avatars.githubusercontent.com/u/43553423?u=fee5739394fea074cb0b66929d070114a5067aae&v=4 + avatarUrl: https://avatars.githubusercontent.com/u/43553423?u=2a812c1a2ec58227ed01778837f255143de9df97&v=4 url: https://github.com/arrrrrmin - - login: BomGard - avatarUrl: https://avatars.githubusercontent.com/u/47395385?u=8e9052f54e0b8dc7285099c438fa29c55a7d6407&v=4 - url: https://github.com/BomGard + - login: MauriceKuenicke + avatarUrl: https://avatars.githubusercontent.com/u/47433175?u=37455bc95c7851db296ac42626f0cacb77ca2443&v=4 + url: https://github.com/MauriceKuenicke - login: akanz1 avatarUrl: https://avatars.githubusercontent.com/u/51492342?u=2280f57134118714645e16b535c1a37adf6b369b&v=4 url: https://github.com/akanz1 @@ -548,24 +566,24 @@ sponsors: - login: alessio-proietti avatarUrl: https://avatars.githubusercontent.com/u/67370599?u=8ac73db1e18e946a7681f173abdb640516f88515&v=4 url: https://github.com/alessio-proietti - - login: Mr-Sunglasses - avatarUrl: https://avatars.githubusercontent.com/u/81439109?u=a5d0762fdcec26e18a028aef05323de3c6fb195c&v=4 - url: https://github.com/Mr-Sunglasses + - login: pondDevThai + avatarUrl: https://avatars.githubusercontent.com/u/71592181?u=08af9a59bccfd8f6b101de1005aa9822007d0a44&v=4 + url: https://github.com/pondDevThai + - login: CY0xZ + avatarUrl: https://avatars.githubusercontent.com/u/103884082?u=0b3260c6a1af6268492f69264dbb75989afb155f&v=4 + url: https://github.com/CY0xZ - - login: backbord avatarUrl: https://avatars.githubusercontent.com/u/6814946?v=4 url: https://github.com/backbord + - login: mattwelke + avatarUrl: https://avatars.githubusercontent.com/u/7719209?u=5d963ead289969257190b133250653bd99df06ba&v=4 + url: https://github.com/mattwelke - login: gabrielmbmb avatarUrl: https://avatars.githubusercontent.com/u/29572918?u=6d1e00b5d558e96718312ff910a2318f47cc3145&v=4 url: https://github.com/gabrielmbmb - login: danburonline avatarUrl: https://avatars.githubusercontent.com/u/34251194?u=2cad4388c1544e539ecb732d656e42fb07b4ff2d&v=4 url: https://github.com/danburonline - - login: zachspar - avatarUrl: https://avatars.githubusercontent.com/u/41600414?u=edf29c197137f51bace3f19a2ba759662640771f&v=4 - url: https://github.com/zachspar - - login: sownt - avatarUrl: https://avatars.githubusercontent.com/u/44340502?u=c06e3c45fb00a403075172770805fe57ff17b1cf&v=4 - url: https://github.com/sownt - - login: aahouzi - avatarUrl: https://avatars.githubusercontent.com/u/75032370?u=82677ee9cd86b3ccf4e13d9cb6765d8de5713e1e&v=4 - url: https://github.com/aahouzi + - login: Moises6669 + avatarUrl: https://avatars.githubusercontent.com/u/66188523?u=81761d977faabab60cba5a06e7d50b44416c0c99&v=4 + url: https://github.com/Moises6669 diff --git a/docs/en/data/people.yml b/docs/en/data/people.yml index 031c1ca4da2fe..d804ecabbab2a 100644 --- a/docs/en/data/people.yml +++ b/docs/en/data/people.yml @@ -1,12 +1,12 @@ maintainers: - login: tiangolo - answers: 1248 - prs: 318 + answers: 1265 + prs: 333 avatarUrl: https://avatars.githubusercontent.com/u/1326112?u=740f11212a731f56798f558ceddb0bd07642afa7&v=4 url: https://github.com/tiangolo experts: - login: Kludex - count: 352 + count: 360 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex - login: dmontagu @@ -29,6 +29,10 @@ experts: count: 130 avatarUrl: https://avatars.githubusercontent.com/u/331403?v=4 url: https://github.com/phy25 +- login: JarroVGIT + count: 129 + avatarUrl: https://avatars.githubusercontent.com/u/13659033?u=e8bea32d07a5ef72f7dde3b2079ceb714923ca05&v=4 + url: https://github.com/JarroVGIT - login: raphaelauv count: 77 avatarUrl: https://avatars.githubusercontent.com/u/10202690?u=e6f86f5c0c3026a15d6b51792fa3e532b12f1371&v=4 @@ -37,10 +41,6 @@ experts: count: 71 avatarUrl: https://avatars.githubusercontent.com/u/31127044?u=b0f2c37142f4b762e41ad65dc49581813422bd71&v=4 url: https://github.com/ArcLightSlavik -- login: JarroVGIT - count: 68 - avatarUrl: https://avatars.githubusercontent.com/u/13659033?u=e8bea32d07a5ef72f7dde3b2079ceb714923ca05&v=4 - url: https://github.com/JarroVGIT - login: falkben count: 58 avatarUrl: https://avatars.githubusercontent.com/u/653031?u=0c8d8f33d87f1aa1a6488d3f02105e9abc838105&v=4 @@ -57,14 +57,18 @@ experts: count: 43 avatarUrl: https://avatars.githubusercontent.com/u/27180793?u=5cf2877f50b3eb2bc55086089a78a36f07042889&v=4 url: https://github.com/Dustyposa -- login: adriangb - count: 40 - avatarUrl: https://avatars.githubusercontent.com/u/1755071?u=81f0262df34e1460ca546fbd0c211169c2478532&v=4 - url: https://github.com/adriangb +- login: iudeen + count: 42 + avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 + url: https://github.com/iudeen - login: jgould22 - count: 40 + count: 42 avatarUrl: https://avatars.githubusercontent.com/u/4335847?u=ed77f67e0bb069084639b24d812dbb2a2b1dc554&v=4 url: https://github.com/jgould22 +- login: adriangb + count: 40 + avatarUrl: https://avatars.githubusercontent.com/u/1755071?u=75087f0cf0e9f725f3cd18a899218b6c63ae60d3&v=4 + url: https://github.com/adriangb - login: includeamin count: 39 avatarUrl: https://avatars.githubusercontent.com/u/11836741?u=8bd5ef7e62fe6a82055e33c4c0e0a7879ff8cfb6&v=4 @@ -73,6 +77,10 @@ experts: count: 37 avatarUrl: https://avatars.githubusercontent.com/u/5167622?u=de8f597c81d6336fcebc37b32dfd61a3f877160c&v=4 url: https://github.com/STeveShary +- login: chbndrhnns + count: 34 + avatarUrl: https://avatars.githubusercontent.com/u/7534547?v=4 + url: https://github.com/chbndrhnns - login: prostomarkeloff count: 33 avatarUrl: https://avatars.githubusercontent.com/u/28061158?u=72309cc1f2e04e40fa38b29969cb4e9d3f722e7b&v=4 @@ -85,20 +93,16 @@ experts: count: 31 avatarUrl: https://avatars.githubusercontent.com/u/31960541?u=47f4829c77f4962ab437ffb7995951e41eeebe9b&v=4 url: https://github.com/krishnardt -- login: chbndrhnns - count: 30 - avatarUrl: https://avatars.githubusercontent.com/u/7534547?v=4 - url: https://github.com/chbndrhnns - login: wshayes count: 29 avatarUrl: https://avatars.githubusercontent.com/u/365303?u=07ca03c5ee811eb0920e633cc3c3db73dbec1aa5&v=4 url: https://github.com/wshayes - login: panla - count: 27 + count: 28 avatarUrl: https://avatars.githubusercontent.com/u/41326348?u=ba2fda6b30110411ecbf406d187907e2b420ac19&v=4 url: https://github.com/panla - login: acidjunk - count: 25 + count: 26 avatarUrl: https://avatars.githubusercontent.com/u/685002?u=b5094ab4527fc84b006c0ac9ff54367bdebb2267&v=4 url: https://github.com/acidjunk - login: ghandic @@ -125,14 +129,14 @@ experts: count: 21 avatarUrl: https://avatars.githubusercontent.com/u/565544?v=4 url: https://github.com/chris-allnutt +- login: odiseo0 + count: 20 + avatarUrl: https://avatars.githubusercontent.com/u/87550035?u=ab724eae71c3fe1cf81e8dc76e73415da926ef7d&v=4 + url: https://github.com/odiseo0 - login: retnikt count: 19 avatarUrl: https://avatars.githubusercontent.com/u/24581770?v=4 url: https://github.com/retnikt -- login: odiseo0 - count: 19 - avatarUrl: https://avatars.githubusercontent.com/u/87550035?u=ab724eae71c3fe1cf81e8dc76e73415da926ef7d&v=4 - url: https://github.com/odiseo0 - login: Hultner count: 18 avatarUrl: https://avatars.githubusercontent.com/u/2669034?u=115e53df959309898ad8dc9443fbb35fee71df07&v=4 @@ -173,6 +177,10 @@ experts: count: 13 avatarUrl: https://avatars.githubusercontent.com/u/58201?u=4f1f9843d69433ca0d380d95146cfe119e5fdac4&v=4 url: https://github.com/haizaar +- login: yinziyan1206 + count: 13 + avatarUrl: https://avatars.githubusercontent.com/u/37829370?v=4 + url: https://github.com/yinziyan1206 - login: valentin994 count: 13 avatarUrl: https://avatars.githubusercontent.com/u/42819267?u=fdeeaa9242a59b243f8603496b00994f6951d5a2&v=4 @@ -181,47 +189,31 @@ experts: count: 12 avatarUrl: https://avatars.githubusercontent.com/u/17401854?u=474680c02b94cba810cb9032fb7eb787d9cc9d22&v=4 url: https://github.com/David-Lor -- login: yinziyan1206 - count: 12 - avatarUrl: https://avatars.githubusercontent.com/u/37829370?v=4 - url: https://github.com/yinziyan1206 - login: n8sty count: 12 avatarUrl: https://avatars.githubusercontent.com/u/2964996?v=4 url: https://github.com/n8sty -- login: lowercase00 - count: 11 - avatarUrl: https://avatars.githubusercontent.com/u/21188280?v=4 - url: https://github.com/lowercase00 -- login: zamiramir - count: 11 - avatarUrl: https://avatars.githubusercontent.com/u/40475662?u=e58ef61034e8d0d6a312cc956fb09b9c3332b449&v=4 - url: https://github.com/zamiramir +- login: zoliknemet + count: 12 + avatarUrl: https://avatars.githubusercontent.com/u/22326718?u=31ba446ac290e23e56eea8e4f0c558aaf0b40779&v=4 + url: https://github.com/zoliknemet last_month_active: - login: JarroVGIT - count: 30 + count: 27 avatarUrl: https://avatars.githubusercontent.com/u/13659033?u=e8bea32d07a5ef72f7dde3b2079ceb714923ca05&v=4 url: https://github.com/JarroVGIT -- login: zoliknemet - count: 9 - avatarUrl: https://avatars.githubusercontent.com/u/22326718?u=31ba446ac290e23e56eea8e4f0c558aaf0b40779&v=4 - url: https://github.com/zoliknemet - login: iudeen - count: 5 + count: 17 avatarUrl: https://avatars.githubusercontent.com/u/10519440?u=2843b3303282bff8b212dcd4d9d6689452e4470c&v=4 url: https://github.com/iudeen -- login: Kludex +- login: imacat count: 5 + avatarUrl: https://avatars.githubusercontent.com/u/594968?v=4 + url: https://github.com/imacat +- login: Kludex + count: 3 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex -- login: odiseo0 - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/87550035?u=ab724eae71c3fe1cf81e8dc76e73415da926ef7d&v=4 - url: https://github.com/odiseo0 -- login: jonatasoli - count: 3 - avatarUrl: https://avatars.githubusercontent.com/u/26334101?u=071c062d2861d3dd127f6b4a5258cd8ef55d4c50&v=4 - url: https://github.com/jonatasoli top_contributors: - login: waynerv count: 25 @@ -236,25 +228,29 @@ top_contributors: avatarUrl: https://avatars.githubusercontent.com/u/35119617?u=58ed2a45798a4339700e2f62b2e12e6e54bf0396&v=4 url: https://github.com/dmontagu - login: jaystone776 - count: 15 + count: 16 avatarUrl: https://avatars.githubusercontent.com/u/11191137?u=299205a95e9b6817a43144a48b643346a5aac5cc&v=4 url: https://github.com/jaystone776 - login: euri10 count: 13 avatarUrl: https://avatars.githubusercontent.com/u/1104190?u=321a2e953e6645a7d09b732786c7a8061e0f8a8b&v=4 url: https://github.com/euri10 +- login: Kludex + count: 13 + avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 + url: https://github.com/Kludex - login: mariacamilagl count: 12 avatarUrl: https://avatars.githubusercontent.com/u/11489395?u=4adb6986bf3debfc2b8216ae701f2bd47d73da7d&v=4 url: https://github.com/mariacamilagl -- login: Kludex - count: 11 - avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 - url: https://github.com/Kludex - login: Smlep count: 10 avatarUrl: https://avatars.githubusercontent.com/u/16785985?v=4 url: https://github.com/Smlep +- login: dependabot + count: 9 + avatarUrl: https://avatars.githubusercontent.com/in/29110?v=4 + url: https://github.com/apps/dependabot - login: Serrones count: 8 avatarUrl: https://avatars.githubusercontent.com/u/22691749?u=4795b880e13ca33a73e52fc0ef7dc9c60c8fce47&v=4 @@ -279,10 +275,10 @@ top_contributors: count: 5 avatarUrl: https://avatars.githubusercontent.com/u/1175560?v=4 url: https://github.com/Attsun1031 -- login: dependabot +- login: ComicShrimp count: 5 - avatarUrl: https://avatars.githubusercontent.com/in/29110?v=4 - url: https://github.com/apps/dependabot + avatarUrl: https://avatars.githubusercontent.com/u/43503750?u=b3e4d9a14d9a65d429ce62c566aef73178b7111d&v=4 + url: https://github.com/ComicShrimp - login: jekirl count: 4 avatarUrl: https://avatars.githubusercontent.com/u/2546697?u=a027452387d85bd4a14834e19d716c99255fb3b7&v=4 @@ -303,25 +299,29 @@ top_contributors: count: 4 avatarUrl: https://avatars.githubusercontent.com/u/3360631?u=5fa1f475ad784d64eb9666bdd43cc4d285dcc773&v=4 url: https://github.com/hitrust +- login: rjNemo + count: 4 + avatarUrl: https://avatars.githubusercontent.com/u/56785022?u=d5c3a02567c8649e146fcfc51b6060ccaf8adef8&v=4 + url: https://github.com/rjNemo - login: lsglucas count: 4 avatarUrl: https://avatars.githubusercontent.com/u/61513630?u=320e43fe4dc7bc6efc64e9b8f325f8075634fd20&v=4 url: https://github.com/lsglucas -- login: ComicShrimp - count: 4 - avatarUrl: https://avatars.githubusercontent.com/u/43503750?u=b3e4d9a14d9a65d429ce62c566aef73178b7111d&v=4 - url: https://github.com/ComicShrimp - login: NinaHwang count: 4 avatarUrl: https://avatars.githubusercontent.com/u/79563565?u=1741703bd6c8f491503354b363a86e879b4c1cab&v=4 url: https://github.com/NinaHwang top_reviewers: - login: Kludex - count: 95 + count: 96 avatarUrl: https://avatars.githubusercontent.com/u/7353520?u=62adc405ef418f4b6c8caa93d3eb8ab107bc4927&v=4 url: https://github.com/Kludex +- login: BilalAlpaslan + count: 51 + avatarUrl: https://avatars.githubusercontent.com/u/47563997?u=63ed66e304fe8d765762c70587d61d9196e5c82d&v=4 + url: https://github.com/BilalAlpaslan - login: tokusumi - count: 49 + count: 50 avatarUrl: https://avatars.githubusercontent.com/u/41147016?u=55010621aece725aa702270b54fed829b6a1fe60&v=4 url: https://github.com/tokusumi - login: waynerv @@ -332,10 +332,6 @@ top_reviewers: count: 47 avatarUrl: https://avatars.githubusercontent.com/u/59285379?v=4 url: https://github.com/Laineyzhang55 -- login: BilalAlpaslan - count: 45 - avatarUrl: https://avatars.githubusercontent.com/u/47563997?u=63ed66e304fe8d765762c70587d61d9196e5c82d&v=4 - url: https://github.com/BilalAlpaslan - login: ycd count: 45 avatarUrl: https://avatars.githubusercontent.com/u/62724709?u=826f228edf0bab0d19ad1d5c4ba4df1047ccffef&v=4 @@ -345,7 +341,7 @@ top_reviewers: avatarUrl: https://avatars.githubusercontent.com/u/24587499?u=e772190a051ab0eaa9c8542fcff1892471638f2b&v=4 url: https://github.com/cikay - login: yezz123 - count: 34 + count: 39 avatarUrl: https://avatars.githubusercontent.com/u/52716203?u=636b4f79645176df4527dd45c12d5dbb5a4193cf&v=4 url: https://github.com/yezz123 - login: AdrianDeAnda @@ -356,6 +352,10 @@ top_reviewers: count: 31 avatarUrl: https://avatars.githubusercontent.com/u/31127044?u=b0f2c37142f4b762e41ad65dc49581813422bd71&v=4 url: https://github.com/ArcLightSlavik +- login: JarroVGIT + count: 27 + avatarUrl: https://avatars.githubusercontent.com/u/13659033?u=e8bea32d07a5ef72f7dde3b2079ceb714923ca05&v=4 + url: https://github.com/JarroVGIT - login: cassiobotaro count: 25 avatarUrl: https://avatars.githubusercontent.com/u/3127847?u=b0a652331da17efeb85cd6e3a4969182e5004804&v=4 @@ -369,7 +369,7 @@ top_reviewers: avatarUrl: https://avatars.githubusercontent.com/u/39375566?u=260ad6b1a4b34c07dbfa728da5e586f16f6d1824&v=4 url: https://github.com/komtaki - login: hard-coders - count: 19 + count: 20 avatarUrl: https://avatars.githubusercontent.com/u/9651103?u=95db33927bbff1ed1c07efddeb97ac2ff33068ed&v=4 url: https://github.com/hard-coders - login: 0417taehyun @@ -380,10 +380,6 @@ top_reviewers: count: 18 avatarUrl: https://avatars.githubusercontent.com/u/61513630?u=320e43fe4dc7bc6efc64e9b8f325f8075634fd20&v=4 url: https://github.com/lsglucas -- login: JarroVGIT - count: 18 - avatarUrl: https://avatars.githubusercontent.com/u/13659033?u=e8bea32d07a5ef72f7dde3b2079ceb714923ca05&v=4 - url: https://github.com/JarroVGIT - login: zy7y count: 17 avatarUrl: https://avatars.githubusercontent.com/u/67154681?u=5d634834cc514028ea3f9115f7030b99a1f4d5a4&v=4 @@ -424,6 +420,14 @@ top_reviewers: count: 12 avatarUrl: https://avatars.githubusercontent.com/u/31848542?u=efb5b45b55584450507834f279ce48d4d64dea2f&v=4 url: https://github.com/RunningIkkyu +- login: odiseo0 + count: 12 + avatarUrl: https://avatars.githubusercontent.com/u/87550035?u=ab724eae71c3fe1cf81e8dc76e73415da926ef7d&v=4 + url: https://github.com/odiseo0 +- login: LorhanSohaky + count: 11 + avatarUrl: https://avatars.githubusercontent.com/u/16273730?u=095b66f243a2cd6a0aadba9a095009f8aaf18393&v=4 + url: https://github.com/LorhanSohaky - login: solomein-sv count: 11 avatarUrl: https://avatars.githubusercontent.com/u/46193920?u=46acfb4aeefb1d7b9fdc5a8cbd9eb8744683c47a&v=4 @@ -440,10 +444,10 @@ top_reviewers: count: 10 avatarUrl: https://avatars.githubusercontent.com/u/7887703?v=4 url: https://github.com/maoyibo -- login: odiseo0 +- login: ComicShrimp count: 10 - avatarUrl: https://avatars.githubusercontent.com/u/87550035?u=ab724eae71c3fe1cf81e8dc76e73415da926ef7d&v=4 - url: https://github.com/odiseo0 + avatarUrl: https://avatars.githubusercontent.com/u/43503750?u=b3e4d9a14d9a65d429ce62c566aef73178b7111d&v=4 + url: https://github.com/ComicShrimp - login: graingert count: 9 avatarUrl: https://avatars.githubusercontent.com/u/413772?v=4 @@ -460,6 +464,10 @@ top_reviewers: count: 9 avatarUrl: https://avatars.githubusercontent.com/u/69092910?u=4ac58eab99bd37d663f3d23551df96d4fbdbf760&v=4 url: https://github.com/bezaca +- login: izaguerreiro + count: 8 + avatarUrl: https://avatars.githubusercontent.com/u/2241504?v=4 + url: https://github.com/izaguerreiro - login: raphaelauv count: 8 avatarUrl: https://avatars.githubusercontent.com/u/10202690?u=e6f86f5c0c3026a15d6b51792fa3e532b12f1371&v=4 @@ -472,10 +480,6 @@ top_reviewers: count: 8 avatarUrl: https://avatars.githubusercontent.com/u/5690226?v=4 url: https://github.com/rogerbrinkmann -- login: ComicShrimp - count: 8 - avatarUrl: https://avatars.githubusercontent.com/u/43503750?u=b3e4d9a14d9a65d429ce62c566aef73178b7111d&v=4 - url: https://github.com/ComicShrimp - login: NinaHwang count: 8 avatarUrl: https://avatars.githubusercontent.com/u/79563565?u=1741703bd6c8f491503354b363a86e879b4c1cab&v=4 @@ -488,6 +492,10 @@ top_reviewers: count: 7 avatarUrl: https://avatars.githubusercontent.com/u/22691749?u=4795b880e13ca33a73e52fc0ef7dc9c60c8fce47&v=4 url: https://github.com/Serrones +- login: jovicon + count: 7 + avatarUrl: https://avatars.githubusercontent.com/u/21287303?u=b049eac3e51a4c0473c2efe66b4d28a7d8f2b572&v=4 + url: https://github.com/jovicon - login: ryuckel count: 7 avatarUrl: https://avatars.githubusercontent.com/u/36391432?u=094eec0cfddd5013f76f31e55e56147d78b19553&v=4 @@ -500,15 +508,3 @@ top_reviewers: count: 7 avatarUrl: https://avatars.githubusercontent.com/u/1405026?v=4 url: https://github.com/Mause -- login: wakabame - count: 7 - avatarUrl: https://avatars.githubusercontent.com/u/35513518?v=4 - url: https://github.com/wakabame -- login: AlexandreBiguet - count: 7 - avatarUrl: https://avatars.githubusercontent.com/u/1483079?u=ff926455cd4cab03c6c49441aa5dc2b21df3e266&v=4 - url: https://github.com/AlexandreBiguet -- login: krocdort - count: 7 - avatarUrl: https://avatars.githubusercontent.com/u/34248814?v=4 - url: https://github.com/krocdort From d0cc996dc7000542beb95286834c55bd785a78eb Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 4 Sep 2022 15:17:43 +0000 Subject: [PATCH 177/194] =?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 327175a76525b..9232db7f122c3 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 👥 Update FastAPI People. PR [#5347](https://github.com/tiangolo/fastapi/pull/5347) by [@github-actions[bot]](https://github.com/apps/github-actions). * ✨ Export `WebSocketState` in `fastapi.websockets`. PR [#4376](https://github.com/tiangolo/fastapi/pull/4376) by [@matiuszka](https://github.com/matiuszka). * 🐛 Fix FastAPI People GitHub Action: set HTTPX timeout for GraphQL query request. PR [#5222](https://github.com/tiangolo/fastapi/pull/5222) by [@iudeen](https://github.com/iudeen). * ✏ Update Hypercorn link, now pointing to GitHub. PR [#5346](https://github.com/tiangolo/fastapi/pull/5346) by [@baconfield](https://github.com/baconfield). From f8460a8b54fd4975ca64c7fbe8d516740781f0df Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Sun, 4 Sep 2022 14:09:24 -0500 Subject: [PATCH 178/194] =?UTF-8?q?=F0=9F=90=9B=20Allow=20exit=20code=20fo?= =?UTF-8?q?r=20dependencies=20with=20`yield`=20to=20always=20execute,=20by?= =?UTF-8?q?=20removing=20capacity=20limiter=20for=20them,=20to=20e.g.=20al?= =?UTF-8?q?low=20closing=20DB=20connections=20without=20deadlocks=20(#5122?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- fastapi/concurrency.py | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/fastapi/concurrency.py b/fastapi/concurrency.py index becac3f33db76..c728ec1d22915 100644 --- a/fastapi/concurrency.py +++ b/fastapi/concurrency.py @@ -1,6 +1,8 @@ import sys from typing import AsyncGenerator, ContextManager, TypeVar +import anyio +from anyio import CapacityLimiter from starlette.concurrency import iterate_in_threadpool as iterate_in_threadpool # noqa from starlette.concurrency import run_in_threadpool as run_in_threadpool # noqa from starlette.concurrency import ( # noqa @@ -22,11 +24,24 @@ async def contextmanager_in_threadpool( cm: ContextManager[_T], ) -> AsyncGenerator[_T, None]: + # blocking __exit__ from running waiting on a free thread + # can create race conditions/deadlocks if the context manager itself + # has it's own internal pool (e.g. a database connection pool) + # to avoid this we let __exit__ run without a capacity limit + # since we're creating a new limiter for each call, any non-zero limit + # works (1 is arbitrary) + exit_limiter = CapacityLimiter(1) try: yield await run_in_threadpool(cm.__enter__) except Exception as e: - ok: bool = await run_in_threadpool(cm.__exit__, type(e), e, None) + ok = bool( + await anyio.to_thread.run_sync( + cm.__exit__, type(e), e, None, limiter=exit_limiter + ) + ) if not ok: raise e else: - await run_in_threadpool(cm.__exit__, None, None, None) + await anyio.to_thread.run_sync( + cm.__exit__, None, None, None, limiter=exit_limiter + ) From f3efaf69da4dd6e00dbc871b418f74d3338b7c3a Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 4 Sep 2022 19:10:05 +0000 Subject: [PATCH 179/194] =?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 9232db7f122c3..f44cd4f6e03c8 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 🐛 Allow exit code for dependencies with `yield` to always execute, by removing capacity limiter for them, to e.g. allow closing DB connections without deadlocks. PR [#5122](https://github.com/tiangolo/fastapi/pull/5122) by [@adriangb](https://github.com/adriangb). * 👥 Update FastAPI People. PR [#5347](https://github.com/tiangolo/fastapi/pull/5347) by [@github-actions[bot]](https://github.com/apps/github-actions). * ✨ Export `WebSocketState` in `fastapi.websockets`. PR [#4376](https://github.com/tiangolo/fastapi/pull/4376) by [@matiuszka](https://github.com/matiuszka). * 🐛 Fix FastAPI People GitHub Action: set HTTPX timeout for GraphQL query request. PR [#5222](https://github.com/tiangolo/fastapi/pull/5222) by [@iudeen](https://github.com/iudeen). From ddf6daeb0759c6e0cb2cfc6af075ba95dd271779 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sun, 4 Sep 2022 21:25:29 +0200 Subject: [PATCH 180/194] =?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 | 48 +++++++++++++++++++++++++---------- 1 file changed, 34 insertions(+), 14 deletions(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index f44cd4f6e03c8..4b241cdd6dbcf 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,30 +2,50 @@ ## Latest Changes -* 🐛 Allow exit code for dependencies with `yield` to always execute, by removing capacity limiter for them, to e.g. allow closing DB connections without deadlocks. PR [#5122](https://github.com/tiangolo/fastapi/pull/5122) by [@adriangb](https://github.com/adriangb). -* 👥 Update FastAPI People. PR [#5347](https://github.com/tiangolo/fastapi/pull/5347) by [@github-actions[bot]](https://github.com/apps/github-actions). +🚨 This is probably the last release (or one of the last releases) to support Python 3.6. 🔥 + +Python 3.6 reached the [end-of-life and is no longer supported by Python](https://www.python.org/downloads/release/python-3615/) since around a year ago. + +You hopefully updated to a supported version of Python a while ago. If you haven't, you really should. + +### Features + * ✨ Export `WebSocketState` in `fastapi.websockets`. PR [#4376](https://github.com/tiangolo/fastapi/pull/4376) by [@matiuszka](https://github.com/matiuszka). +* ✨ Support Python internal description on Pydantic model's docstring. PR [#3032](https://github.com/tiangolo/fastapi/pull/3032) by [@Kludex](https://github.com/Kludex). +* ✨ Update `ORJSONResponse` to support non `str` keys and serializing Numpy arrays. PR [#3892](https://github.com/tiangolo/fastapi/pull/3892) by [@baby5](https://github.com/baby5). + +### Fixes + +* 🐛 Allow exit code for dependencies with `yield` to always execute, by removing capacity limiter for them, to e.g. allow closing DB connections without deadlocks. PR [#5122](https://github.com/tiangolo/fastapi/pull/5122) by [@adriangb](https://github.com/adriangb). * 🐛 Fix FastAPI People GitHub Action: set HTTPX timeout for GraphQL query request. PR [#5222](https://github.com/tiangolo/fastapi/pull/5222) by [@iudeen](https://github.com/iudeen). +* 🐛 Make sure a parameter defined as required is kept required in OpenAPI even if defined as optional in another dependency. PR [#4319](https://github.com/tiangolo/fastapi/pull/4319) by [@cd17822](https://github.com/cd17822). +* 🐛 Fix support for path parameters in WebSockets. PR [#3879](https://github.com/tiangolo/fastapi/pull/3879) by [@davidbrochart](https://github.com/davidbrochart). + +### Docs + * ✏ Update Hypercorn link, now pointing to GitHub. PR [#5346](https://github.com/tiangolo/fastapi/pull/5346) by [@baconfield](https://github.com/baconfield). +* ✏ Tweak wording in `docs/en/docs/advanced/dataclasses.md`. PR [#3698](https://github.com/tiangolo/fastapi/pull/3698) by [@pfackeldey](https://github.com/pfackeldey). +* 📝 Add note about Python 3.10 `X | Y` operator in explanation about Response Models. PR [#5307](https://github.com/tiangolo/fastapi/pull/5307) by [@MendyLanda](https://github.com/MendyLanda). +* 📝 Add link to New Relic article: "How to monitor FastAPI application performance using Python agent". PR [#5260](https://github.com/tiangolo/fastapi/pull/5260) by [@sjyothi54](https://github.com/sjyothi54). +* 📝 Update docs for `ORJSONResponse` with details about improving performance. PR [#2615](https://github.com/tiangolo/fastapi/pull/2615) by [@falkben](https://github.com/falkben). +* 📝 Add docs for creating a custom Response class. PR [#5331](https://github.com/tiangolo/fastapi/pull/5331) by [@tiangolo](https://github.com/tiangolo). +* 📝 Add tip about using alias for form data fields. PR [#5329](https://github.com/tiangolo/fastapi/pull/5329) by [@tiangolo](https://github.com/tiangolo). + +### Translations + * 🌐 Add Russian translation for `docs/ru/docs/features.md`. PR [#5315](https://github.com/tiangolo/fastapi/pull/5315) by [@Xewus](https://github.com/Xewus). -* ⬆ Bump dawidd6/action-download-artifact from 2.22.0 to 2.23.0. PR [#5321](https://github.com/tiangolo/fastapi/pull/5321) by [@dependabot[bot]](https://github.com/apps/dependabot). -* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#5318](https://github.com/tiangolo/fastapi/pull/5318) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). * 🌐 Update Chinese translation for `docs/zh/docs/tutorial/request-files.md`. PR [#4529](https://github.com/tiangolo/fastapi/pull/4529) by [@ASpathfinder](https://github.com/ASpathfinder). * 🌐 Add Chinese translation for `docs/zh/docs/tutorial/encoder.md`. PR [#4969](https://github.com/tiangolo/fastapi/pull/4969) by [@Zssaer](https://github.com/Zssaer). -* ✏ Tweak wording in `docs/en/docs/advanced/dataclasses.md`. PR [#3698](https://github.com/tiangolo/fastapi/pull/3698) by [@pfackeldey](https://github.com/pfackeldey). -* 📝 Add note about Python 3.10 `X | Y` operator in explanation about Response Models. PR [#5307](https://github.com/tiangolo/fastapi/pull/5307) by [@MendyLanda](https://github.com/MendyLanda). * 🌐 Fix MkDocs file line for Portuguese translation of `background-task.md`. PR [#5242](https://github.com/tiangolo/fastapi/pull/5242) by [@ComicShrimp](https://github.com/ComicShrimp). + +### Internal + +* 👥 Update FastAPI People. PR [#5347](https://github.com/tiangolo/fastapi/pull/5347) by [@github-actions[bot]](https://github.com/apps/github-actions). +* ⬆ Bump dawidd6/action-download-artifact from 2.22.0 to 2.23.0. PR [#5321](https://github.com/tiangolo/fastapi/pull/5321) by [@dependabot[bot]](https://github.com/apps/dependabot). +* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#5318](https://github.com/tiangolo/fastapi/pull/5318) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). * ✏ Fix a small code highlight line error. PR [#5256](https://github.com/tiangolo/fastapi/pull/5256) by [@hjlarry](https://github.com/hjlarry). -* 📝 Add link to New Relic article: "How to monitor FastAPI application performance using Python agent". PR [#5260](https://github.com/tiangolo/fastapi/pull/5260) by [@sjyothi54](https://github.com/sjyothi54). -* 🐛 Make sure a parameter defined as required is kept required in OpenAPI even if defined as optional in another dependency. PR [#4319](https://github.com/tiangolo/fastapi/pull/4319) by [@cd17822](https://github.com/cd17822). * ♻ Internal small refactor, move `operation_id` parameter position in delete method for consistency with the code. PR [#4474](https://github.com/tiangolo/fastapi/pull/4474) by [@hiel](https://github.com/hiel). -* ✨ Support Python internal description on Pydantic model's docstring. PR [#3032](https://github.com/tiangolo/fastapi/pull/3032) by [@Kludex](https://github.com/Kludex). -* ✨ Update `ORJSONResponse` to support non `str` keys and serializing Numpy arrays. PR [#3892](https://github.com/tiangolo/fastapi/pull/3892) by [@baby5](https://github.com/baby5). * 🔧 Update sponsors, disable ImgWhale. PR [#5338](https://github.com/tiangolo/fastapi/pull/5338) by [@tiangolo](https://github.com/tiangolo). -* 📝 Update docs for `ORJSONResponse` with details about improving performance. PR [#2615](https://github.com/tiangolo/fastapi/pull/2615) by [@falkben](https://github.com/falkben). -* 📝 Add docs for creating a custom Response class. PR [#5331](https://github.com/tiangolo/fastapi/pull/5331) by [@tiangolo](https://github.com/tiangolo). -* 📝 Add tip about using alias for form data fields. PR [#5329](https://github.com/tiangolo/fastapi/pull/5329) by [@tiangolo](https://github.com/tiangolo). -* 🐛 Fix support for path parameters in WebSockets. PR [#3879](https://github.com/tiangolo/fastapi/pull/3879) by [@davidbrochart](https://github.com/davidbrochart). ## 0.81.0 From 3079ba925ec04ce2a630d3d919a1308b48a45df0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sun, 4 Sep 2022 21:26:31 +0200 Subject: [PATCH 181/194] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.82?= =?UTF-8?q?.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 3 +++ fastapi/__init__.py | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 4b241cdd6dbcf..303e6b8e11403 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,9 @@ ## Latest Changes + +## 0.82.0 + 🚨 This is probably the last release (or one of the last releases) to support Python 3.6. 🔥 Python 3.6 reached the [end-of-life and is no longer supported by Python](https://www.python.org/downloads/release/python-3615/) since around a year ago. diff --git a/fastapi/__init__.py b/fastapi/__init__.py index 3688ec89f021e..c50543bf990b4 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.81.0" +__version__ = "0.82.0" from starlette import status as status From ef5d6181b62214eee73ccdaf8617e8e3ea39a6ea Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Thu, 8 Sep 2022 16:08:33 +0200 Subject: [PATCH 182/194] =?UTF-8?q?=E2=AC=86=20[pre-commit.ci]=20pre-commi?= =?UTF-8?q?t=20autoupdate=20(#5352)?= 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> --- .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 237feb083882f..c4c1d4d9e8787 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -19,7 +19,7 @@ repos: - --py3-plus - --keep-runtime-typing - repo: https://github.com/myint/autoflake - rev: v1.5.1 + rev: v1.5.3 hooks: - id: autoflake args: @@ -43,7 +43,7 @@ repos: name: isort (pyi) types: [pyi] - repo: https://github.com/psf/black - rev: 22.6.0 + rev: 22.8.0 hooks: - id: black ci: From 895789bed0280865b8aa85973dc35d89f33730b5 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 8 Sep 2022 14:09:15 +0000 Subject: [PATCH 183/194] =?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 303e6b8e11403..ba5d7b26fcebb 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#5352](https://github.com/tiangolo/fastapi/pull/5352) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). ## 0.82.0 From 3ec498af63ddc994a7c70f1a05407ea5f7095be4 Mon Sep 17 00:00:00 2001 From: DCsunset Date: Thu, 8 Sep 2022 10:29:23 -0400 Subject: [PATCH 184/194] =?UTF-8?q?=E2=9C=A8=20Add=20support=20in=20`jsona?= =?UTF-8?q?ble=5Fencoder`=20for=20include=20and=20exclude=20with=20datacla?= =?UTF-8?q?sses=20(#4923)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sebastián Ramírez --- fastapi/encoders.py | 6 +++++- tests/test_jsonable_encoder.py | 16 ++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/fastapi/encoders.py b/fastapi/encoders.py index f64e4b86ea3b4..93045ca27f158 100644 --- a/fastapi/encoders.py +++ b/fastapi/encoders.py @@ -74,8 +74,12 @@ def jsonable_encoder( obj_dict = dataclasses.asdict(obj) return jsonable_encoder( obj_dict, - exclude_none=exclude_none, + include=include, + exclude=exclude, + by_alias=by_alias, + exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, + exclude_none=exclude_none, custom_encoder=custom_encoder, sqlalchemy_safe=sqlalchemy_safe, ) diff --git a/tests/test_jsonable_encoder.py b/tests/test_jsonable_encoder.py index 5e55f2f918467..f4fdcf6014a43 100644 --- a/tests/test_jsonable_encoder.py +++ b/tests/test_jsonable_encoder.py @@ -1,3 +1,4 @@ +from dataclasses import dataclass from datetime import datetime, timezone from enum import Enum from pathlib import PurePath, PurePosixPath, PureWindowsPath @@ -19,6 +20,12 @@ def __init__(self, owner: Person, name: str): self.name = name +@dataclass +class Item: + name: str + count: int + + class DictablePerson(Person): def __iter__(self): return ((k, v) for k, v in self.__dict__.items()) @@ -131,6 +138,15 @@ def test_encode_dictable(): } +def test_encode_dataclass(): + item = Item(name="foo", count=100) + assert jsonable_encoder(item) == {"name": "foo", "count": 100} + assert jsonable_encoder(item, include={"name"}) == {"name": "foo"} + assert jsonable_encoder(item, exclude={"count"}) == {"name": "foo"} + assert jsonable_encoder(item, include={}) == {} + assert jsonable_encoder(item, exclude={}) == {"name": "foo", "count": 100} + + def test_encode_unsupported(): unserializable = Unserializable() with pytest.raises(ValueError): From c4007cb9ecacd54df95e29780976937af01ff5ae Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 8 Sep 2022 14:30:00 +0000 Subject: [PATCH 185/194] =?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 ba5d7b26fcebb..bc58b578d3f86 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* ✨ Add support in `jsonable_encoder` for include and exclude with dataclasses. PR [#4923](https://github.com/tiangolo/fastapi/pull/4923) by [@DCsunset](https://github.com/DCsunset). * ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#5352](https://github.com/tiangolo/fastapi/pull/5352) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). ## 0.82.0 From 0b4fe10c8fed59de02100612a6168a9aefaf3659 Mon Sep 17 00:00:00 2001 From: Thomas Meckel <14177833+tmeckel@users.noreply.github.com> Date: Thu, 8 Sep 2022 17:02:59 +0200 Subject: [PATCH 186/194] =?UTF-8?q?=F0=9F=90=9B=20Fix=20empty=20reponse=20?= =?UTF-8?q?body=20when=20default=20`status=5Fcode`=20is=20empty=20but=20th?= =?UTF-8?q?e=20a=20`Response`=20parameter=20with=20`response.status=5Fcode?= =?UTF-8?q?`=20is=20set=20(#5360)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Thomas Meckel Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Sebastián Ramírez --- fastapi/routing.py | 2 +- tests/test_reponse_set_reponse_code_empty.py | 97 ++++++++++++++++++++ 2 files changed, 98 insertions(+), 1 deletion(-) create mode 100644 tests/test_reponse_set_reponse_code_empty.py diff --git a/fastapi/routing.py b/fastapi/routing.py index 233f79fcbf126..710cb97346127 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -258,7 +258,7 @@ async def app(request: Request) -> Response: is_coroutine=is_coroutine, ) response = actual_response_class(content, **response_args) - if not is_body_allowed_for_status_code(status_code): + if not is_body_allowed_for_status_code(response.status_code): response.body = b"" response.headers.raw.extend(sub_response.headers.raw) return response diff --git a/tests/test_reponse_set_reponse_code_empty.py b/tests/test_reponse_set_reponse_code_empty.py new file mode 100644 index 0000000000000..094d54a84b60c --- /dev/null +++ b/tests/test_reponse_set_reponse_code_empty.py @@ -0,0 +1,97 @@ +from typing import Any + +from fastapi import FastAPI, Response +from fastapi.testclient import TestClient + +app = FastAPI() + + +@app.delete( + "/{id}", + status_code=204, +) +async def delete_deployment( + id: int, + response: Response, +) -> Any: + response.status_code = 400 + return {"msg": "Status overwritten", "id": id} + + +client = TestClient(app) + + +openapi_schema = { + "openapi": "3.0.2", + "info": {"title": "FastAPI", "version": "0.1.0"}, + "paths": { + "/{id}": { + "delete": { + "summary": "Delete Deployment", + "operationId": "delete_deployment__id__delete", + "parameters": [ + { + "required": True, + "schema": {"title": "Id", "type": "integer"}, + "name": "id", + "in": "path", + } + ], + "responses": { + "204": {"description": "Successful Response"}, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + }, + }, + } + } + }, + "components": { + "schemas": { + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": {"$ref": "#/components/schemas/ValidationError"}, + } + }, + }, + "ValidationError": { + "title": "ValidationError", + "required": ["loc", "msg", "type"], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": {"anyOf": [{"type": "string"}, {"type": "integer"}]}, + }, + "msg": {"title": "Message", "type": "string"}, + "type": {"title": "Error Type", "type": "string"}, + }, + }, + } + }, +} + + +def test_openapi_schema(): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + assert response.json() == openapi_schema + + +def test_dependency_set_status_code(): + response = client.delete("/1") + assert response.status_code == 400 and response.content + assert response.json() == {"msg": "Status overwritten", "id": 1} From 6620273083275f7fec446bb3456d3df6582c6813 Mon Sep 17 00:00:00 2001 From: github-actions Date: Thu, 8 Sep 2022 15:03:37 +0000 Subject: [PATCH 187/194] =?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 bc58b578d3f86..7d0a16c9585c4 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 🐛 Fix empty reponse body when default `status_code` is empty but the a `Response` parameter with `response.status_code` is set. PR [#5360](https://github.com/tiangolo/fastapi/pull/5360) by [@tmeckel](https://github.com/tmeckel). * ✨ Add support in `jsonable_encoder` for include and exclude with dataclasses. PR [#4923](https://github.com/tiangolo/fastapi/pull/4923) by [@DCsunset](https://github.com/DCsunset). * ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#5352](https://github.com/tiangolo/fastapi/pull/5352) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). From 4d270463af2279d9723d99da45f0b31631424030 Mon Sep 17 00:00:00 2001 From: Irfanuddin Shafi Ahmed Date: Sun, 11 Sep 2022 21:43:36 +0530 Subject: [PATCH 188/194] =?UTF-8?q?=F0=9F=90=9BFix=20`RuntimeError`=20rais?= =?UTF-8?q?ed=20when=20`HTTPException`=20has=20a=20status=20code=20with=20?= =?UTF-8?q?no=20content=20(#5365)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Marcelo Trylesinski Co-authored-by: Sebastián Ramírez --- fastapi/exception_handlers.py | 16 +++++------ tests/test_starlette_exception.py | 46 +++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 8 deletions(-) diff --git a/fastapi/exception_handlers.py b/fastapi/exception_handlers.py index 2b286d71c7610..4d7ea5ec2e44b 100644 --- a/fastapi/exception_handlers.py +++ b/fastapi/exception_handlers.py @@ -1,19 +1,19 @@ from fastapi.encoders import jsonable_encoder from fastapi.exceptions import RequestValidationError +from fastapi.utils import is_body_allowed_for_status_code from starlette.exceptions import HTTPException from starlette.requests import Request -from starlette.responses import JSONResponse +from starlette.responses import JSONResponse, Response from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY -async def http_exception_handler(request: Request, exc: HTTPException) -> JSONResponse: +async def http_exception_handler(request: Request, exc: HTTPException) -> Response: headers = getattr(exc, "headers", None) - if headers: - return JSONResponse( - {"detail": exc.detail}, status_code=exc.status_code, headers=headers - ) - else: - return JSONResponse({"detail": exc.detail}, status_code=exc.status_code) + if not is_body_allowed_for_status_code(exc.status_code): + return Response(status_code=exc.status_code, headers=headers) + return JSONResponse( + {"detail": exc.detail}, status_code=exc.status_code, headers=headers + ) async def request_validation_exception_handler( diff --git a/tests/test_starlette_exception.py b/tests/test_starlette_exception.py index 859169d3cdad8..2b6712f7b6c58 100644 --- a/tests/test_starlette_exception.py +++ b/tests/test_starlette_exception.py @@ -18,6 +18,16 @@ async def read_item(item_id: str): return {"item": items[item_id]} +@app.get("/http-no-body-statuscode-exception") +async def no_body_status_code_exception(): + raise HTTPException(status_code=204) + + +@app.get("/http-no-body-statuscode-with-detail-exception") +async def no_body_status_code_with_detail_exception(): + raise HTTPException(status_code=204, detail="I should just disappear!") + + @app.get("/starlette-items/{item_id}") async def read_starlette_item(item_id: str): if item_id not in items: @@ -31,6 +41,30 @@ async def read_starlette_item(item_id: str): "openapi": "3.0.2", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { + "/http-no-body-statuscode-exception": { + "get": { + "operationId": "no_body_status_code_exception_http_no_body_statuscode_exception_get", + "responses": { + "200": { + "content": {"application/json": {"schema": {}}}, + "description": "Successful " "Response", + } + }, + "summary": "No Body " "Status " "Code " "Exception", + } + }, + "/http-no-body-statuscode-with-detail-exception": { + "get": { + "operationId": "no_body_status_code_with_detail_exception_http_no_body_statuscode_with_detail_exception_get", + "responses": { + "200": { + "content": {"application/json": {"schema": {}}}, + "description": "Successful " "Response", + } + }, + "summary": "No Body Status Code With Detail Exception", + } + }, "/items/{item_id}": { "get": { "responses": { @@ -154,3 +188,15 @@ def test_get_starlette_item_not_found(): assert response.status_code == 404, response.text assert response.headers.get("x-error") is None assert response.json() == {"detail": "Item not found"} + + +def test_no_body_status_code_exception_handlers(): + response = client.get("/http-no-body-statuscode-exception") + assert response.status_code == 204 + assert not response.content + + +def test_no_body_status_code_with_detail_exception_handlers(): + response = client.get("/http-no-body-statuscode-with-detail-exception") + assert response.status_code == 204 + assert not response.content From 275306c369d7186aebf6e6d7d56be11e6d01c43c Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 11 Sep 2022 16:14:21 +0000 Subject: [PATCH 189/194] =?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 7d0a16c9585c4..92e1dfe77b71a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 🐛Fix `RuntimeError` raised when `HTTPException` has a status code with no content. PR [#5365](https://github.com/tiangolo/fastapi/pull/5365) by [@iudeen](https://github.com/iudeen). * 🐛 Fix empty reponse body when default `status_code` is empty but the a `Response` parameter with `response.status_code` is set. PR [#5360](https://github.com/tiangolo/fastapi/pull/5360) by [@tmeckel](https://github.com/tmeckel). * ✨ Add support in `jsonable_encoder` for include and exclude with dataclasses. PR [#4923](https://github.com/tiangolo/fastapi/pull/4923) by [@DCsunset](https://github.com/DCsunset). * ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#5352](https://github.com/tiangolo/fastapi/pull/5352) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). From 4fec12b354c7d87101aac60d0143236afcd8678f Mon Sep 17 00:00:00 2001 From: Marcelo Trylesinski Date: Sun, 11 Sep 2022 18:15:49 +0200 Subject: [PATCH 190/194] =?UTF-8?q?=F0=9F=93=9D=20Update=20`SECURITY.md`?= =?UTF-8?q?=20(#5377)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- SECURITY.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SECURITY.md b/SECURITY.md index 322f95f629ccf..db412cf2c8e66 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -6,7 +6,7 @@ Learn more about it below. 👇 ## Versions -The latest versions of FastAPI are supported. +The latest version of FastAPI is supported. You are encouraged to [write tests](https://fastapi.tiangolo.com/tutorial/testing/) for your application and update your FastAPI version frequently after ensuring that your tests are passing. This way you will benefit from the latest features, bug fixes, and **security fixes**. From 306326a2138eff3835901fa34190e4475aed1409 Mon Sep 17 00:00:00 2001 From: github-actions Date: Sun, 11 Sep 2022 16:16:31 +0000 Subject: [PATCH 191/194] =?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 92e1dfe77b71a..9c86e4615b684 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,7 @@ ## Latest Changes +* 📝 Update `SECURITY.md`. PR [#5377](https://github.com/tiangolo/fastapi/pull/5377) by [@Kludex](https://github.com/Kludex). * 🐛Fix `RuntimeError` raised when `HTTPException` has a status code with no content. PR [#5365](https://github.com/tiangolo/fastapi/pull/5365) by [@iudeen](https://github.com/iudeen). * 🐛 Fix empty reponse body when default `status_code` is empty but the a `Response` parameter with `response.status_code` is set. PR [#5360](https://github.com/tiangolo/fastapi/pull/5360) by [@tmeckel](https://github.com/tmeckel). * ✨ Add support in `jsonable_encoder` for include and exclude with dataclasses. PR [#4923](https://github.com/tiangolo/fastapi/pull/4923) by [@DCsunset](https://github.com/DCsunset). From 22a155efc1ba51b215ed0aedcc0054854e85122e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sun, 11 Sep 2022 18:24:46 +0200 Subject: [PATCH 192/194] =?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 | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 9c86e4615b684..bea543c43c38b 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,10 +2,21 @@ ## Latest Changes -* 📝 Update `SECURITY.md`. PR [#5377](https://github.com/tiangolo/fastapi/pull/5377) by [@Kludex](https://github.com/Kludex). -* 🐛Fix `RuntimeError` raised when `HTTPException` has a status code with no content. PR [#5365](https://github.com/tiangolo/fastapi/pull/5365) by [@iudeen](https://github.com/iudeen). -* 🐛 Fix empty reponse body when default `status_code` is empty but the a `Response` parameter with `response.status_code` is set. PR [#5360](https://github.com/tiangolo/fastapi/pull/5360) by [@tmeckel](https://github.com/tmeckel). +### Features + * ✨ Add support in `jsonable_encoder` for include and exclude with dataclasses. PR [#4923](https://github.com/tiangolo/fastapi/pull/4923) by [@DCsunset](https://github.com/DCsunset). + +### Fixes + +* 🐛 Fix `RuntimeError` raised when `HTTPException` has a status code with no content. PR [#5365](https://github.com/tiangolo/fastapi/pull/5365) by [@iudeen](https://github.com/iudeen). +* 🐛 Fix empty reponse body when default `status_code` is empty but the a `Response` parameter with `response.status_code` is set. PR [#5360](https://github.com/tiangolo/fastapi/pull/5360) by [@tmeckel](https://github.com/tmeckel). + +### Docs + +* 📝 Update `SECURITY.md`. PR [#5377](https://github.com/tiangolo/fastapi/pull/5377) by [@Kludex](https://github.com/Kludex). + +### Internal + * ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#5352](https://github.com/tiangolo/fastapi/pull/5352) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci). ## 0.82.0 From ed0fcba7cbea46b0cca74e9fce568f9c7316d8e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sun, 11 Sep 2022 18:25:29 +0200 Subject: [PATCH 193/194] =?UTF-8?q?=F0=9F=94=96=20Release=20version=200.83?= =?UTF-8?q?.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/release-notes.md | 3 +++ fastapi/__init__.py | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index bea543c43c38b..63595da41f58a 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -2,6 +2,9 @@ ## Latest Changes + +## 0.83.0 + ### Features * ✨ Add support in `jsonable_encoder` for include and exclude with dataclasses. PR [#4923](https://github.com/tiangolo/fastapi/pull/4923) by [@DCsunset](https://github.com/DCsunset). diff --git a/fastapi/__init__.py b/fastapi/__init__.py index c50543bf990b4..a9b44fc4a89f7 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.82.0" +__version__ = "0.83.0" from starlette import status as status From b2aa3593be300b57973987fb2489ed01ed9c9f68 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Sun, 11 Sep 2022 18:26:30 +0200 Subject: [PATCH 194/194] =?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 | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/en/docs/release-notes.md b/docs/en/docs/release-notes.md index 63595da41f58a..120b374e2cf98 100644 --- a/docs/en/docs/release-notes.md +++ b/docs/en/docs/release-notes.md @@ -5,6 +5,12 @@ ## 0.83.0 +🚨 This is probably the last release (or one of the last releases) to support Python 3.6. 🔥 + +Python 3.6 reached the [end-of-life and is no longer supported by Python](https://www.python.org/downloads/release/python-3615/) since around a year ago. + +You hopefully updated to a supported version of Python a while ago. If you haven't, you really should. + ### Features * ✨ Add support in `jsonable_encoder` for include and exclude with dataclasses. PR [#4923](https://github.com/tiangolo/fastapi/pull/4923) by [@DCsunset](https://github.com/DCsunset).