]> git.ipfire.org Git - thirdparty/fastapi/fastapi.git/commitdiff
📝 Add docs recommending `Union` over `Optional` and migrate source examples (#4908)
authorSebastián Ramírez <tiangolo@gmail.com>
Sat, 14 May 2022 11:59:59 +0000 (06:59 -0500)
committerGitHub <noreply@github.com>
Sat, 14 May 2022 11:59:59 +0000 (06:59 -0500)
* 📝 Add docs recommending Union over Optional

* 📝 Update docs recommending Union over Optional

* 📝 Update source examples for docs, recommend Union over Optional

* 📝 Update highlighted lines with updated source examples

* 📝 Update highlighted lines in Markdown with recent code changes

* 📝 Update docs, use Union instead of Optional

* ♻️ Update source examples to recommend Union over Optional

* 🎨 Update highlighted code in Markdown after moving from Optional to Union

131 files changed:
README.md
docs/de/docs/index.md
docs/en/docs/advanced/additional-status-codes.md
docs/en/docs/advanced/testing-dependencies.md
docs/en/docs/deployment/docker.md
docs/en/docs/index.md
docs/en/docs/python-types.md
docs/en/docs/tutorial/body-multiple-params.md
docs/en/docs/tutorial/body.md
docs/en/docs/tutorial/dependencies/classes-as-dependencies.md
docs/en/docs/tutorial/dependencies/index.md
docs/en/docs/tutorial/dependencies/sub-dependencies.md
docs/en/docs/tutorial/path-params-numeric-validations.md
docs/en/docs/tutorial/response-model.md
docs/en/docs/tutorial/schema-extra-example.md
docs/es/docs/advanced/additional-status-codes.md
docs/es/docs/index.md
docs/es/docs/tutorial/query-params.md
docs/fa/docs/index.md
docs/fr/docs/index.md
docs/ja/docs/advanced/additional-status-codes.md
docs/ja/docs/tutorial/query-params-str-validations.md
docs/ko/docs/index.md
docs/ko/docs/tutorial/path-params-numeric-validations.md
docs/ko/docs/tutorial/query-params.md
docs/nl/docs/index.md
docs/pl/docs/index.md
docs/pt/docs/index.md
docs/pt/docs/tutorial/body.md
docs/pt/docs/tutorial/query-params-str-validations.md
docs/ru/docs/index.md
docs/sq/docs/index.md
docs/tr/docs/index.md
docs/uk/docs/index.md
docs/zh/docs/advanced/additional-status-codes.md
docs/zh/docs/index.md
docs/zh/docs/tutorial/body-multiple-params.md
docs/zh/docs/tutorial/dependencies/index.md
docs/zh/docs/tutorial/dependencies/sub-dependencies.md
docs/zh/docs/tutorial/path-params-numeric-validations.md
docs/zh/docs/tutorial/query-params-str-validations.md
docs/zh/docs/tutorial/response-model.md
docs/zh/docs/tutorial/schema-extra-example.md
docs_src/additional_responses/tutorial002.py
docs_src/additional_responses/tutorial004.py
docs_src/background_tasks/tutorial002.py
docs_src/body/tutorial001.py
docs_src/body/tutorial002.py
docs_src/body/tutorial003.py
docs_src/body/tutorial004.py
docs_src/body_multiple_params/tutorial002.py
docs_src/body_nested_models/tutorial001.py
docs_src/body_nested_models/tutorial002.py
docs_src/body_nested_models/tutorial002_py39.py
docs_src/body_nested_models/tutorial003.py
docs_src/body_nested_models/tutorial003_py39.py
docs_src/body_nested_models/tutorial004.py
docs_src/body_nested_models/tutorial004_py39.py
docs_src/body_nested_models/tutorial005.py
docs_src/body_nested_models/tutorial005_py39.py
docs_src/body_nested_models/tutorial006.py
docs_src/body_nested_models/tutorial006_py39.py
docs_src/body_nested_models/tutorial007.py
docs_src/body_nested_models/tutorial007_py39.py
docs_src/body_updates/tutorial001.py
docs_src/body_updates/tutorial001_py39.py
docs_src/body_updates/tutorial002.py
docs_src/body_updates/tutorial002_py39.py
docs_src/dataclasses/tutorial001.py
docs_src/dataclasses/tutorial002.py
docs_src/dataclasses/tutorial003.py
docs_src/dependencies/tutorial001.py
docs_src/dependencies/tutorial002.py
docs_src/dependencies/tutorial003.py
docs_src/dependencies/tutorial004.py
docs_src/dependencies/tutorial005.py
docs_src/dependency_testing/tutorial001.py
docs_src/encoder/tutorial001.py
docs_src/extra_data_types/tutorial001.py
docs_src/extra_models/tutorial001.py
docs_src/extra_models/tutorial002.py
docs_src/header_params/tutorial001.py
docs_src/header_params/tutorial002.py
docs_src/header_params/tutorial003.py
docs_src/header_params/tutorial003_py39.py
docs_src/nosql_databases/tutorial001.py
docs_src/openapi_callbacks/tutorial001.py
docs_src/path_operation_advanced_configuration/tutorial004.py
docs_src/path_operation_configuration/tutorial001.py
docs_src/path_operation_configuration/tutorial001_py39.py
docs_src/path_operation_configuration/tutorial002.py
docs_src/path_operation_configuration/tutorial002_py39.py
docs_src/path_operation_configuration/tutorial003.py
docs_src/path_operation_configuration/tutorial003_py39.py
docs_src/path_operation_configuration/tutorial004.py
docs_src/path_operation_configuration/tutorial004_py39.py
docs_src/path_operation_configuration/tutorial005.py
docs_src/path_operation_configuration/tutorial005_py39.py
docs_src/python_types/tutorial009c.py [new file with mode: 0644]
docs_src/python_types/tutorial009c_py310.py [new file with mode: 0644]
docs_src/python_types/tutorial011.py
docs_src/python_types/tutorial011_py39.py
docs_src/python_types/tutorial012.py [new file with mode: 0644]
docs_src/query_params/tutorial002.py
docs_src/query_params/tutorial003.py
docs_src/query_params/tutorial004.py
docs_src/query_params/tutorial006.py
docs_src/query_params_str_validations/tutorial001.py
docs_src/request_files/tutorial001_02.py
docs_src/response_directly/tutorial001.py
docs_src/response_model/tutorial001.py
docs_src/response_model/tutorial001_py39.py
docs_src/response_model/tutorial002.py
docs_src/response_model/tutorial003.py
docs_src/response_model/tutorial004.py
docs_src/response_model/tutorial004_py39.py
docs_src/response_model/tutorial005.py
docs_src/response_model/tutorial006.py
docs_src/schema_extra_example/tutorial001.py
docs_src/schema_extra_example/tutorial002.py
docs_src/schema_extra_example/tutorial003.py
docs_src/schema_extra_example/tutorial004.py
docs_src/security/tutorial002.py
docs_src/security/tutorial003.py
docs_src/security/tutorial004.py
docs_src/security/tutorial005.py
docs_src/security/tutorial005_py39.py
docs_src/sql_databases/sql_app/schemas.py
docs_src/sql_databases/sql_app_py39/schemas.py
docs_src/sql_databases_peewee/sql_app/schemas.py
docs_src/websockets/tutorial002.py

index 9ad50f271f220e67021defc7a8930717eadbb602..5e9e97a2a2b701f0a82c3aa915583a5945b47aed 100644 (file)
--- a/README.md
+++ b/README.md
@@ -151,7 +151,7 @@ $ pip install "uvicorn[standard]"
 * Create a file `main.py` with:
 
 ```Python
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 
@@ -164,7 +164,7 @@ def read_root():
 
 
 @app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 ```
 
@@ -174,7 +174,7 @@ def read_item(item_id: int, q: Optional[str] = None):
 If your code uses `async` / `await`, use `async def`:
 
 ```Python hl_lines="9  14"
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 
@@ -187,7 +187,7 @@ async def read_root():
 
 
 @app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Optional[str] = None):
+async def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 ```
 
@@ -266,7 +266,7 @@ Now modify the file `main.py` to receive a body from a `PUT` request.
 Declare the body using standard Python types, thanks to Pydantic.
 
 ```Python hl_lines="4  9-12  25-27"
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -277,7 +277,7 @@ app = FastAPI()
 class Item(BaseModel):
     name: str
     price: float
-    is_offer: Optional[bool] = None
+    is_offer: Union[bool, None] = None
 
 
 @app.get("/")
@@ -286,7 +286,7 @@ def read_root():
 
 
 @app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 
 
index ce13bcc4a06c1b6959cec70a4e0b1afde493e325..9297544622de2d829eb14cee54fa27e27eb23283 100644 (file)
@@ -149,7 +149,7 @@ $ pip install uvicorn[standard]
 * Create a file `main.py` with:
 
 ```Python
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 
@@ -162,7 +162,7 @@ def read_root():
 
 
 @app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 ```
 
@@ -172,7 +172,7 @@ def read_item(item_id: int, q: Optional[str] = None):
 If your code uses `async` / `await`, use `async def`:
 
 ```Python hl_lines="9  14"
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 
@@ -185,7 +185,7 @@ async def read_root():
 
 
 @app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Optional[str] = None):
+async def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 ```
 
@@ -264,7 +264,7 @@ Now modify the file `main.py` to receive a body from a `PUT` request.
 Declare the body using standard Python types, thanks to Pydantic.
 
 ```Python hl_lines="4  9-12  25-27"
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -275,7 +275,7 @@ app = FastAPI()
 class Item(BaseModel):
     name: str
     price: float
-    is_offer: Optional[bool] = None
+    is_offer: Union[bool, None] = None
 
 
 @app.get("/")
@@ -284,7 +284,7 @@ def read_root():
 
 
 @app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 
 
index 37ec283ffebbb5ee0e0ca9bed04d9a3e22832cac..b61f88b93d19ff8726fad4486ec9b2e4dcbe4a21 100644 (file)
@@ -14,7 +14,7 @@ But you also want it to accept new items. And when the items didn't exist before
 
 To achieve that, import `JSONResponse`, and return your content there directly, setting the `status_code` that you want:
 
-```Python hl_lines="4  23"
+```Python hl_lines="4  25"
 {!../../../docs_src/additional_status_codes/tutorial001.py!}
 ```
 
index 79208e8dc8625ea6b03e44f4ebd9098e56755c56..7bba82fb7fe50aacaa9f93a896d305d76b746f14 100644 (file)
@@ -28,7 +28,7 @@ To override a dependency for testing, you put as a key the original dependency (
 
 And then **FastAPI** will call that override instead of the original dependency.
 
-```Python hl_lines="26-27  30"
+```Python hl_lines="28-29  32"
 {!../../../docs_src/dependency_testing/tutorial001.py!}
 ```
 
index 651b0e840b087bb626c76157d6bd6dabc2fc372e..8a542622e408a6107a8fd395a704b125ea3b709c 100644 (file)
@@ -142,7 +142,7 @@ Successfully installed fastapi pydantic uvicorn
 * Create a `main.py` file with:
 
 ```Python
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 
@@ -155,7 +155,7 @@ def read_root():
 
 
 @app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 ```
 
index 7de1e50df5627f3e31b87193048548d36bb008ca..17163ba014673e45f36296d53419f4b0f31fe638 100644 (file)
@@ -148,7 +148,7 @@ $ pip install "uvicorn[standard]"
 * Create a file `main.py` with:
 
 ```Python
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 
@@ -161,7 +161,7 @@ def read_root():
 
 
 @app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 ```
 
@@ -171,7 +171,7 @@ def read_item(item_id: int, q: Optional[str] = None):
 If your code uses `async` / `await`, use `async def`:
 
 ```Python hl_lines="9  14"
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 
@@ -184,7 +184,7 @@ async def read_root():
 
 
 @app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Optional[str] = None):
+async def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 ```
 
@@ -263,7 +263,7 @@ Now modify the file `main.py` to receive a body from a `PUT` request.
 Declare the body using standard Python types, thanks to Pydantic.
 
 ```Python hl_lines="4  9-12  25-27"
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -274,7 +274,7 @@ app = FastAPI()
 class Item(BaseModel):
     name: str
     price: float
-    is_offer: Optional[bool] = None
+    is_offer: Union[bool, None] = None
 
 
 @app.get("/")
@@ -283,7 +283,7 @@ def read_root():
 
 
 @app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 
 
index 8486ed849d2815776ff114feb03bb862a0bf1ed3..963fcaf1cd580525a8ac2c276f562dfb040929ed 100644 (file)
@@ -317,6 +317,45 @@ This also means that in Python 3.10, you can use `Something | None`:
     {!> ../../../docs_src/python_types/tutorial009_py310.py!}
     ```
 
+#### Using `Union` or `Optional`
+
+If you are using a Python version below 3.10, here's a tip from my very **subjective** point of view:
+
+* 🚨 Avoid using `Optional[SomeType]`
+* Instead ✨ **use `Union[SomeType, None]`** ✨.
+
+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.
+
+It's just about the words and names. But those words can affect how you and your teammates think about the code.
+
+As an example, let's take this function:
+
+```Python hl_lines="1  4"
+{!../../../docs_src/python_types/tutorial009c.py!}
+```
+
+The parameter `name` is defined as `Optional[str]`, but it is **not optional**, you cannot call the function without the parameter:
+
+```Python
+say_hi()  # Oh, no, this throws an error! 😱
+```
+
+The `name` parameter is **still required** (not *optional*) because it doesn't have a default value. Still, `name` accepts `None` as the value:
+
+```Python
+say_hi(name=None)  # This works, None is valid 🎉
+```
+
+The good news is, once you are on Python 3.10 you won't have to worry about that, as you will be able to simply use `|` to define unions of types:
+
+```Python hl_lines="1  4"
+{!../../../docs_src/python_types/tutorial009c_py310.py!}
+```
+
+And then you won't have to worry about names like `Optional` and `Union`. 😎
+
 #### Generic types
 
 These types that take type parameters in square brackets are called **Generic types** or **Generics**, for example:
@@ -422,6 +461,9 @@ An example from the official Pydantic docs:
 
 You will see a lot more of all this in practice in the [Tutorial - User Guide](tutorial/index.md){.internal-link target=_blank}.
 
+!!! tip
+    Pydantic has a special behavior when you use `Optional` or `Union[Something, None]` without a default value, you can read more about it in the Pydantic docs about <a href="https://pydantic-docs.helpmanual.io/usage/models/#required-optional-fields" class="external-link" target="_blank">Required Optional fields</a>.
+
 ## Type hints in **FastAPI**
 
 **FastAPI** takes advantage of these type hints to do several things.
index 13de4c8eab531ac76d7d6fa384d0a9f09217c418..31dd27fed45a430ec7eaa66806e5cb23c30e2f73 100644 (file)
@@ -89,13 +89,13 @@ But you can instruct **FastAPI** to treat it as another body key using `Body`:
 
 === "Python 3.6 and above"
 
-    ```Python hl_lines="23"
+    ```Python hl_lines="22"
     {!> ../../../docs_src/body_multiple_params/tutorial003.py!}
     ```
 
 === "Python 3.10 and above"
 
-    ```Python hl_lines="21"
+    ```Python hl_lines="20"
     {!> ../../../docs_src/body_multiple_params/tutorial003_py310.py!}
     ```
 
@@ -126,7 +126,7 @@ Of course, you can also declare additional query parameters whenever you need, a
 As, by default, singular values are interpreted as query parameters, you don't have to explicitly add a `Query`, you can just do:
 
 ```Python
-q: Optional[str] = None
+q: Union[str, None] = None
 ```
 
 Or in Python 3.10 and above:
@@ -139,7 +139,7 @@ For example:
 
 === "Python 3.6 and above"
 
-    ```Python hl_lines="28"
+    ```Python hl_lines="27"
     {!> ../../../docs_src/body_multiple_params/tutorial004.py!}
     ```
 
@@ -152,7 +152,6 @@ For example:
 !!! info
     `Body` also has all the same extra validation and metadata parameters as `Query`,`Path` and others you will see later.
 
-
 ## Embed a single body parameter
 
 Let's say you only have a single `item` body parameter from a Pydantic model `Item`.
@@ -162,7 +161,7 @@ By default, **FastAPI** will then expect its body directly.
 But if you want it to expect a JSON with a key `item` and inside of it the model contents, as it does when you declare extra body parameters, you can use the special `Body` parameter `embed`:
 
 ```Python
-item: Item = Body(..., embed=True)
+item: Item = Body(embed=True)
 ```
 
 as in:
index eb21f29a864fa75227aae4c9fb3e66a969dd02dd..5090059360ba75a50832f1dd83dbee7aa33ba13b 100644 (file)
@@ -206,7 +206,7 @@ The function parameters will be recognized as follows:
 !!! note
     FastAPI will know that the value of `q` is not required because of the default value `= None`.
 
-    The `Optional` in `Optional[str]` is not used by FastAPI, but will allow your editor to give you better support and detect errors.
+    The `Union` in `Union[str, None]` is not used by FastAPI, but will allow your editor to give you better support and detect errors.
 
 ## Without Pydantic
 
index 663fff15bf3f5cf849bfc891dae80ab91fa08744..fb41ba1f67e2f1c54238f1f069072c13413938dd 100644 (file)
@@ -109,7 +109,7 @@ Pay attention to the `__init__` method used to create the instance of the class:
 
 === "Python 3.6 and above"
 
-    ```Python hl_lines="8"
+    ```Python hl_lines="9"
     {!> ../../../docs_src/dependencies/tutorial001.py!}
     ```
 
index fe10facfbc36540857c7d834f1b1f25c7e12868d..5078c00968362f50dd7c96a1d5440154f584a9f1 100644 (file)
@@ -33,7 +33,7 @@ It is just a function that can take all the same parameters that a *path operati
 
 === "Python 3.6 and above"
 
-    ```Python hl_lines="8-9"
+    ```Python hl_lines="8-11"
     {!> ../../../docs_src/dependencies/tutorial001.py!}
     ```
 
@@ -81,7 +81,7 @@ The same way you use `Body`, `Query`, etc. with your *path operation function* p
 
 === "Python 3.6 and above"
 
-    ```Python hl_lines="13  18"
+    ```Python hl_lines="15  20"
     {!> ../../../docs_src/dependencies/tutorial001.py!}
     ```
 
index 51531228da54d263abc02eb45f78d3beafa1156a..a5b40c9ad743b057d6e18f3d4e03744ae524f832 100644 (file)
@@ -55,7 +55,7 @@ Then we can use the dependency with:
 
 === "Python 3.6 and above"
 
-    ```Python hl_lines="21"
+    ```Python hl_lines="22"
     {!> ../../../docs_src/dependencies/tutorial005.py!}
     ```
 
index 31bf91a0ea6e6abb716e5f73353f9923ac863bc0..29235c6e2863b47265955a6818e45613809f5a51 100644 (file)
@@ -59,7 +59,7 @@ It doesn't matter for **FastAPI**. It will detect the parameters by their names,
 
 So, you can declare your function as:
 
-```Python hl_lines="8"
+```Python hl_lines="7"
 {!../../../docs_src/path_params_numeric_validations/tutorial002.py!}
 ```
 
@@ -71,7 +71,7 @@ Pass `*`, as the first parameter of the function.
 
 Python won't do anything with that `*`, but it will know that all the following parameters should be called as keyword arguments (key-value pairs), also known as <abbr title="From: K-ey W-ord Arg-uments"><code>kwargs</code></abbr>. Even if they don't have a default value.
 
-```Python hl_lines="8"
+```Python hl_lines="7"
 {!../../../docs_src/path_params_numeric_validations/tutorial003.py!}
 ```
 
index c751a9256be90b3a84950a07a0a68c53f18db11c..e371e86e4abbb19536cdfb6189ec4db14be70c49 100644 (file)
@@ -162,7 +162,7 @@ Your response model could have default values, like:
     {!> ../../../docs_src/response_model/tutorial004_py310.py!}
     ```
 
-* `description: Optional[str] = None` has a default of `None`.
+* `description: Union[str, None] = None` 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: `[]`.
 
index c69df51dc9e0e489c183611608ae66e715167d70..94347018d08ddd61c4c5279e039c9e1476680077 100644 (file)
@@ -68,13 +68,13 @@ Here we pass an `example` of the data expected in `Body()`:
 
 === "Python 3.6 and above"
 
-    ```Python hl_lines="21-26"
+    ```Python hl_lines="20-25"
     {!> ../../../docs_src/schema_extra_example/tutorial003.py!}
     ```
 
 === "Python 3.10 and above"
 
-    ```Python hl_lines="19-24"
+    ```Python hl_lines="18-23"
     {!> ../../../docs_src/schema_extra_example/tutorial003_py310.py!}
     ```
 
@@ -99,13 +99,13 @@ Each specific example `dict` in the `examples` can contain:
 
 === "Python 3.6 and above"
 
-    ```Python hl_lines="22-48"
+    ```Python hl_lines="21-47"
     {!> ../../../docs_src/schema_extra_example/tutorial004.py!}
     ```
 
 === "Python 3.10 and above"
 
-    ```Python hl_lines="20-46"
+    ```Python hl_lines="19-45"
     {!> ../../../docs_src/schema_extra_example/tutorial004_py310.py!}
     ```
 
index 67224fb364a94f39096fbbb57d5c6acc59d44b34..1f28ea85b738a1b8550504c4c477f5e915cc74a4 100644 (file)
@@ -14,7 +14,7 @@ Pero también quieres que acepte nuevos ítems. Cuando los ítems no existan ant
 
 Para conseguir esto importa `JSONResponse` y devuelve ahí directamente tu contenido, asignando el `status_code` que quieras:
 
-```Python hl_lines="2  19"
+```Python hl_lines="4  25"
 {!../../../docs_src/additional_status_codes/tutorial001.py!}
 ```
 
index 1fa79fdde04333df35f64c83fe946d1e400a7c84..ef4850b56518c18f86a0e60537a297b43d789e43 100644 (file)
@@ -145,7 +145,7 @@ $ pip install uvicorn[standard]
 
 ```Python
 from fastapi import FastAPI
-from typing import Optional
+from typing import Union
 
 app = FastAPI()
 
@@ -156,7 +156,7 @@ def read_root():
 
 
 @app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 ```
 
@@ -167,7 +167,7 @@ Si tu código usa `async` / `await`, usa `async def`:
 
 ```Python hl_lines="7  12"
 from fastapi import FastAPI
-from typing import Optional
+from typing import Union
 
 app = FastAPI()
 
@@ -178,7 +178,7 @@ async def read_root():
 
 
 @app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Optional[str] = None):
+async def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 ```
 
@@ -259,7 +259,7 @@ Declara el body usando las declaraciones de tipo estándares de Python gracias a
 ```Python hl_lines="2  7-10  23-25"
 from fastapi import FastAPI
 from pydantic import BaseModel
-from typing import Optional
+from typing import Union
 
 app = FastAPI()
 
@@ -267,7 +267,7 @@ app = FastAPI()
 class Item(BaseModel):
     name: str
     price: float
-    is_offer: Optional[bool] = None
+    is_offer: Union[bool, None] = None
 
 
 @app.get("/")
@@ -276,7 +276,7 @@ def read_root():
 
 
 @app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 
 
index 69caee6e8b10a4fe72237378d6e775f2873fc48a..482af8dc06f74eb0f03b4c82f0f0c5a6eee4a3a4 100644 (file)
@@ -75,7 +75,7 @@ En este caso el parámetro de la función `q` será opcional y será `None` por
 !!! note "Nota"
     FastAPI sabrá que `q` es opcional por el `= None`.
 
-    El `Optional` en `Optional[str]` no es usado por FastAPI (FastAPI solo usará la parte `str`), pero el `Optional[str]` le permitirá a tu editor ayudarte a encontrar errores en tu código.
+    El `Union` en `Union[str, None]` no es usado por FastAPI (FastAPI solo usará la parte `str`), pero el `Union[str, None]` le permitirá a tu editor ayudarte a encontrar errores en tu código.
 
 ## Conversión de tipos de parámetros de query
 
index 0070de17964ef4edf6a997840eb5a025104d0e5f..fd52f994c83a9155862220d7bcab0e4aa4a957c6 100644 (file)
@@ -152,7 +152,7 @@ $ pip install "uvicorn[standard]"
 * Create a file `main.py` with:
 
 ```Python
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 
@@ -165,7 +165,7 @@ def read_root():
 
 
 @app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 ```
 
@@ -175,7 +175,7 @@ def read_item(item_id: int, q: Optional[str] = None):
 If your code uses `async` / `await`, use `async def`:
 
 ```Python hl_lines="9  14"
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 
@@ -188,7 +188,7 @@ async def read_root():
 
 
 @app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Optional[str] = None):
+async def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 ```
 
@@ -267,7 +267,7 @@ Now modify the file `main.py` to receive a body from a `PUT` request.
 Declare the body using standard Python types, thanks to Pydantic.
 
 ```Python hl_lines="4  9-12  25-27"
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -278,7 +278,7 @@ app = FastAPI()
 class Item(BaseModel):
     name: str
     price: float
-    is_offer: Optional[bool] = None
+    is_offer: Union[bool, None] = None
 
 
 @app.get("/")
@@ -287,7 +287,7 @@ def read_root():
 
 
 @app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 
 
index 0b537054e998a9d6631be8ff45ebf5e74732ac21..f713ee96b386f54cc5d4b92555c8928412360e67 100644 (file)
@@ -149,7 +149,7 @@ $ pip install uvicorn[standard]
 * Create a file `main.py` with:
 
 ```Python
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 
@@ -162,7 +162,7 @@ def read_root():
 
 
 @app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 ```
 
@@ -172,7 +172,7 @@ def read_item(item_id: int, q: Optional[str] = None):
 If your code uses `async` / `await`, use `async def`:
 
 ```Python hl_lines="9 14"
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 
@@ -185,7 +185,7 @@ async def read_root():
 
 
 @app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Optional[str] = None):
+async def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 ```
 
@@ -264,7 +264,7 @@ Now modify the file `main.py` to receive a body from a `PUT` request.
 Declare the body using standard Python types, thanks to Pydantic.
 
 ```Python hl_lines="4  9 10 11 12  25 26 27"
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -275,7 +275,7 @@ app = FastAPI()
 class Item(BaseModel):
     name: str
     price: float
-    is_offer: Optional[bool] = None
+    is_offer: Union[bool, None] = None
 
 
 @app.get("/")
@@ -284,7 +284,7 @@ def read_root():
 
 
 @app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 
 
index 6c03cd92b3a5a2d9d7b4c3e475ddec266802ed2d..d1f8e645169f3549e4cb60eb7fade914d8f55a0b 100644 (file)
@@ -14,7 +14,7 @@
 
 これを達成するには、 `JSONResponse` をインポートし、 `status_code` を設定して直接内容を返します。
 
-```Python hl_lines="4  23"
+```Python hl_lines="4  25"
 {!../../../docs_src/additional_status_codes/tutorial001.py!}
 ```
 
index ff0af725fba9ed05f8d3e25727b1ef6a304fe396..8d375d7ce0ec977a7760d75d16ac83686cda37d8 100644 (file)
 {!../../../docs_src/query_params_str_validations/tutorial002.py!}
 ```
 
-デフォルト値`None`を`Query(None)`に置き換える必要があるので、`Query`の最初の引数はデフォルト値を定義するのと同じです。
+デフォルト値`None`を`Query(default=None)`に置き換える必要があるので、`Query`の最初の引数はデフォルト値を定義するのと同じです。
 
 なので:
 
 ```Python
-q: Optional[str] = Query(None)
+q: Optional[str] = Query(default=None)
 ```
 
 ...を以下と同じようにパラメータをオプションにします:
@@ -60,7 +60,7 @@ q: Optional[str] = None
     もしくは:
 
     ```Python
-    = Query(None)
+    = Query(default=None)
     ```
 
     そして、 `None` を利用することでクエリパラメータが必須ではないと検知します。
@@ -70,7 +70,7 @@ q: Optional[str] = None
 そして、さらに多くのパラメータを`Query`に渡すことができます。この場合、文字列に適用される、`max_length`パラメータを指定します。
 
 ```Python
-q: str = Query(None, max_length=50)
+q: Union[str, None] = Query(default=None, max_length=50)
 ```
 
 これにより、データを検証し、データが有効でない場合は明確なエラーを表示し、OpenAPIスキーマの *path operation* にパラメータを記載します。
@@ -79,7 +79,7 @@ q: str = Query(None, max_length=50)
 
 パラメータ`min_length`も追加することができます:
 
-```Python hl_lines="9"
+```Python hl_lines="10"
 {!../../../docs_src/query_params_str_validations/tutorial003.py!}
 ```
 
@@ -87,7 +87,7 @@ q: str = Query(None, max_length=50)
 
 パラメータが一致するべき<abbr title="正規表現とは、文字列の検索パターンを定義する文字列です。">正規表現</abbr>を定義することができます:
 
-```Python hl_lines="10"
+```Python hl_lines="11"
 {!../../../docs_src/query_params_str_validations/tutorial004.py!}
 ```
 
@@ -125,13 +125,13 @@ q: str
 以下の代わりに:
 
 ```Python
-q: Optional[str] = None
+q: Union[str, None] = None
 ```
 
 現在は以下の例のように`Query`で宣言しています:
 
 ```Python
-q: Optional[str] = Query(None, min_length=3)
+q: Union[str, None] = Query(default=None, min_length=3)
 ```
 
 そのため、`Query`を使用して必須の値を宣言する必要がある場合は、第一引数に`...`を使用することができます:
index 284628955bd432dab3903bb2463d293a5fe9e3e6..ec44229947b7c1fc980f1969fdcdfe21d07cb9c8 100644 (file)
@@ -145,7 +145,7 @@ $ pip install uvicorn[standard]
 * `main.py` 파일을 만드십시오:
 
 ```Python
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 
@@ -158,7 +158,7 @@ def read_root():
 
 
 @app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 ```
 
@@ -168,7 +168,7 @@ def read_item(item_id: int, q: Optional[str] = None):
 여러분의 코드가 `async` / `await`을 사용한다면, `async def`를 사용하십시오.
 
 ```Python hl_lines="9 14"
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 
@@ -181,7 +181,7 @@ async def read_root():
 
 
 @app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Optional[str] = None):
+async def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 ```
 
@@ -260,7 +260,7 @@ INFO:     Application startup complete.
 Pydantic을 이용해 파이썬 표준 타입으로 본문을 선언합니다.
 
 ```Python hl_lines="4  9 10 11 12  25 26 27"
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -271,7 +271,7 @@ app = FastAPI()
 class Item(BaseModel):
     name: str
     price: float
-    is_offer: Optional[bool] = None
+    is_offer: Union[bool, None] = None
 
 
 @app.get("/")
@@ -280,7 +280,7 @@ def read_root():
 
 
 @app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 
 
index abb9d03dbb50c26f335ef40aca3b7f584ef1de4f..cadf543fc69fed4ad74dab5eae4f49d433bd1f68 100644 (file)
@@ -43,7 +43,7 @@
 
 따라서 함수를 다음과 같이 선언 할 수 있습니다:
 
-```Python hl_lines="8"
+```Python hl_lines="7"
 {!../../../docs_src/path_params_numeric_validations/tutorial002.py!}
 ```
 
@@ -55,7 +55,7 @@
 
 파이썬은 `*`으로 아무런 행동도 하지 않지만, 따르는 매개변수들은 <abbr title="유래: K-ey W-ord Arg-uments"><code>kwargs</code></abbr>로도 알려진 키워드 인자(키-값 쌍)여야 함을 인지합니다. 기본값을 가지고 있지 않더라도 그렇습니다.
 
-```Python hl_lines="8"
+```Python hl_lines="7"
 {!../../../docs_src/path_params_numeric_validations/tutorial003.py!}
 ```
 
index 05f2ff9c9123b028a786cac343b93b2b09f428df..bb631e6ffc31043fcf743e938fae95aa5c99c713 100644 (file)
@@ -75,7 +75,7 @@ http://127.0.0.1:8000/items/?skip=20
 !!! note "참고"
     FastAPI는 `q`가 `= None`이므로 선택적이라는 것을 인지합니다.
 
-    `Optional[str]`에 있는 `Optional`은 FastAPI(FastAPI는 `str` 부분만 사용합니다)가 사용하는게 아니지만, `Optional[str]`은 편집기에게 코드에서 오류를 찾아낼 수 있게 도와줍니다.
+    `Union[str, None]`에 있는 `Union`은 FastAPI(FastAPI는 `str` 부분만 사용합니다)가 사용하는게 아니지만, `Union[str, None]`은 편집기에게 코드에서 오류를 찾아낼 수 있게 도와줍니다.
 
 ## 쿼리 매개변수 형변환
 
index 0070de17964ef4edf6a997840eb5a025104d0e5f..fd52f994c83a9155862220d7bcab0e4aa4a957c6 100644 (file)
@@ -152,7 +152,7 @@ $ pip install "uvicorn[standard]"
 * Create a file `main.py` with:
 
 ```Python
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 
@@ -165,7 +165,7 @@ def read_root():
 
 
 @app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 ```
 
@@ -175,7 +175,7 @@ def read_item(item_id: int, q: Optional[str] = None):
 If your code uses `async` / `await`, use `async def`:
 
 ```Python hl_lines="9  14"
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 
@@ -188,7 +188,7 @@ async def read_root():
 
 
 @app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Optional[str] = None):
+async def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 ```
 
@@ -267,7 +267,7 @@ Now modify the file `main.py` to receive a body from a `PUT` request.
 Declare the body using standard Python types, thanks to Pydantic.
 
 ```Python hl_lines="4  9-12  25-27"
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -278,7 +278,7 @@ app = FastAPI()
 class Item(BaseModel):
     name: str
     price: float
-    is_offer: Optional[bool] = None
+    is_offer: Union[bool, None] = None
 
 
 @app.get("/")
@@ -287,7 +287,7 @@ def read_root():
 
 
 @app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 
 
index 4a300ae632dbc8f33dd9d6a20e71dde68de970e2..bbe1b1ad15e0db38bd8cc2bcfe67c0b3319bd40c 100644 (file)
@@ -144,7 +144,7 @@ $ pip install uvicorn[standard]
 * Utwórz plik o nazwie `main.py` z:
 
 ```Python
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 
@@ -157,7 +157,7 @@ def read_root():
 
 
 @app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 ```
 
@@ -167,7 +167,7 @@ def read_item(item_id: int, q: Optional[str] = None):
 Jeżeli twój kod korzysta z `async` / `await`, użyj `async def`:
 
 ```Python hl_lines="9  14"
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 
@@ -180,7 +180,7 @@ async def read_root():
 
 
 @app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Optional[str] = None):
+async def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 ```
 
@@ -258,7 +258,7 @@ Zmodyfikuj teraz plik `main.py`, aby otrzmywał treść (body) żądania `PUT`.
 Zadeklaruj treść żądania, używając standardowych typów w Pythonie dzięki Pydantic.
 
 ```Python hl_lines="4  9-12  25-27"
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -269,7 +269,7 @@ app = FastAPI()
 class Item(BaseModel):
     name: str
     price: float
-    is_offer: Optional[bool] = None
+    is_offer: Union[bool, None] = None
 
 
 @app.get("/")
@@ -278,7 +278,7 @@ def read_root():
 
 
 @app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 
 
index c1a0dbf0dbbe0f22c228856e74f7970075e53c14..b1d0c89f2a8132beb00c60b5facfe8ff851c2b82 100644 (file)
@@ -138,7 +138,7 @@ $ pip install uvicorn[standard]
 * Crie um arquivo `main.py` com:
 
 ```Python
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 
@@ -151,7 +151,7 @@ def read_root():
 
 
 @app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 ```
 
@@ -161,7 +161,7 @@ def read_item(item_id: int, q: Optional[str] = None):
 Se seu código utiliza `async` / `await`, use `async def`:
 
 ```Python hl_lines="9  14"
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 
@@ -174,7 +174,7 @@ async def read_root():
 
 
 @app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Optional[str] = None):
+async def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 ```
 
@@ -253,6 +253,8 @@ Agora modifique o arquivo `main.py` para receber um corpo para uma requisição
 Declare o corpo utilizando tipos padrão Python, graças ao Pydantic.
 
 ```Python hl_lines="4  9-12  25-27"
+from typing import Union
+
 from fastapi import FastAPI
 from pydantic import BaseModel
 
@@ -262,7 +264,7 @@ app = FastAPI()
 class Item(BaseModel):
     name: str
     price: float
-    is_offer: Optional[bool] = None
+    is_offer: Union[bool] = None
 
 
 @app.get("/")
@@ -271,7 +273,7 @@ def read_root():
 
 
 @app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 
 
