mirror of https://github.com/tiangolo/fastapi.git
📝 Add docs recommending `Union` over `Optional` and migrate source examples (#4908)
* 📝 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
This commit is contained in:
parent
c5be1b0550
commit
ca437cdfab
14
README.md
14
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}
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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!}
|
||||
```
|
||||
|
||||
|
|
|
|||
|
|
@ -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!}
|
||||
```
|
||||
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
```
|
||||
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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:
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
||||
|
|
|
|||
|
|
@ -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!}
|
||||
```
|
||||
|
||||
|
|
|
|||
|
|
@ -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!}
|
||||
```
|
||||
|
||||
|
|
|
|||
|
|
@ -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!}
|
||||
```
|
||||
|
||||
|
|
|
|||
|
|
@ -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!}
|
||||
```
|
||||
|
||||
|
|
|
|||
|
|
@ -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: `[]`.
|
||||
|
||||
|
|
|
|||
|
|
@ -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!}
|
||||
```
|
||||
|
||||
|
|
|
|||
|
|
@ -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!}
|
||||
```
|
||||
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@
|
|||
|
||||
これを達成するには、 `JSONResponse` をインポートし、 `status_code` を設定して直接内容を返します。
|
||||
|
||||
```Python hl_lines="4 23"
|
||||
```Python hl_lines="4 25"
|
||||
{!../../../docs_src/additional_status_codes/tutorial001.py!}
|
||||
```
|
||||
|
||||
|
|
|
|||
|
|
@ -34,12 +34,12 @@
|
|||
{!../../../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`を使用して必須の値を宣言する必要がある場合は、第一引数に`...`を使用することができます:
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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!}
|
||||
```
|
||||
|
||||
|
|
|
|||
|
|
@ -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]`은 편집기에게 코드에서 오류를 찾아낼 수 있게 도와줍니다.
|
||||
|
||||
## 쿼리 매개변수 형변환
|
||||
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
||||
|
|
|
|||
|
|
@ -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:
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@
|
|||
|
||||
要实现它,导入 `JSONResponse`,然后在其中直接返回你的内容,并将 `status_code` 设置为为你要的值。
|
||||
|
||||
```Python hl_lines="2 19"
|
||||
```Python hl_lines="4 25"
|
||||
{!../../../docs_src/additional_status_codes/tutorial001.py!}
|
||||
```
|
||||
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
```
|
||||
|
||||
比如:
|
||||
|
|
|
|||
|
|
@ -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!}
|
||||
```
|
||||
|
||||
|
|
|
|||
|
|
@ -37,7 +37,7 @@ FastAPI 支持创建含**子依赖项**的依赖项。
|
|||
|
||||
接下来,就可以使用依赖项:
|
||||
|
||||
```Python hl_lines="21"
|
||||
```Python hl_lines="22"
|
||||
{!../../../docs_src/dependencies/tutorial005.py!}
|
||||
```
|
||||
|
||||
|
|
|
|||
|
|
@ -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!}
|
||||
```
|
||||
|
||||
|
|
|
|||
|
|
@ -30,12 +30,12 @@
|
|||
{!../../../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` 且需要声明一个值是必需的时,可以将 `...` 用作第一个参数值:
|
||||
|
|
|
|||
|
|
@ -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] = []` 具有一个空列表作为默认值: `[]`.
|
||||
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@
|
|||
|
||||
比如,你可以将请求体的一个 `example` 传递给 `Body`:
|
||||
|
||||
```Python hl_lines="21-26"
|
||||
```Python hl_lines="20-25"
|
||||
{!../../../docs_src/schema_extra_example/tutorial003.py!}
|
||||
```
|
||||
|
||||
|
|
|
|||
|
|
@ -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:
|
||||
|
|
|
|||
|
|
@ -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:
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
|
|
|||
|
|
@ -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})
|
||||
|
|
|
|||
|
|
@ -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}")
|
||||
|
|
|
|||
|
|
@ -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 = []
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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] = []
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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] = []
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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}")
|
||||
|
|
|
|||
|
|
@ -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}")
|
||||
|
|
|
|||
|
|
@ -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}")
|
||||
|
|
|
|||
|
|
@ -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}")
|
||||
|
|
|
|||
|
|
@ -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}")
|
||||
|
|
|
|||
|
|
@ -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}")
|
||||
|
|
|
|||
|
|
@ -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]
|
||||
|
||||
|
|
|
|||
|
|
@ -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]
|
||||
|
||||
|
|
|
|||
|
|
@ -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] = []
|
||||
|
||||
|
|
|
|||
|
|
@ -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] = []
|
||||
|
||||
|
|
|
|||
|
|
@ -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] = []
|
||||
|
||||
|
|
|
|||
|
|
@ -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] = []
|
||||
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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):
|
||||
|
|
|
|||
|
|
@ -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):
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
|
|
|
|||
|
|
@ -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}
|
||||
|
|
|
|||
|
|
@ -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):
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,5 @@
|
|||
from typing import Optional
|
||||
|
||||
|
||||
def say_hi(name: Optional[str]):
|
||||
print(f"Hey {name}!")
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
def say_hi(name: str | None):
|
||||
print(f"Hey {name}!")
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue