Skip to content

Configuration and Settings

CalendarApi comes with a lightweight toml config loader and parser for advanced usage.

The HTTP options (HTTPClientConfig) can also be passed to CalendarApi / AsyncCalendarApi as keyword arguments (HTTPClientOptions), see the Configuration section.

ConfigSection dataclass

ConfigSection()

Methods:

  • from_config_file –

    Charge la configuration depuis un fichier toml respectant la structure attendue.

from_config_file classmethod

from_config_file(fpath: str | Path, *, with_section: bool = True) -> ConfigSection

Charge la configuration depuis un fichier toml respectant la structure attendue.

Parameters:

  • fpath

    (str) –

    Chemin du fichier de configuration .toml

Returns:

  • DatashopConfig ( ConfigSection ) –

    Instance configurée selon le fichier renseigné.

Raises:

  • ConfigurationError –

    Si strict=True et que le fichier de configuration n'existe pas!

Source code in pycalendar_api/config/base.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
@classmethod
def from_config_file(cls, fpath: str|Path, *, with_section: bool=True) -> "ConfigSection":
    """Charge la configuration depuis un fichier toml respectant la structure attendue.

    Args:
        fpath (str): Chemin du fichier de configuration `.toml`

    Returns:
        DatashopConfig: Instance configurée selon le fichier renseigné.

    Raises:
        ConfigurationError: Si `strict=True` et que le fichier de configuration n'existe pas!
    """
    fpath = Path(fpath)
    if not fpath.exists():
        raise ConfigurationError(f"Le chemin du fichier de configuration n'existe pas. {fpath=}")

    dico = {}
    try:
        with open(fpath) as fd:
            dico = tomllib.loads(fd.read())

        dico = toml_doc_to_dict(dico)
    except PermissionError:
        msg = f"Accès refusé au chemin {fpath=}"
        raise ConfigurationError(msg)

    if cls.section == 'root':
        return cls(**dico)

    if with_section:
        kwargs = dico.get(cls.section, {})
        if cls.key is None:
            return cls(**kwargs)
        else:
            return cls(**kwargs.get(cls.key, {}))
    else:
        # Flat file without nesting
        if cls.key:
            return cls(**dico.get(cls.key, {}))

ApiConfig dataclass

ApiConfig(section: ClassVar = 'api', host: str = 'https://calendar-api.ma', api_endpoint: str = '/api/v1', api_key: str = 'UNDEFINED')

API server config section

Methods:

  • from_config_file –

    Charge la configuration depuis un fichier toml respectant la structure attendue.

from_config_file classmethod

from_config_file(fpath: str | Path, *, with_section: bool = True) -> ConfigSection

Charge la configuration depuis un fichier toml respectant la structure attendue.

Parameters:

  • fpath

    (str) –

    Chemin du fichier de configuration .toml

Returns:

  • DatashopConfig ( ConfigSection ) –

    Instance configurée selon le fichier renseigné.

Raises:

  • ConfigurationError –

    Si strict=True et que le fichier de configuration n'existe pas!

Source code in pycalendar_api/config/base.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
@classmethod
def from_config_file(cls, fpath: str|Path, *, with_section: bool=True) -> "ConfigSection":
    """Charge la configuration depuis un fichier toml respectant la structure attendue.

    Args:
        fpath (str): Chemin du fichier de configuration `.toml`

    Returns:
        DatashopConfig: Instance configurée selon le fichier renseigné.

    Raises:
        ConfigurationError: Si `strict=True` et que le fichier de configuration n'existe pas!
    """
    fpath = Path(fpath)
    if not fpath.exists():
        raise ConfigurationError(f"Le chemin du fichier de configuration n'existe pas. {fpath=}")

    dico = {}
    try:
        with open(fpath) as fd:
            dico = tomllib.loads(fd.read())

        dico = toml_doc_to_dict(dico)
    except PermissionError:
        msg = f"Accès refusé au chemin {fpath=}"
        raise ConfigurationError(msg)

    if cls.section == 'root':
        return cls(**dico)

    if with_section:
        kwargs = dico.get(cls.section, {})
        if cls.key is None:
            return cls(**kwargs)
        else:
            return cls(**kwargs.get(cls.key, {}))
    else:
        # Flat file without nesting
        if cls.key:
            return cls(**dico.get(cls.key, {}))

HTTPClientConfig dataclass

HTTPClientConfig(section: ClassVar = 'http_client', default_encoding: str = 'utf-8', timeout: float = 10, read_timeout: float | None = None, retries: int = 3, verify: bool | str = True, cert: str | None = None, cert_key: str | None = None, proxy: str | None = None, trust_env: bool = True, follow_redirects: bool = True)

HTTP client config section ([http_client] in the toml file). Every field is an option of get_http_client

Attributes:

  • default_encoding (str) –

    Encoding of the responses without charset

  • timeout (float) –

    Connect/write/pool timeout in seconds

  • read_timeout (float | None) –

    Read timeout in seconds. Default: timeout * 5

  • retries (int) –

    Retries on connection errors

  • verify (bool | str) –

    Verify the server certificate (true/false), or path to a CA bundle file or directory

  • cert (str | None) –

    Client certificate file (PEM), for mutual TLS

  • cert_key (str | None) –

    Private key file of cert, when not included in it

  • proxy (str | None) –

    Proxy URL, ie: http://user:pass@proxy:3128

  • trust_env (bool) –

    When proxy is not set, use HTTPS_PROXY / HTTP_PROXY / ALL_PROXY / NO_PROXY. When verify=true, use SSL_CERT_FILE / SSL_CERT_DIR

  • follow_redirects (bool) –

    Follow the HTTP redirects

