Browse Source

📝 Update docs in examples for settings with Pydantic v2 (#9799)

pull/9800/head
Sebastián Ramírez 2 years ago
committed by GitHub
parent
commit
3fa58f5edb
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 26
      docs/en/docs/advanced/settings.md
  2. 5
      docs_src/settings/app03_an/config.py
  3. 10
      docs_src/settings/app03_an/config_pv1.py

26
docs/en/docs/advanced/settings.md

@ -344,14 +344,28 @@ APP_NAME="ChimichangApp"
And then update your `config.py` with:
```Python hl_lines="9-10"
{!../../../docs_src/settings/app03/config.py!}
```
=== "Pydantic v2"
Here we create a class `Config` inside of your Pydantic `Settings` class, and set the `env_file` to the filename with the dotenv file we want to use.
```Python hl_lines="9"
{!> ../../../docs_src/settings/app03_an/config.py!}
```
!!! tip
The `Config` class is used just for Pydantic configuration. You can read more at <a href="https://pydantic-docs.helpmanual.io/usage/model_config/" class="external-link" target="_blank">Pydantic Model Config</a>
!!! tip
The `model_config` attribute is used just for Pydantic configuration. You can read more at <a href="https://docs.pydantic.dev/latest/usage/model_config/" class="external-link" target="_blank">Pydantic Model Config</a>.
=== "Pydantic v1"
```Python hl_lines="9-10"
{!> ../../../docs_src/settings/app03_an/config_pv1.py!}
```
!!! tip
The `Config` class is used just for Pydantic configuration. You can read more at <a href="https://docs.pydantic.dev/1.10/usage/model_config/" class="external-link" target="_blank">Pydantic Model Config</a>.
!!! info
In Pydantic version 1 the configuration was done in an internal class `Config`, in Pydantic version 2 it's done in an attribute `model_config`. This attribute takes a `dict`, and to get autocompletion and inline errors you can import and use `SettingsConfigDict` to define that `dict`.
Here we define the config `env_file` inside of your Pydantic `Settings` class, and set the value to the filename with the dotenv file we want to use.
### Creating the `Settings` only once with `lru_cache`

5
docs_src/settings/app03_an/config.py

@ -1,4 +1,4 @@
from pydantic_settings import BaseSettings
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
@ -6,5 +6,4 @@ class Settings(BaseSettings):
admin_email: str
items_per_user: int = 50
class Config:
env_file = ".env"
model_config = SettingsConfigDict(env_file=".env")

10
docs_src/settings/app03_an/config_pv1.py

@ -0,0 +1,10 @@
from pydantic import BaseSettings
class Settings(BaseSettings):
app_name: str = "Awesome API"
admin_email: str
items_per_user: int = 50
class Config:
env_file = ".env"
Loading…
Cancel
Save