Skip to content

Re-add complex types #143

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# See https://pre-commit.com for more information
# See https://pre-commit.com/hooks.html for more hooks
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v3.2.0
hooks:
- id: trailing-whitespace
# - id: end-of-file-fixer
- id: check-yaml
- id: check-added-large-files

- repo: https://github.com/asottile/pyupgrade
rev: v3.3.0
hooks:
- id: pyupgrade
args: [--py38-plus]

- repo: https://github.com/pycqa/flake8
rev: "6.0.0"
hooks:
- id: flake8
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,11 @@ Google Cloud SQL database connections from within Google Cloud Run are supported
Alternatively you can set all your databases at once, by using the `DATABASES` setting (either in a `PydanticSettings` sub-class or via the `DJANGO_DATABASES` environment variable:

```python
from pydantic_settings import PydanticSettings, types


def MySettings(PydanticSettings):
DATABASES = {"default": "sqlite:///db.sqlite3"} # type: ignore
DATABASES: types.DATABASES = {"default": "sqlite:///db.sqlite3"} # type: ignore
```

It is also possible to configure additional database connections with environment variables in the same way as the default `DATABASE_URL` configuration by using a `Field` that has a `configure_database` argument that points to the database alias in the `DATABASES` dictionary.
Expand Down
8 changes: 4 additions & 4 deletions pydantic_settings/cache.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import re
from typing import Dict
from typing import Any, Dict
from urllib.parse import parse_qs

from django import VERSION
Expand Down Expand Up @@ -71,17 +71,17 @@ def is_redis_scheme(self) -> bool:
def parse(dsn: CacheDsn) -> dict:
"""Parses a cache URL."""
backend = CACHE_ENGINES[dsn.scheme]
config = {"BACKEND": backend}
config: dict[str, Any] = {"BACKEND": backend}

options = {}
options: dict[str, Any] = {}
if dsn.scheme in REDIS_PARSERS:
options["PARSER_CLASS"] = REDIS_PARSERS[dsn.scheme]

cache_args = dsn.query_args.copy()

# File based
if dsn.host is None:
path = dsn.path
path = dsn.path or ""

if dsn.scheme in FILE_UNIX_PREFIX:
path = "unix:" + path
Expand Down
22 changes: 12 additions & 10 deletions pydantic_settings/database.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import re
import urllib.parse
from typing import Dict, Optional, Pattern, Tuple, cast
from typing import TYPE_CHECKING, Pattern, Tuple, Union, cast
from urllib.parse import quote_plus

from pydantic import AnyUrl
from pydantic.validators import constr_length_validator, str_validator

from pydantic_settings.models import DatabaseModel

if TYPE_CHECKING:
from pydantic.networks import Parts

_cloud_sql_regex_cache = None


Expand All @@ -26,11 +29,12 @@
}


def cloud_sql_regex() -> Pattern[str]:
def cloud_sql_regex() -> Pattern:
global _cloud_sql_regex_cache
if _cloud_sql_regex_cache is None:
_cloud_sql_regex_cache = re.compile(
r"(?:(?P<scheme>[a-z][a-z0-9+\-.]+)://)?" # scheme https://tools.ietf.org/html/rfc3986#appendix-A
# scheme https://tools.ietf.org/html/rfc3986#appendix-A
r"(?:(?P<scheme>[a-z][a-z0-9+\-.]+)://)?"
r"(?:(?P<user>[^\s:/]*)(?::(?P<password>[^\s/]*))?@)?" # user info
r"(?P<path>/[^\s?#]*)?", # path
re.IGNORECASE,
Expand Down Expand Up @@ -64,19 +68,17 @@ def validate(cls, value, field, config):
return super().validate(value, field, config)

@classmethod
def validate_host(
cls, parts: Dict[str, str]
) -> Tuple[Optional[str], Optional[str], str, bool]:
host = None
def validate_host(cls, parts: "Parts") -> Tuple[str, Union[str, None], str, bool]:
host: str | None = None
for f in ("domain", "ipv4", "ipv6"):
host = parts[f]
host = cast(Union[str, None], parts.get(f))
if host:
break

if host is None:
return None, None, "file", False
return None, None, "file", False # type: ignore

if host.startswith("%2F"):
if host and host.startswith("%2F"):
return host, None, "socket", False

return super().validate_host(parts)
Expand Down
9 changes: 6 additions & 3 deletions pydantic_settings/default.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from pydantic import root_validator

from pydantic_settings.models import DatabaseModel, TemplateBackendModel
from pydantic_settings.settings import DatabaseModel, PydanticSettings
from pydantic_settings.settings import PydanticSettings


class DjangoDefaultProjectSettings(PydanticSettings):
Expand All @@ -12,7 +12,9 @@ class DjangoDefaultProjectSettings(PydanticSettings):
generates for new projects.
"""

DATABASES: Dict[str, DatabaseModel] = {"default": "sqlite:///db.sqlite3"} # type: ignore
DATABASES: Dict[str, DatabaseModel] = {
"default": "sqlite:///db.sqlite3", # type: ignore
}

TEMPLATES: List[TemplateBackendModel] = [
TemplateBackendModel.parse_obj(data)
Expand Down Expand Up @@ -54,7 +56,8 @@ class DjangoDefaultProjectSettings(PydanticSettings):

AUTH_PASSWORD_VALIDATORS: List[dict] = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
"NAME": "django.contrib.auth.password_validation"
".UserAttributeSimilarityValidator",
},
{
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
Expand Down
2 changes: 1 addition & 1 deletion pydantic_settings/sentry.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

import sentry_sdk
from pydantic import AnyUrl
from pydantic.config import BaseConfig
from pydantic.fields import ModelField
from pydantic.main import BaseConfig
from sentry_sdk.integrations.django import DjangoIntegration

from .settings import PydanticSettings
Expand Down
Loading