Methods:

  • from_config_file –

    Charge la configuration depuis un fichier toml respectant la structure attendue.

  • override –

    Copy of this section with some options replaced

from_config_file classmethod

from_config_file(fpath: str | Path, *, with_section: bool = True) -> ConfigSection

Charge la configuration depuis un fichier toml respectant la structure attendue.

Parameters:

  • fpath

    (str) –

    Chemin du fichier de configuration .toml

Returns:

  • DatashopConfig ( ConfigSection ) –

    Instance configurée selon le fichier renseigné.

Raises:

  • ConfigurationError –

    Si strict=True et que le fichier de configuration n'existe pas!

Source code in pycalendar_api/config/base.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
@classmethod
def from_config_file(cls, fpath: str|Path, *, with_section: bool=True) -> "ConfigSection":
    """Charge la configuration depuis un fichier toml respectant la structure attendue.

    Args:
        fpath (str): Chemin du fichier de configuration `.toml`

    Returns:
        DatashopConfig: Instance configurée selon le fichier renseigné.

    Raises:
        ConfigurationError: Si `strict=True` et que le fichier de configuration n'existe pas!
    """
    fpath = Path(fpath)
    if not fpath.exists():
        raise ConfigurationError(f"Le chemin du fichier de configuration n'existe pas. {fpath=}")

    dico = {}
    try:
        with open(fpath) as fd:
            dico = tomllib.loads(fd.read())

        dico = toml_doc_to_dict(dico)
    except PermissionError:
        msg = f"Accès refusé au chemin {fpath=}"
        raise ConfigurationError(msg)

    if cls.section == 'root':
        return cls(**dico)

    if with_section:
        kwargs = dico.get(cls.section, {})
        if cls.key is None:
            return cls(**kwargs)
        else:
            return cls(**kwargs.get(cls.key, {}))
    else:
        # Flat file without nesting
        if cls.key:
            return cls(**dico.get(cls.key, {}))

override

override(**options) -> HTTPClientConfig

Copy of this section with some options replaced

Raises:

Source code in pycalendar_api/config/settings.py
60
61
62
63
64
65
66
67
68
69
70
def override(self, **options) -> "HTTPClientConfig":
    """Copy of this section with some options replaced

    Raises:
        TypeError: Unknown option
    """
    unknown = set(options) - {f.name for f in fields(self)}
    if unknown:
        msg = f"Unknown HTTP client option(s) {sorted(unknown)}. Valid options: {[f.name for f in fields(self)]}"
        raise TypeError(msg)
    return replace(self, **options)

HTTPClientOptions

Keyword arguments accepted by CalendarApi / AsyncCalendarApi to override HTTPClientConfig

Settings dataclass

Settings(section: ClassVar = 'root', api: ApiConfig = ApiConfig(), http_client: HTTPClientConfig = HTTPClientConfig())

pycalendar_api client config file

Methods:

__post_init__

__post_init__()

One level config File

Source code in pycalendar_api/config/settings.py
 94
 95
 96
 97
 98
 99
100
def __post_init__(self):
    """One level config File"""
    for f in fields(self):
        attr = getattr(self, f.name)
        if isinstance(attr, dict):
            instance = f.type(**attr)
            setattr(self, f.name, instance)

from_config_file classmethod

from_config_file(fpath: str | Path, *, with_section: bool = True) -> ConfigSection

Charge la configuration depuis un fichier toml respectant la structure attendue.

Parameters:

  • fpath

    (str) –

    Chemin du fichier de configuration .toml

Returns:

  • DatashopConfig ( ConfigSection ) –

    Instance configurée selon le fichier renseigné.

Raises:

  • ConfigurationError –

    Si strict=True et que le fichier de configuration n'existe pas!

Source code in pycalendar_api/config/base.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
@classmethod
def from_config_file(cls, fpath: str|Path, *, with_section: bool=True) -> "ConfigSection":
    """Charge la configuration depuis un fichier toml respectant la structure attendue.

    Args:
        fpath (str): Chemin du fichier de configuration `.toml`

    Returns:
        DatashopConfig: Instance configurée selon le fichier renseigné.

    Raises:
        ConfigurationError: Si `strict=True` et que le fichier de configuration n'existe pas!
    """
    fpath = Path(fpath)
    if not fpath.exists():
        raise ConfigurationError(f"Le chemin du fichier de configuration n'existe pas. {fpath=}")

    dico = {}
    try:
        with open(fpath) as fd:
            dico = tomllib.loads(fd.read())

        dico = toml_doc_to_dict(dico)
    except PermissionError:
        msg = f"Accès refusé au chemin {fpath=}"
        raise ConfigurationError(msg)

    if cls.section == 'root':
        return cls(**dico)

    if with_section:
        kwargs = dico.get(cls.section, {})
        if cls.key is None:
            return cls(**kwargs)
        else:
            return cls(**kwargs.get(cls.key, {}))
    else:
        # Flat file without nesting
        if cls.key:
            return cls(**dico.get(cls.key, {}))