index 5abc9117795faba028f94ba42dde3a874513ca08..99e05ab77e95ff67a7b06d6f188d5d322f660af7 100644 (file)
@@ -158,7 +158,7 @@ Os parâmetros da função serão reconhecidos conforme abaixo:
 !!! note "Observação"
     O FastAPI saberá que o valor de `q` não é obrigatório por causa do valor padrão `= None`.
 
-    O `Optional` em `Optional[str]` não é utilizado pelo FastAPI, mas permite ao seu editor de texto lhe dar um suporte melhor e detectar erros.
+    O `Union` em `Union[str, None]` não é utilizado pelo FastAPI, mas permite ao seu editor de texto lhe dar um suporte melhor e detectar erros.
 
 ## Sem o Pydantic
 
index baac5f493154930f94832d879360f1f297589fc1..9a9e071db9b3ccfc2ef8d31619b2d7d30f3c5938 100644 (file)
@@ -8,12 +8,12 @@ Vamos utilizar essa aplicação como exemplo:
 {!../../../docs_src/query_params_str_validations/tutorial001.py!}
 ```
 
-O parâmetro de consulta `q` é do tipo `Optional[str]`, o que significa que é do tipo `str` mas que também pode ser `None`, e de fato, o valor padrão é `None`, então o FastAPI saberá que não é obrigatório.
+O parâmetro de consulta `q` é do tipo `Union[str, None]`, o que significa que é do tipo `str` mas que também pode ser `None`, e de fato, o valor padrão é `None`, então o FastAPI saberá que não é obrigatório.
 
 !!! note "Observação"
     O FastAPI saberá que o valor de `q` não é obrigatório por causa do valor padrão `= None`.
 
-    O `Optional` em `Optional[str]` não é usado pelo FastAPI, mas permitirá que seu editor lhe dê um melhor suporte e detecte erros.
+    O `Union` em `Union[str, None]` não é usado pelo FastAPI, mas permitirá que seu editor lhe dê um melhor suporte e detecte erros.
 
 ## Validação adicional
 
@@ -35,18 +35,18 @@ Agora utilize-o como valor padrão do seu parâmetro, definindo o parâmetro `ma
 {!../../../docs_src/query_params_str_validations/tutorial002.py!}
 ```
 
-Note que substituímos o valor padrão de `None` para `Query(None)`, o primeiro parâmetro de `Query` serve para o mesmo propósito: definir o valor padrão do parâmetro.
+Note que substituímos o valor padrão de `None` para `Query(default=None)`, o primeiro parâmetro de `Query` serve para o mesmo propósito: definir o valor padrão do parâmetro.
 
 Então:
 
 ```Python
-q: Optional[str] = Query(None)
+q: Union[str, None] = Query(default=None)
 ```
 
 ...Torna o parâmetro opcional, da mesma maneira que:
 
 ```Python
-q: Optional[str] = None
+q: Union[str, None] = None
 ```
 
 Mas o declara explicitamente como um parâmetro de consulta.
@@ -61,17 +61,17 @@ Mas o declara explicitamente como um parâmetro de consulta.
     Ou com:
 
     ```Python
-    = Query(None)
+    = Query(default=None)
     ```
 
     E irá utilizar o `None` para detectar que o parâmetro de consulta não é obrigatório.
 
-    O `Optional` é apenas para permitir que seu editor de texto lhe dê um melhor suporte.
+    O `Union` é apenas para permitir que seu editor de texto lhe dê um melhor suporte.
 
 Então, podemos passar mais parâmetros para `Query`. Neste caso, o parâmetro `max_length` que se aplica a textos:
 
 ```Python
-q: str = Query(None, max_length=50)
+q: str = Query(default=None, max_length=50)
 ```
 
 Isso irá validar os dados, mostrar um erro claro quando os dados forem inválidos, e documentar o parâmetro na *operação de rota* do esquema OpenAPI..
@@ -80,7 +80,7 @@ Isso irá validar os dados, mostrar um erro claro quando os dados forem inválid
 
 Você também pode incluir um parâmetro `min_length`:
 
-```Python hl_lines="9"
+```Python hl_lines="10"
 {!../../../docs_src/query_params_str_validations/tutorial003.py!}
 ```
 
@@ -88,7 +88,7 @@ Você também pode incluir um parâmetro `min_length`:
 
 Você pode definir uma <abbr title="Uma expressão regular, regex ou regexp é uma sequência de caracteres que define um parâmetro de busca para textos.">expressão regular</abbr> que combine com um padrão esperado pelo parâmetro:
 
-```Python hl_lines="10"
+```Python hl_lines="11"
 {!../../../docs_src/query_params_str_validations/tutorial004.py!}
 ```
 
@@ -126,13 +126,13 @@ q: str
 em vez desta:
 
 ```Python
-q: Optional[str] = None
+q: Union[str, None] = None
 ```
 
 Mas agora nós o estamos declarando como `Query`, conforme abaixo:
 
 ```Python
-q: Optional[str] = Query(None, min_length=3)
+q: Union[str, None] = Query(default=None, min_length=3)
 ```
 
 Então, quando você precisa declarar um parâmetro obrigatório utilizando o `Query`, você pode utilizar `...` como o primeiro argumento:
index a1d3022762cfd397fd2d6704d3cf32f9a4be2b94..9a3957d5f6efa8bca044dfd4c78cc0a76557438e 100644 (file)
@@ -149,7 +149,7 @@ $ pip install uvicorn[standard]
 * Create a file `main.py` with:
 
 ```Python
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 
@@ -162,7 +162,7 @@ def read_root():
 
 
 @app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 ```
 
@@ -172,7 +172,7 @@ def read_item(item_id: int, q: Optional[str] = None):
 If your code uses `async` / `await`, use `async def`:
 
 ```Python hl_lines="9  14"
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 
@@ -185,7 +185,7 @@ async def read_root():
 
 
 @app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Optional[str] = None):
+async def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 ```
 
@@ -264,7 +264,7 @@ Now modify the file `main.py` to receive a body from a `PUT` request.
 Declare the body using standard Python types, thanks to Pydantic.
 
 ```Python hl_lines="4  9-12  25-27"
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -275,7 +275,7 @@ app = FastAPI()
 class Item(BaseModel):
     name: str
     price: float
-    is_offer: Optional[bool] = None
+    is_offer: Union[bool, None] = None
 
 
 @app.get("/")
@@ -284,7 +284,7 @@ def read_root():
 
 
 @app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 
 
index 0bb7b55e3b0659d064ee8bcada3f3b918a6d345b..29f92e020a7a8be1b76059b84bc092a82a15c76b 100644 (file)
@@ -149,7 +149,7 @@ $ pip install uvicorn[standard]
 * Create a file `main.py` with:
 
 ```Python
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 
@@ -162,7 +162,7 @@ def read_root():
 
 
 @app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 ```
 
@@ -172,7 +172,7 @@ def read_item(item_id: int, q: Optional[str] = None):
 If your code uses `async` / `await`, use `async def`:
 
 ```Python hl_lines="9  14"
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 
@@ -185,7 +185,7 @@ async def read_root():
 
 
 @app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Optional[str] = None):
+async def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 ```
 
@@ -264,7 +264,7 @@ Now modify the file `main.py` to receive a body from a `PUT` request.
 Declare the body using standard Python types, thanks to Pydantic.
 
 ```Python hl_lines="4  9-12  25-27"
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -275,7 +275,7 @@ app = FastAPI()
 class Item(BaseModel):
     name: str
     price: float
-    is_offer: Optional[bool] = None
+    is_offer: Union[bool, None] = None
 
 
 @app.get("/")
@@ -284,7 +284,7 @@ def read_root():
 
 
 @app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 
 
index 3195cd4409ac4e33f06808ee807f576e963bad64..5693029b528a1583329238bd0210fe3c80047c73 100644 (file)
@@ -157,7 +157,7 @@ $ pip install uvicorn[standard]
 * `main.py` adında bir dosya oluştur :
 
 ```Python
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 
@@ -170,7 +170,7 @@ def read_root():
 
 
 @app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 ```
 
@@ -180,7 +180,7 @@ def read_item(item_id: int, q: Optional[str] = None):
 Eğer kodunda `async` / `await` var ise, `async def` kullan:
 
 ```Python hl_lines="9 14"
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 
@@ -193,7 +193,7 @@ async def read_root():
 
 
 @app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Optional[str] = None):
+async def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 ```
 
@@ -272,7 +272,7 @@ Senin için alternatif olarak (<a href="https://github.com/Rebilly/ReDoc" class=
 Şimdi Pydantic sayesinde, Python'un standart tiplerini kullanarak bir body tanımlayacağız.
 
 ```Python hl_lines="4  9 10 11 12  25 26 27"
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -283,7 +283,7 @@ app = FastAPI()
 class Item(BaseModel):
     name: str
     price: float
-    is_offer: Optional[bool] = None
+    is_offer: Union[bool, None] = None
 
 
 @app.get("/")
@@ -292,7 +292,7 @@ def read_root():
 
 
 @app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 
 
index 0bb7b55e3b0659d064ee8bcada3f3b918a6d345b..29f92e020a7a8be1b76059b84bc092a82a15c76b 100644 (file)
@@ -149,7 +149,7 @@ $ pip install uvicorn[standard]
 * Create a file `main.py` with:
 
 ```Python
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 
@@ -162,7 +162,7 @@ def read_root():
 
 
 @app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 ```
 
@@ -172,7 +172,7 @@ def read_item(item_id: int, q: Optional[str] = None):
 If your code uses `async` / `await`, use `async def`:
 
 ```Python hl_lines="9  14"
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 
@@ -185,7 +185,7 @@ async def read_root():
 
 
 @app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Optional[str] = None):
+async def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 ```
 
@@ -264,7 +264,7 @@ Now modify the file `main.py` to receive a body from a `PUT` request.
 Declare the body using standard Python types, thanks to Pydantic.
 
 ```Python hl_lines="4  9-12  25-27"
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -275,7 +275,7 @@ app = FastAPI()
 class Item(BaseModel):
     name: str
     price: float
-    is_offer: Optional[bool] = None
+    is_offer: Union[bool, None] = None
 
 
 @app.get("/")
@@ -284,7 +284,7 @@ def read_root():
 
 
 @app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 
 
index 40cceebee9e51cb175d8121ddab0c4bfb6fd49f2..54ec9775b6204057d92d48d55547bf797061bee1 100644 (file)
@@ -14,7 +14,7 @@
 
 要实现它,导入 `JSONResponse`,然后在其中直接返回你的内容,并将 `status_code` 设置为为你要的值。
 
-```Python hl_lines="2  19"
+```Python hl_lines="4  25"
 {!../../../docs_src/additional_status_codes/tutorial001.py!}
 ```
 
index 20755283dba67946e8053ead7f57a046b7c8df4c..797032c865f2287a34e9f1b214d8ead5c2a35283 100644 (file)
@@ -145,7 +145,7 @@ $ pip install uvicorn[standard]
 * 创建一个 `main.py` 文件并写入以下内容:
 
 ```Python
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 
@@ -158,7 +158,7 @@ def read_root():
 
 
 @app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 ```
 
@@ -168,7 +168,7 @@ def read_item(item_id: int, q: Optional[str] = None):
 如果你的代码里会出现 `async` / `await`,请使用 `async def`:
 
 ```Python hl_lines="9  14"
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 
@@ -181,7 +181,7 @@ async def read_root():
 
 
 @app.get("/items/{item_id}")
-async def read_item(item_id: int, q: Optional[str] = None):
+async def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 ```
 
@@ -260,7 +260,7 @@ INFO:     Application startup complete.
 我们借助 Pydantic 来使用标准的 Python 类型声明请求体。
 
 ```Python hl_lines="4  9-12  25-27"
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -271,7 +271,7 @@ app = FastAPI()
 class Item(BaseModel):
     name: str
     price: float
-    is_offer: Optional[bool] = None
+    is_offer: Union[bool, None] = None
 
 
 @app.get("/")
@@ -280,7 +280,7 @@ def read_root():
 
 
 @app.get("/items/{item_id}")
-def read_item(item_id: int, q: Optional[str] = None):
+def read_item(item_id: int, q: Union[str, None] = None):
     return {"item_id": item_id, "q": q}
 
 
index 0176902d05dbfd2108c3a68e9456747167611d5b..34fa5b638ff1dccc366143ab37185c1176116b7a 100644 (file)
@@ -72,7 +72,7 @@
 但是你可以使用 `Body` 指示 **FastAPI** 将其作为请求体的另一个键进行处理。
 
 
-```Python hl_lines="21"
+```Python hl_lines="22"
 {!../../../docs_src/body_multiple_params/tutorial003.py!}
 ```
 
@@ -126,7 +126,7 @@ q: str = None
 但是,如果你希望它期望一个拥有 `item` 键并在值中包含模型内容的 JSON,就像在声明额外的请求体参数时所做的那样,则可以使用一个特殊的 `Body` 参数 `embed`:
 
 ```Python
-item: Item = Body(..., embed=True)
+item: Item = Body(embed=True)
 ```
 
 比如:
index 626fa15521b35584e71edda75f2d02e524dc843c..c717da0f636f8ce9af4384a75d091d65715afcfb 100644 (file)
@@ -31,7 +31,7 @@ FastAPI 提供了简单易用,但功能强大的**<abbr title="也称为组件
 
 依赖项就是一个函数,且可以使用与*路径操作函数*相同的参数:
 
-```Python hl_lines="8-9"
+```Python hl_lines="8-11"
 {!../../../docs_src/dependencies/tutorial001.py!}
 ```
 
@@ -63,7 +63,7 @@ FastAPI 提供了简单易用,但功能强大的**<abbr title="也称为组件
 
 与在*路径操作函数*参数中使用 `Body`、`Query` 的方式相同,声明依赖项需要使用 `Depends` 和一个新的参数:
 
-```Python hl_lines="13  18"
+```Python hl_lines="15  20"
 {!../../../docs_src/dependencies/tutorial001.py!}
 ```
 
index 2963189b87926021249b635aeb50526afa360201..58377bbfecd8d4775889a9bc3cd49283f285532f 100644 (file)
@@ -37,7 +37,7 @@ FastAPI 支持创建含**子依赖项**的依赖项。
 
 接下来,就可以使用依赖项:
 
-```Python hl_lines="21"
+```Python hl_lines="22"
 {!../../../docs_src/dependencies/tutorial005.py!}
 ```
 
index 8358cbad579c46bc4dd8a4b9a6d339c74b3dd054..13512a08edf061eb7a37a903f1436b0cc4da1911 100644 (file)
@@ -43,7 +43,7 @@
 
 因此,你可以将函数声明为:
 
-```Python hl_lines="8"
+```Python hl_lines="7"
 {!../../../docs_src/path_params_numeric_validations/tutorial002.py!}
 ```
 
@@ -55,7 +55,7 @@
 
 Python 不会对该 `*` 做任何事情,但是它将知道之后的所有参数都应作为关键字参数(键值对),也被称为 <abbr title="来自:K-ey W-ord Arg-uments"><code>kwargs</code></abbr>,来调用。即使它们没有默认值。
 
-```Python hl_lines="8"
+```Python hl_lines="7"
 {!../../../docs_src/path_params_numeric_validations/tutorial003.py!}
 ```
 
index 1d1d383d4074567a83516f943c5492e2ce7486ef..0b2b9446adcf095020d4136f05f0b65a0a2c7eed 100644 (file)
 {!../../../docs_src/query_params_str_validations/tutorial002.py!}
 ```
 
-由于我们必须用 `Query(None)` 替换默认值 `None`,`Query` 的第一个参数同样也是用于定义默认值。
+由于我们必须用 `Query(default=None)` 替换默认值 `None`,`Query` 的第一个参数同样也是用于定义默认值。
 
 所以:
 
 ```Python
-q: str = Query(None)
+q: Union[str, None] = Query(default=None)
 ```
 
 ...使得参数可选,等同于:
@@ -49,7 +49,7 @@ q: str = None
 然后,我们可以将更多的参数传递给 `Query`。在本例中,适用于字符串的 `max_length` 参数:
 
 ```Python
-q: str = Query(None, max_length=50)
+q: Union[str, None] = Query(default=None, max_length=50)
 ```
 
 将会校验数据,在数据无效时展示清晰的错误信息,并在 OpenAPI 模式的*路径操作*中记录该参​​数。
@@ -58,7 +58,7 @@ q: str = Query(None, max_length=50)
 
 你还可以添加 `min_length` 参数:
 
-```Python hl_lines="9"
+```Python hl_lines="10"
 {!../../../docs_src/query_params_str_validations/tutorial003.py!}
 ```
 
@@ -66,7 +66,7 @@ q: str = Query(None, max_length=50)
 
 你可以定义一个参数值必须匹配的<abbr title="正则表达式或正则是定义字符串搜索模式的字符序列。">正则表达式</abbr>:
 
-```Python hl_lines="10"
+```Python hl_lines="11"
 {!../../../docs_src/query_params_str_validations/tutorial004.py!}
 ```
 
@@ -110,7 +110,7 @@ q: str = None
 但是现在我们正在用 `Query` 声明它,例如:
 
 ```Python
-q: str = Query(None, min_length=3)
+q: Union[str, None] = Query(default=None, min_length=3)
 ```
 
 因此,当你在使用 `Query` 且需要声明一个值是必需的时,可以将 `...` 用作第一个参数值:
index 59a7c17d5ce7f4c39a8da915df63533966ccd756..ea3d0666ded6e36b3151c6df7e65a448fd0b8067 100644 (file)
@@ -94,7 +94,7 @@ FastAPI 将使用此 `response_model` 来:
 {!../../../docs_src/response_model/tutorial004.py!}
 ```
 
-* `description: Optional[str] = None` 具有默认值 `None`。
+* `description: Union[str, None] = None` 具有默认值 `None`。
 * `tax: float = 10.5` 具有默认值 `10.5`.
 * `tags: List[str] = []` 具有一个空列表作为默认值: `[]`.
 
index 6482366b0cad8f8b654a2f0a3754f6a4d7a44df5..8f5fbfe70bbb52d92228538408857c8b8f910f96 100644 (file)
@@ -33,7 +33,7 @@
 
 比如,你可以将请求体的一个 `example` 传递给 `Body`:
 
-```Python hl_lines="21-26"
+```Python hl_lines="20-25"
 {!../../../docs_src/schema_extra_example/tutorial003.py!}
 ```
 
index a46e959596df28ab586a2496ea6161e65f27a826..bd0c9570494363f390f2dba7e4880aa0645308fb 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from fastapi.responses import FileResponse
@@ -23,7 +23,7 @@ app = FastAPI()
         }
     },
 )
-async def read_item(item_id: str, img: Optional[bool] = None):
+async def read_item(item_id: str, img: Union[bool, None] = None):
     if img:
         return FileResponse("image.png", media_type="image/png")
     else:
index 361aecb8e7e847ba69235751abe7f25ec75f0a83..978bc18c13217dc205fd47fdb7fa6134e009ba24 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from fastapi.responses import FileResponse
@@ -25,7 +25,7 @@ app = FastAPI()
     response_model=Item,
     responses={**responses, 200: {"content": {"image/png": {}}}},
 )
-async def read_item(item_id: str, img: Optional[bool] = None):
+async def read_item(item_id: str, img: Union[bool, None] = None):
     if img:
         return FileResponse("image.png", media_type="image/png")
     else:
index e7517e8cde686d5eb8cfd0914675047e82ffd451..2e1b2f6c6cf63b8df9930454f00fa9a4366a3591 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import BackgroundTasks, Depends, FastAPI
 
@@ -10,7 +10,7 @@ def write_log(message: str):
         log.write(message)
 
 
-def get_query(background_tasks: BackgroundTasks, q: Optional[str] = None):
+def get_query(background_tasks: BackgroundTasks, q: Union[str, None] = None):
     if q:
         message = f"found query: {q}\n"
         background_tasks.add_task(write_log, message)
index 52144bd2b0d078f1d9cda36260b53b007ec35bf5..f933172746af3441a8cb86ab6470419c044f6c18 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -6,9 +6,9 @@ from pydantic import BaseModel
 
 class Item(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
-    tax: Optional[float] = None
+    tax: Union[float, None] = None
 
 
 app = FastAPI()
index 644fabae99dc3112312c80dd69306e6b28bbf7c5..7f51839082d9dc39fa3eefeb48fa14a153547cc5 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -6,9 +6,9 @@ from pydantic import BaseModel
 
 class Item(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
-    tax: Optional[float] = None
+    tax: Union[float, None] = None
 
 
 app = FastAPI()
index c99ea694b65ab9bb251bbd5e8cf3d0a002cc56bb..89a6b833ce237e62a3734382fd6eed6c20615cb7 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -6,9 +6,9 @@ from pydantic import BaseModel
 
 class Item(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
-    tax: Optional[float] = None
+    tax: Union[float, None] = None
 
 
 app = FastAPI()
index 7a222a390e7ffcfae7f330e0a870b6e484461f70..e2df0df2baa27f283192588d8fec8e50d10bdeb1 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -6,16 +6,16 @@ from pydantic import BaseModel
 
 class Item(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
-    tax: Optional[float] = None
+    tax: Union[float, None] = None
 
 
 app = FastAPI()
 
 
 @app.put("/items/{item_id}")
-async def create_item(item_id: int, item: Item, q: Optional[str] = None):
+async def create_item(item_id: int, item: Item, q: Union[str, None] = None):
     result = {"item_id": item_id, **item.dict()}
     if q:
         result.update({"q": q})
index 6b874842034102591f78b0298417c7f008f3eedc..2d7160ae8e2bedcc98fd3ff6b865f8ba832c2b6a 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -8,14 +8,14 @@ app = FastAPI()
 
 class Item(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
-    tax: Optional[float] = None
+    tax: Union[float, None] = None
 
 
 class User(BaseModel):
     username: str
-    full_name: Optional[str] = None
+    full_name: Union[str, None] = None
 
 
 @app.put("/items/{item_id}")
index fe14fdf93e615a73c0897c10d4533383edbeddbb..37ef6dda58b7fb829418f0334e219fb979d697bd 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
 
 class Item(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
-    tax: Optional[float] = None
+    tax: Union[float, None] = None
     tags: list = []
 
 
index 1770516a45d2e2a1769fb8a9b324a25c9d46baa2..155cff788548069b70d8684daca5266b0e0fe3be 100644 (file)
@@ -1,4 +1,4 @@
-from typing import List, Optional
+from typing import List, Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
 
 class Item(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
-    tax: Optional[float] = None
+    tax: Union[float, None] = None
     tags: List[str] = []
 
 
index af523a74e4ce21cd0706d8bbf10d0f0cca621df3..8a93a7233ffa336eb31bda202330ef8db3236b37 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
 
 class Item(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
-    tax: Optional[float] = None
+    tax: Union[float, None] = None
     tags: list[str] = []
 
 
index 33dbbe3a9e696056a878889a3719a02240a7c715..84ed18bf48054976e63a0d69170aa66b70a41058 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional, Set
+from typing import Set, Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
 
 class Item(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
-    tax: Optional[float] = None
+    tax: Union[float, None] = None
     tags: Set[str] = set()
 
 
index 931d92f88367339c8e1451c4d82d04e6050f9ccc..b590ece369f93c6a1f3e019e0c231ccbc2f5f1e6 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
 
 class Item(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
-    tax: Optional[float] = None
+    tax: Union[float, None] = None
     tags: set[str] = set()
 
 
index 311a4e73f44fd45659ca4b4606fb0f8314095826..a07bfacac150a7887ce5f79b663790806c3a854d 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional, Set
+from typing import Set, Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -13,11 +13,11 @@ class Image(BaseModel):
 
 class Item(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
-    tax: Optional[float] = None
+    tax: Union[float, None] = None
     tags: Set[str] = set()
-    image: Optional[Image] = None
+    image: Union[Image, None] = None
 
 
 @app.put("/items/{item_id}")
index ab05da02386c7cc64d2360fcfd40193409c4a49d..dc2b175fb224310fe6d93d106b5aa5986737f8d2 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -13,11 +13,11 @@ class Image(BaseModel):
 
 class Item(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
-    tax: Optional[float] = None
+    tax: Union[float, None] = None
     tags: set[str] = set()
-    image: Optional[Image] = None
+    image: Union[Image, None] = None
 
 
 @app.put("/items/{item_id}")
index e76498c3b6f093077378cfb3f960f8fb9c8171d7..5a01264eda859a68f8c5d30e563a5b99cf4096c8 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional, Set
+from typing import Set, Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel, HttpUrl
@@ -13,11 +13,11 @@ class Image(BaseModel):
 
 class Item(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
-    tax: Optional[float] = None
+    tax: Union[float, None] = None
     tags: Set[str] = set()
-    image: Optional[Image] = None
+    image: Union[Image, None] = None
 
 
 @app.put("/items/{item_id}")
index 5045518837776587ea544e8393a565811e29ffb1..47db90008afb7f62fb671bdf80b8f34097157f86 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel, HttpUrl
@@ -13,11 +13,11 @@ class Image(BaseModel):
 
 class Item(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
-    tax: Optional[float] = None
+    tax: Union[float, None] = None
     tags: set[str] = set()
-    image: Optional[Image] = None
+    image: Union[Image, None] = None
 
 
 @app.put("/items/{item_id}")
index da78367153d8d71309f1837683bf465ff9850028..75f1f30e33a9253afd3b96389633c29b25b2dd33 100644 (file)
@@ -1,4 +1,4 @@
-from typing import List, Optional, Set
+from typing import List, Set, Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel, HttpUrl
@@ -13,11 +13,11 @@ class Image(BaseModel):
 
 class Item(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
-    tax: Optional[float] = None
+    tax: Union[float, None] = None
     tags: Set[str] = set()
-    images: Optional[List[Image]] = None
+    images: Union[List[Image], None] = None
 
 
 @app.put("/items/{item_id}")
index 61898178e243cced26ef4dbde79b4c34f729dee7..b14409703a6fb2b7412ab21d2eade58a5e63708f 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel, HttpUrl
@@ -13,11 +13,11 @@ class Image(BaseModel):
 
 class Item(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
-    tax: Optional[float] = None
+    tax: Union[float, None] = None
     tags: set[str] = set()
-    images: Optional[list[Image]] = None
+    images: Union[list[Image], None] = None
 
 
 @app.put("/items/{item_id}")
index dfbbeaab1b2cb11f3b9fae9b0523169ba03042b2..641f09dced1f7b4391cf0e51b541f2105417138f 100644 (file)
@@ -1,4 +1,4 @@
-from typing import List, Optional, Set
+from typing import List, Set, Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel, HttpUrl
@@ -13,16 +13,16 @@ class Image(BaseModel):
 
 class Item(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
-    tax: Optional[float] = None
+    tax: Union[float, None] = None
     tags: Set[str] = set()
-    images: Optional[List[Image]] = None
+    images: Union[List[Image], None] = None
 
 
 class Offer(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
     items: List[Item]
 
index 0c7d32fbbea3648437f8ae83f49bc4e5b53d8648..59cf01e2364aeb742046b5f18659eab659e1abf1 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel, HttpUrl
@@ -13,16 +13,16 @@ class Image(BaseModel):
 
 class Item(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
-    tax: Optional[float] = None
+    tax: Union[float, None] = None
     tags: set[str] = set()
-    images: Optional[list[Image]] = None
+    images: Union[list[Image], None] = None
 
 
 class Offer(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
     items: list[Item]
 
index 9b8f3ccf1b718af04e994e3d0ab7a44af67c9721..4e65d77e262628351a588e1f681e521c57f8648e 100644 (file)
@@ -1,4 +1,4 @@
-from typing import List, Optional
+from typing import List, Union
 
 from fastapi import FastAPI
 from fastapi.encoders import jsonable_encoder
@@ -8,9 +8,9 @@ app = FastAPI()
 
 
 class Item(BaseModel):
-    name: Optional[str] = None
-    description: Optional[str] = None
-    price: Optional[float] = None
+    name: Union[str, None] = None
+    description: Union[str, None] = None
+    price: Union[float, None] = None
     tax: float = 10.5
     tags: List[str] = []
 
index 5d5388b56739ba8e60c9b2fc557642b7c5824fe6..999bcdb82deb0fea14e47500c5e32636f44e866f 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from fastapi.encoders import jsonable_encoder
@@ -8,9 +8,9 @@ app = FastAPI()
 
 
 class Item(BaseModel):
-    name: Optional[str] = None
-    description: Optional[str] = None
-    price: Optional[float] = None
+    name: Union[str, None] = None
+    description: Union[str, None] = None
+    price: Union[float, None] = None
     tax: float = 10.5
     tags: list[str] = []
 
index 46d27e67e74a6ba3c577f7491538d8fe4022e725..c3a0fe79eae1183106741911f6acda47eb076e79 100644 (file)
@@ -1,4 +1,4 @@
-from typing import List, Optional
+from typing import List, Union
 
 from fastapi import FastAPI
 from fastapi.encoders import jsonable_encoder
@@ -8,9 +8,9 @@ app = FastAPI()
 
 
 class Item(BaseModel):
-    name: Optional[str] = None
-    description: Optional[str] = None
-    price: Optional[float] = None
+    name: Union[str, None] = None
+    description: Union[str, None] = None
+    price: Union[float, None] = None
     tax: float = 10.5
     tags: List[str] = []
 
index ab85bd5ae7248a1f1f09df96f03edd69cdcb769b..eb35b35215e8f751ae6725b5e1cf8f92775c9ebe 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from fastapi.encoders import jsonable_encoder
@@ -8,9 +8,9 @@ app = FastAPI()
 
 
 class Item(BaseModel):
-    name: Optional[str] = None
-    description: Optional[str] = None
-    price: Optional[float] = None
+    name: Union[str, None] = None
+    description: Union[str, None] = None
+    price: Union[float, None] = None
     tax: float = 10.5
     tags: list[str] = []
 
index 43015eb27f5fa415987dd7a15b886befdb54609b..2954c391f1ce2ea489aeda4afedea80adc7c6be3 100644 (file)
@@ -1,5 +1,5 @@
 from dataclasses import dataclass
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 
@@ -8,8 +8,8 @@ from fastapi import FastAPI
 class Item:
     name: str
     price: float
-    description: Optional[str] = None
-    tax: Optional[float] = None
+    description: Union[str, None] = None
+    tax: Union[float, None] = None
 
 
 app = FastAPI()
index aaa7b8799c60aee665b5f2eaa195c6ba2257ed10..08a23808046565ecb4e118b92870f896937a2cc4 100644 (file)
@@ -1,5 +1,5 @@
 from dataclasses import dataclass, field
-from typing import List, Optional
+from typing import List, Union
 
 from fastapi import FastAPI
 
@@ -9,8 +9,8 @@ class Item:
     name: str
     price: float
     tags: List[str] = field(default_factory=list)
-    description: Optional[str] = None
-    tax: Optional[float] = None
+    description: Union[str, None] = None
+    tax: Union[float, None] = None
 
 
 app = FastAPI()
index 2c1fccdd71d01c7abf6893eaf52cf4a23a2c6dba..34ce1199e52b70e4e87e76233ed8388548bb5f45 100644 (file)
@@ -1,5 +1,5 @@
 from dataclasses import field  # (1)
-from typing import List, Optional
+from typing import List, Union
 
 from fastapi import FastAPI
 from pydantic.dataclasses import dataclass  # (2)
@@ -8,7 +8,7 @@ from pydantic.dataclasses import dataclass  # (2)
 @dataclass
 class Item:
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
 
 
 @dataclass
index a9da971dc0c50b0c8d116228489bcbfc87fa2b27..b1275103a0075d5ca6c5b06ac683ee9b09ae81e3 100644 (file)
@@ -1,11 +1,13 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import Depends, FastAPI
 
 app = FastAPI()
 
 
-async def common_parameters(q: Optional[str] = None, skip: int = 0, limit: int = 100):
+async def common_parameters(
+    q: Union[str, None] = None, skip: int = 0, limit: int = 100
+):
     return {"q": q, "skip": skip, "limit": limit}
 
 
index 458f6b5bb2e515a54b71bf8287c13243b8b7dcd3..8e863e4fabed7ad48c9a00f65f9a59bca65ebc63 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import Depends, FastAPI
 
@@ -9,7 +9,7 @@ fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"
 
 
 class CommonQueryParams:
-    def __init__(self, q: Optional[str] = None, skip: int = 0, limit: int = 100):
+    def __init__(self, q: Union[str, None] = None, skip: int = 0, limit: int = 100):
         self.q = q
         self.skip = skip
         self.limit = limit
index 3f3e940f8149b717a67ddadb162aab88f7832698..34614e5397fd01107df9f1b3f52fe318a3cfc42e 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import Depends, FastAPI
 
@@ -9,7 +9,7 @@ fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"
 
 
 class CommonQueryParams:
-    def __init__(self, q: Optional[str] = None, skip: int = 0, limit: int = 100):
+    def __init__(self, q: Union[str, None] = None, skip: int = 0, limit: int = 100):
         self.q = q
         self.skip = skip
         self.limit = limit
index daa7b46703cab3673bf5cfff5bd112162404f3b3..d9fe8814886ea57068607452e06e6129fa42fa75 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import Depends, FastAPI
 
@@ -9,7 +9,7 @@ fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"
 
 
 class CommonQueryParams:
-    def __init__(self, q: Optional[str] = None, skip: int = 0, limit: int = 100):
+    def __init__(self, q: Union[str, None] = None, skip: int = 0, limit: int = 100):
         self.q = q
         self.skip = skip
         self.limit = limit
index 24f73c61780325948b4df79a0e0b67d6daf663bc..697332b5ba3b650f927fb4ee452eb4069cbdc7ee 100644 (file)
@@ -1,16 +1,17 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import Cookie, Depends, FastAPI
 
 app = FastAPI()
 
 
-def query_extractor(q: Optional[str] = None):
+def query_extractor(q: Union[str, None] = None):
     return q
 
 
 def query_or_cookie_extractor(
-    q: str = Depends(query_extractor), last_query: Optional[str] = Cookie(default=None)
+    q: str = Depends(query_extractor),
+    last_query: Union[str, None] = Cookie(default=None),
 ):
     if not q:
         return last_query
index 237d3b2310b5787701d1f0edd22d10f34ff25937..a5fe1d9bff84c078f4adebe3c98b35ec1399354a 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import Depends, FastAPI
 from fastapi.testclient import TestClient
@@ -6,7 +6,9 @@ from fastapi.testclient import TestClient
 app = FastAPI()
 
 
-async def common_parameters(q: Optional[str] = None, skip: int = 0, limit: int = 100):
+async def common_parameters(
+    q: Union[str, None] = None, skip: int = 0, limit: int = 100
+):
     return {"q": q, "skip": skip, "limit": limit}
 
 
@@ -23,7 +25,7 @@ async def read_users(commons: dict = Depends(common_parameters)):
 client = TestClient(app)
 
 
-async def override_dependency(q: Optional[str] = None):
+async def override_dependency(q: Union[str, None] = None):
     return {"q": q, "skip": 5, "limit": 10}
 
 
index a918fdd64a987b9109f7b4a26793a3844473a8b3..5f7e7061e49938d96fbf7a07d82bb9171eba9005 100644 (file)
@@ -1,5 +1,5 @@
 from datetime import datetime
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from fastapi.encoders import jsonable_encoder
@@ -11,7 +11,7 @@ fake_db = {}
 class Item(BaseModel):
     title: str
     timestamp: datetime
-    description: Optional[str] = None
+    description: Union[str, None] = None
 
 
 app = FastAPI()
index 9f5e911bfab02f406a14d7e3ca1b962e61760ce8..8ae8472a7069558fcf8e0e5d8bb367bde3b235d5 100644 (file)
@@ -1,5 +1,5 @@
 from datetime import datetime, time, timedelta
-from typing import Optional
+from typing import Union
 from uuid import UUID
 
 from fastapi import Body, FastAPI
@@ -10,10 +10,10 @@ app = FastAPI()
 @app.put("/items/{item_id}")
 async def read_items(
     item_id: UUID,
-    start_datetime: Optional[datetime] = Body(default=None),
-    end_datetime: Optional[datetime] = Body(default=None),
-    repeat_at: Optional[time] = Body(default=None),
-    process_after: Optional[timedelta] = Body(default=None),
+    start_datetime: Union[datetime, None] = Body(default=None),
+    end_datetime: Union[datetime, None] = Body(default=None),
+    repeat_at: Union[time, None] = Body(default=None),
+    process_after: Union[timedelta, None] = Body(default=None),
 ):
     start_process = start_datetime + process_after
     duration = end_datetime - start_process
index e95844f608ee2bfa8e1c2db4ad17bc776d795199..4be56cd2a744b4214ea715fcc31639489d9c6095 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel, EmailStr
@@ -10,20 +10,20 @@ class UserIn(BaseModel):
     username: str
     password: str
     email: EmailStr
-    full_name: Optional[str] = None
+    full_name: Union[str, None] = None
 
 
 class UserOut(BaseModel):
     username: str
     email: EmailStr
-    full_name: Optional[str] = None
+    full_name: Union[str, None] = None
 
 
 class UserInDB(BaseModel):
     username: str
     hashed_password: str
     email: EmailStr
-    full_name: Optional[str] = None
+    full_name: Union[str, None] = None
 
 
 def fake_password_hasher(raw_password: str):
index 5bc6e707fa18a419f312dcf21cd5973f6c50e65c..70fa16441d642ad70ce81e174de3d5344fae63f4 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel, EmailStr
@@ -9,7 +9,7 @@ app = FastAPI()
 class UserBase(BaseModel):
     username: str
     email: EmailStr
-    full_name: Optional[str] = None
+    full_name: Union[str, None] = None
 
 
 class UserIn(UserBase):
index 1df561a12fb30c0be335ca6fded2f03fdec4e96c..74429c8e2d5423fa8978d538346c115ba5256e49 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI, Header
 
@@ -6,5 +6,5 @@ app = FastAPI()
 
 
 @app.get("/items/")
-async def read_items(user_agent: Optional[str] = Header(default=None)):
+async def read_items(user_agent: Union[str, None] = Header(default=None)):
     return {"User-Agent": user_agent}
index 2250727f6d598c496833902ff0168a117add68fe..639ab1735d0685e4c57a87a797c40fafac5c6f8c 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI, Header
 
@@ -7,6 +7,6 @@ app = FastAPI()
 
 @app.get("/items/")
 async def read_items(
-    strange_header: Optional[str] = Header(default=None, convert_underscores=False)
+    strange_header: Union[str, None] = Header(default=None, convert_underscores=False)
 ):
     return {"strange_header": strange_header}
index 1ef131cee3c14ad97082f86371f50256e2c02c5f..a61314aedbbcc168ce266f5bf2e6547d308f3328 100644 (file)
@@ -1,4 +1,4 @@
-from typing import List, Optional
+from typing import List, Union
 
 from fastapi import FastAPI, Header
 
@@ -6,5 +6,5 @@ app = FastAPI()
 
 
 @app.get("/items/")
-async def read_items(x_token: Optional[List[str]] = Header(default=None)):
+async def read_items(x_token: Union[List[str], None] = Header(default=None)):
     return {"X-Token values": x_token}
index 78dda58da49f91475e154cb32fce9acc79600755..34437db161fc34379d74259c092301e8a23611d8 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI, Header
 
@@ -6,5 +6,5 @@ app = FastAPI()
 
 
 @app.get("/items/")
-async def read_items(x_token: Optional[list[str]] = Header(default=None)):
+async def read_items(x_token: Union[list[str], None] = Header(default=None)):
     return {"X-Token values": x_token}
index 39548d862535f57e2683a6a33b214a9d1e795f94..91893e52811d3d0c23c703904c3b4e79ac8a350b 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from couchbase import LOCKMODE_WAIT
 from couchbase.bucket import Bucket
@@ -23,9 +23,9 @@ def get_bucket():
 
 class User(BaseModel):
     username: str
-    email: Optional[str] = None
-    full_name: Optional[str] = None
-    disabled: Optional[bool] = None
+    email: Union[str, None] = None
+    full_name: Union[str, None] = None
+    disabled: Union[bool, None] = None
 
 
 class UserInDB(User):
index 2fb8367515db146d18fdab02773049d14184b032..3f1bac6e29926207178af7e24ad7f72eac5260b8 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import APIRouter, FastAPI
 from pydantic import BaseModel, HttpUrl
@@ -8,7 +8,7 @@ app = FastAPI()
 
 class Invoice(BaseModel):
     id: str
-    title: Optional[str] = None
+    title: Union[str, None] = None
     customer: str
     total: float
 
@@ -33,7 +33,7 @@ def invoice_notification(body: InvoiceEvent):
 
 
 @app.post("/invoices/", callbacks=invoices_callback_router.routes)
-def create_invoice(invoice: Invoice, callback_url: Optional[HttpUrl] = None):
+def create_invoice(invoice: Invoice, callback_url: Union[HttpUrl, None] = None):
     """
     Create an invoice.
 
index da678aed3a179646434463b9747849690730c860..a3aad4ac4009e6a685c3f1d506dbcab0a4ded906 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional, Set
+from typing import Set, Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
 
 class Item(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
-    tax: Optional[float] = None
+    tax: Union[float, None] = None
     tags: Set[str] = set()
 
 
index 1316d9237eb1fd4b9cc8ad38499f9afb0b93ae6e..83fd8377ab7c94b009ba11d6e0284ef243332500 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional, Set
+from typing import Set, Union
 
 from fastapi import FastAPI, status
 from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
 
 class Item(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
-    tax: Optional[float] = None
+    tax: Union[float, None] = None
     tags: Set[str] = set()
 
 
index 5c04d8bac08b41b2df211a458959097ddb6effae..a9dcbf3898b9de1e0b880f593881149411942da9 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI, status
 from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
 
 class Item(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
-    tax: Optional[float] = None
+    tax: Union[float, None] = None
     tags: set[str] = set()
 
 
index 2df537d8647494f3e0b2823c1f755a3f1b133e01..798b0c23115a30c43a60079aeac64aa247c38fe5 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional, Set
+from typing import Set, Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
 
 class Item(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
-    tax: Optional[float] = None
+    tax: Union[float, None] = None
     tags: Set[str] = set()
 
 
index 766d9fb0b7d76d6f2df50bec2da7759e67e1a504..e7ced7de7e6a1eabfba7aac2148e1f588957a7d5 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
 
 class Item(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
-    tax: Optional[float] = None
+    tax: Union[float, None] = None
     tags: set[str] = set()
 
 
index 269a1a253d7d9ba4b0883589828988f5bfd5a5cd..26bf7dabae2026bc2d2595203e7a5308743c72f5 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional, Set
+from typing import Set, Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
 
 class Item(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
-    tax: Optional[float] = None
+    tax: Union[float, None] = None
     tags: Set[str] = set()
 
 
index 446198b5c8f80a803fd72c0ddb727f8c6fcf4c7e..607c5707e6e30ed6000b1c8b0daa34fc9c99a13b 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
 
 class Item(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
-    tax: Optional[float] = None
+    tax: Union[float, None] = None
     tags: set[str] = set()
 
 
index de83be836ba0e400871ff9c0643aafa1a2cbbcda..8f865c58a6ad06440d3e6eb4ee835259d5cea47a 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional, Set
+from typing import Set, Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
 
 class Item(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
-    tax: Optional[float] = None
+    tax: Union[float, None] = None
     tags: Set[str] = set()
 
 
index bf6005b950ecc6d3e17977cdab59bc07e4487df1..fc25680c5a3d62d929d2b0cf442d9d1eb1c7ca07 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
 
 class Item(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
-    tax: Optional[float] = None
+    tax: Union[float, None] = None
     tags: set[str] = set()
 
 
index 0f62c38146413dc6f4a31f5642550dc11cfc208d..2c1be4a34bcc7bf835ad2632ee77026093e839ea 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional, Set
+from typing import Set, Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
 
 class Item(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
-    tax: Optional[float] = None
+    tax: Union[float, None] = None
     tags: Set[str] = set()
 
 
index 5ef3204055ce8423e7984f4d5276d8eeabf75b27..ddf29b733d07cbdbbb9308669f9a7e8e40456548 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
 
 class Item(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
-    tax: Optional[float] = None
+    tax: Union[float, None] = None
     tags: set[str] = set()
 
 
diff --git a/docs_src/python_types/tutorial009c.py b/docs_src/python_types/tutorial009c.py
new file mode 100644 (file)
index 0000000..2f539a3
--- /dev/null
@@ -0,0 +1,5 @@
+from typing import Optional
+
+
+def say_hi(name: Optional[str]):
+    print(f"Hey {name}!")
diff --git a/docs_src/python_types/tutorial009c_py310.py b/docs_src/python_types/tutorial009c_py310.py
new file mode 100644 (file)
index 0000000..96b1220
--- /dev/null
@@ -0,0 +1,2 @@
+def say_hi(name: str | None):
+    print(f"Hey {name}!")
index 047b633b57cbdeccf35ca4efcdc8983f9c89766e..c8634cbff505a4e4b8d81a02b901474301440ad3 100644 (file)
@@ -1,5 +1,5 @@
 from datetime import datetime
-from typing import List, Optional
+from typing import List, Union
 
 from pydantic import BaseModel
 
@@ -7,7 +7,7 @@ from pydantic import BaseModel
 class User(BaseModel):
     id: int
     name = "John Doe"
-    signup_ts: Optional[datetime] = None
+    signup_ts: Union[datetime, None] = None
     friends: List[int] = []
 
 
index af79e2df038588b36ea6cb0ff63a3f899d49c8ea..468496f51932543e909a181a0cbe9c773acdf24c 100644 (file)
@@ -1,5 +1,5 @@
 from datetime import datetime
-from typing import Optional
+from typing import Union
 
 from pydantic import BaseModel
 
@@ -7,7 +7,7 @@ from pydantic import BaseModel
 class User(BaseModel):
     id: int
     name = "John Doe"
-    signup_ts: Optional[datetime] = None
+    signup_ts: Union[datetime, None] = None
     friends: list[int] = []
 
 
diff --git a/docs_src/python_types/tutorial012.py b/docs_src/python_types/tutorial012.py
new file mode 100644 (file)
index 0000000..74fa94c
--- /dev/null
@@ -0,0 +1,8 @@
+from typing import Optional
+
+from pydantic import BaseModel
+
+
+class User(BaseModel):
+    name: str
+    age: Optional[int]
index 32918465e50f3779e77f07a2e16b459c2a9faf5f..8465f45eedf1655514da6a07e01b83f5e6d0e8ab 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 
@@ -6,7 +6,7 @@ app = FastAPI()
 
 
 @app.get("/items/{item_id}")
-async def read_item(item_id: str, q: Optional[str] = None):
+async def read_item(item_id: str, q: Union[str, None] = None):
     if q:
         return {"item_id": item_id, "q": q}
     return {"item_id": item_id}
index c81a9678562a4119dd40c117b2563df817f1175e..3362715b39702c6d043d07f6701c4e18d4d40ff9 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 
@@ -6,7 +6,7 @@ app = FastAPI()
 
 
 @app.get("/items/{item_id}")
-async def read_item(item_id: str, q: Optional[str] = None, short: bool = False):
+async def read_item(item_id: str, q: Union[str, None] = None, short: bool = False):
     item = {"item_id": item_id}
     if q:
         item.update({"q": q})
index 37f97fa2ac93224b5f755b4e72f90081a04f7ea9..049c3ae934d62b9e8ab657e11ecb6ed9009bdbb6 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 
@@ -7,7 +7,7 @@ app = FastAPI()
 
 @app.get("/users/{user_id}/items/{item_id}")
 async def read_user_item(
-    user_id: int, item_id: str, q: Optional[str] = None, short: bool = False
+    user_id: int, item_id: str, q: Union[str, None] = None, short: bool = False
 ):
     item = {"item_id": item_id, "owner_id": user_id}
     if q:
index ffe32834030116f3cde049adfd603a24e0bd57a8..f0dbfe08feaefe57cf1c49ee2aa161c05220058f 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 
@@ -7,7 +7,7 @@ app = FastAPI()
 
 @app.get("/items/{item_id}")
 async def read_user_item(
-    item_id: str, needy: str, skip: int = 0, limit: Optional[int] = None
+    item_id: str, needy: str, skip: int = 0, limit: Union[int, None] = None
 ):
     item = {"item_id": item_id, "needy": needy, "skip": skip, "limit": limit}
     return item
index 5d7bfb0ee5dba76f6394b1a3ac2485803643bb6c..e38326b18cab90e1e3a6fb7ec32e8d9ab587cfe3 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 
@@ -6,7 +6,7 @@ app = FastAPI()
 
 
 @app.get("/items/")
-async def read_items(q: Optional[str] = None):
+async def read_items(q: Union[str, None] = None):
     results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
     if q:
         results.update({"q": q})
index 3f311c4b853f1674391ca0ae48af3fd29342e5b7..ac30be2d303cacf926bddefa5d993646cc6d1e6f 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI, File, UploadFile
 
@@ -6,7 +6,7 @@ app = FastAPI()
 
 
 @app.post("/files/")
-async def create_file(file: Optional[bytes] = File(default=None)):
+async def create_file(file: Union[bytes, None] = File(default=None)):
     if not file:
         return {"message": "No file sent"}
     else:
@@ -14,7 +14,7 @@ async def create_file(file: Optional[bytes] = File(default=None)):
 
 
 @app.post("/uploadfile/")
-async def create_upload_file(file: Optional[UploadFile] = None):
+async def create_upload_file(file: Union[UploadFile, None] = None):
     if not file:
         return {"message": "No upload file sent"}
     else:
index 6acdc0fc8d4785d5a36f7d33c8a38ca957b0bee5..5ab655a8a7e47d3d9e5db88a7957d9953009d76a 100644 (file)
@@ -1,5 +1,5 @@
 from datetime import datetime
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from fastapi.encoders import jsonable_encoder
@@ -10,7 +10,7 @@ from pydantic import BaseModel
 class Item(BaseModel):
     title: str
     timestamp: datetime
-    description: Optional[str] = None
+    description: Union[str, None] = None
 
 
 app = FastAPI()
index 57992ecfc5142473f89bbc94440275b5ff027025..0f6e03e5b2e582a8e2055ab654e4b92e4edc5c47 100644 (file)
@@ -1,4 +1,4 @@
-from typing import List, Optional
+from typing import List, Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
 
 class Item(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
-    tax: Optional[float] = None
+    tax: Union[float, None] = None
     tags: List[str] = []
 
 
index 37b866864d496cfdceed54d93e8e5366e9899a14..cdcca39d2a91d38c55be3190ecc57052576b0152 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
 
 class Item(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
-    tax: Optional[float] = None
+    tax: Union[float, None] = None
     tags: list[str] = []
 
 
index 373317eb932b5f35a86ea8c0943e04f2decb1dfc..c68e8b1385712dd70037ac43b5d42d1fbc92f9aa 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel, EmailStr
@@ -10,7 +10,7 @@ class UserIn(BaseModel):
     username: str
     password: str
     email: EmailStr
-    full_name: Optional[str] = None
+    full_name: Union[str, None] = None
 
 
 # Don't do this in production!
index e14026dd8cd2959bb7c0e49b4adf20e02ccf5da0..37e493dcbeb10849747761de25fa219f3bd52385 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel, EmailStr
@@ -10,13 +10,13 @@ class UserIn(BaseModel):
     username: str
     password: str
     email: EmailStr
-    full_name: Optional[str] = None
+    full_name: Union[str, None] = None
 
 
 class UserOut(BaseModel):
     username: str
     email: EmailStr
-    full_name: Optional[str] = None
+    full_name: Union[str, None] = None
 
 
 @app.post("/user/", response_model=UserOut)
index 1e18f989dc3d57e3a820037e2448fd5c18fb9583..10b48039aedc36fa7a6cb601d1f417d9b3323a50 100644 (file)
@@ -1,4 +1,4 @@
-from typing import List, Optional
+from typing import List, Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -8,7 +8,7 @@ app = FastAPI()
 
 class Item(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
     tax: float = 10.5
     tags: List[str] = []
index 07ccbbf4166f96098c4b9ed4bc1284a8d3e8f157..9463b45ec13a79b29b91b33cf8b9ebbe7a86948a 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -8,7 +8,7 @@ app = FastAPI()
 
 class Item(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
     tax: float = 10.5
     tags: list[str] = []
index 03933d1f71efcdf02c8788b1a32dc76c8599c8a6..30eb9f8e3fb785b0848f8a4383a35b04ec745714 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -8,7 +8,7 @@ app = FastAPI()
 
 class Item(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
     tax: float = 10.5
 
index 629ab8a3aa3f7dfb4daf6c786c089d650be1dcdb..3ffdb512bce7d905f5a1f34222e65ff9e420bb73 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -8,7 +8,7 @@ app = FastAPI()
 
 class Item(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
     tax: float = 10.5
 
index fab4d7a4454097d2746193dede719afc34169660..a5ae281274df2137e58a4cf93ade4fc2e689d4bd 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
 
 class Item(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
-    tax: Optional[float] = None
+    tax: Union[float, None] = None
 
     class Config:
         schema_extra = {
index a2aec46f54fe498c3316ef06a5288dd1a20865bb..6de434f81d1fd057dc304ae728ab5baf73e594d9 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import FastAPI
 from pydantic import BaseModel, Field
@@ -8,9 +8,9 @@ app = FastAPI()
 
 class Item(BaseModel):
     name: str = Field(example="Foo")
-    description: Optional[str] = Field(default=None, example="A very nice Item")
+    description: Union[str, None] = Field(default=None, example="A very nice Item")
     price: float = Field(example=35.4)
-    tax: Optional[float] = Field(default=None, example=3.2)
+    tax: Union[float, None] = Field(default=None, example=3.2)
 
 
 @app.put("/items/{item_id}")
index 43d46b81ba953a2f6328e06fc19fc846ac0db271..ce1736bbaf191935c99f91f08eae7f53b9fabd7a 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import Body, FastAPI
 from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
 
 class Item(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
-    tax: Optional[float] = None
+    tax: Union[float, None] = None
 
 
 @app.put("/items/{item_id}")
index 42d7a04a3c1d3455e150169130d750f221d6949d..b67edf30cd7158f5b59dadd4f429376aa1208e36 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import Body, FastAPI
 from pydantic import BaseModel
@@ -8,9 +8,9 @@ app = FastAPI()
 
 class Item(BaseModel):
     name: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
     price: float
-    tax: Optional[float] = None
+    tax: Union[float, None] = None
 
 
 @app.put("/items/{item_id}")
index 03e0cd5fcee35c644d32a07989735a9161fbd00d..bfd035221c09d48b20d898595f475c2088d4a4b2 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import Depends, FastAPI
 from fastapi.security import OAuth2PasswordBearer
@@ -11,9 +11,9 @@ oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
 
 class User(BaseModel):
     username: str
-    email: Optional[str] = None
-    full_name: Optional[str] = None
-    disabled: Optional[bool] = None
+    email: Union[str, None] = None
+    full_name: Union[str, None] = None
+    disabled: Union[bool, None] = None
 
 
 def fake_decode_token(token):
index a6bb176e4f3dc07b34c190808c3a178ccfc0e52e..4b324866f6850d76b2862b05e5bf2e7e44b662c1 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import Depends, FastAPI, HTTPException, status
 from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
@@ -33,9 +33,9 @@ oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
 
 class User(BaseModel):
     username: str
-    email: Optional[str] = None
-    full_name: Optional[str] = None
-    disabled: Optional[bool] = None
+    email: Union[str, None] = None
+    full_name: Union[str, None] = None
+    disabled: Union[bool, None] = None
 
 
 class UserInDB(User):
index 18e2c428fb480c36b60fcf92048b1dc035b92ac2..64099abe9cffeb0bb08af20aab40d237ed5c03c1 100644 (file)
@@ -1,5 +1,5 @@
 from datetime import datetime, timedelta
-from typing import Optional
+from typing import Union
 
 from fastapi import Depends, FastAPI, HTTPException, status
 from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
@@ -31,14 +31,14 @@ class Token(BaseModel):
 
 
 class TokenData(BaseModel):
-    username: Optional[str] = None
+    username: Union[str, None] = None
 
 
 class User(BaseModel):
     username: str
-    email: Optional[str] = None
-    full_name: Optional[str] = None
-    disabled: Optional[bool] = None
+    email: Union[str, None] = None
+    full_name: Union[str, None] = None
+    disabled: Union[bool, None] = None
 
 
 class UserInDB(User):
@@ -75,7 +75,7 @@ def authenticate_user(fake_db, username: str, password: str):
     return user
 
 
-def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
+def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None):
     to_encode = data.copy()
     if expires_delta:
         expire = datetime.utcnow() + expires_delta
index 5b34a09f11701cd26be0d444443b897958598623..ab3af9a6a9dd176799d480b9ff89f9eb24bcbf22 100644 (file)
@@ -1,5 +1,5 @@
 from datetime import datetime, timedelta
-from typing import List, Optional
+from typing import List, Union
 
 from fastapi import Depends, FastAPI, HTTPException, Security, status
 from fastapi.security import (
@@ -42,15 +42,15 @@ class Token(BaseModel):
 
 
 class TokenData(BaseModel):
-    username: Optional[str] = None
+    username: Union[str, None] = None
     scopes: List[str] = []
 
 
 class User(BaseModel):
     username: str
-    email: Optional[str] = None
-    full_name: Optional[str] = None
-    disabled: Optional[bool] = None
+    email: Union[str, None] = None
+    full_name: Union[str, None] = None
+    disabled: Union[bool, None] = None
 
 
 class UserInDB(User):
@@ -90,7 +90,7 @@ def authenticate_user(fake_db, username: str, password: str):
     return user
 
 
-def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
+def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None):
     to_encode = data.copy()
     if expires_delta:
         expire = datetime.utcnow() + expires_delta
index d45c08ce6f87cd21834d4299b631f14d0f014a48..38391308af08c3e77c830000ab8aec23d18b9473 100644 (file)
@@ -1,5 +1,5 @@
 from datetime import datetime, timedelta
-from typing import Optional
+from typing import Union
 
 from fastapi import Depends, FastAPI, HTTPException, Security, status
 from fastapi.security import (
@@ -42,15 +42,15 @@ class Token(BaseModel):
 
 
 class TokenData(BaseModel):
-    username: Optional[str] = None
+    username: Union[str, None] = None
     scopes: list[str] = []
 
 
 class User(BaseModel):
     username: str
-    email: Optional[str] = None
-    full_name: Optional[str] = None
-    disabled: Optional[bool] = None
+    email: Union[str, None] = None
+    full_name: Union[str, None] = None
+    disabled: Union[bool, None] = None
 
 
 class UserInDB(User):
@@ -90,7 +90,7 @@ def authenticate_user(fake_db, username: str, password: str):
     return user
 
 
-def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
+def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None):
     to_encode = data.copy()
     if expires_delta:
         expire = datetime.utcnow() + expires_delta
index 51655663a0bfa6d91307a84df0c491ab9e958a5d..c49beba8827076b81b25ee3953fb99fbd7a6c022 100644 (file)
@@ -1,11 +1,11 @@
-from typing import List, Optional
+from typing import List, Union
 
 from pydantic import BaseModel
 
 
 class ItemBase(BaseModel):
     title: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
 
 
 class ItemCreate(ItemBase):
index a19f1cdfec7ffabfd3598bfbdd534e4306a08b0e..dadc403d93f8b96cea304a41c3c66eedd5d290bc 100644 (file)
@@ -1,11 +1,11 @@
-from typing import Optional
+from typing import Union
 
 from pydantic import BaseModel
 
 
 class ItemBase(BaseModel):
     title: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
 
 
 class ItemCreate(ItemBase):
index b715604eec698118678328641ce1fd90fcbdba67..d8775cb30c0c9e01ee43fc763f845b997b63f23f 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Any, List, Optional
+from typing import Any, List, Union
 
 import peewee
 from pydantic import BaseModel
@@ -15,7 +15,7 @@ class PeeweeGetterDict(GetterDict):
 
 class ItemBase(BaseModel):
     title: str
-    description: Optional[str] = None
+    description: Union[str, None] = None
 
 
 class ItemCreate(ItemBase):
index b010085303b2ba44ccf582667ac792eeb962fe3b..cf5c7e805af864b98cad5a06a29cbb88edb688ee 100644 (file)
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Union
 
 from fastapi import Cookie, Depends, FastAPI, Query, WebSocket, status
 from fastapi.responses import HTMLResponse
@@ -57,8 +57,8 @@ async def get():
 
 async def get_cookie_or_token(
     websocket: WebSocket,
-    session: Optional[str] = Cookie(default=None),
-    token: Optional[str] = Query(default=None),
+    session: Union[str, None] = Cookie(default=None),
+    token: Union[str, None] = Query(default=None),
 ):
     if session is None and token is None:
         await websocket.close(code=status.WS_1008_POLICY_VIOLATION)
@@ -69,7 +69,7 @@ async def get_cookie_or_token(
 async def websocket_endpoint(
     websocket: WebSocket,
     item_id: str,
-    q: Optional[int] = None,
+    q: Union[int, None] = None,
     cookie_or_token: str = Depends(get_cookie_or_token),
 ):
     await websocket.accept()