Getting started
Configuration
The configuration of your Expanse application is done through configuration files located in the config directory
or through environment variables or a mix of both.
Configuring via files
Expanse will automatically read configuration files in the config directory. Configuration
files must expose either a config dictionary or a Config class that inherits from
Pydantic's BaeSettings class.
from pydantic_settings import BaseSettings, SettingsConfigDict
class Config(BaseSettings):
foo: str = "bar"
from typing import Any
config: dict[str, Any] = {
"foo": "bar",
}
Configuration values are then accessible from the Config object nested inside
a configuration key based on the name of the configuration file. For instance,
if the settings above are put inside a my_config.py file, the foo setting
should be retrieved using the my-config.foo key.
Configuring via environment variables
It is often good practice to provide settings to your application through the environment. This makes it more flexible without having to tinker with configuration files. This is especially useful since the requirements of your application might differ between the development environment and the production one: for instance, you might want to use a SQLite database in development and a PostgreSQL one in production.
Most standard settings in Expanse can be configured via environment variables. If you have a .env file at the root of
your application, Expanse will automatically load it on application startup.
When setting up your application
via the official installer, a .env.example file will be present with examples
of settings configuration and will be automatically copied to a .env file which will serve as the default settings.
If you define your own configuration files, you should try to retrieve setting values
from environment variables, either manually via os.getenv or using a model_config
when using Pydantic settings.
from pydantic_settings import BaseSettings, SettingsConfigDict
class Config(BaseSettings):
foo: str
model_config = SettingsConfigDict(env_prefix="my_config_", env_nested_delimiter="__")
import os
from typing import Any
config: dict[str, Any] = {
"foo": os.getenv("MY_CONFIG_FOO")
}
Accessing the configuration
If you need to retrieve settings for your application, you can either retrieve the configuration from
the service container
or type-hint the Config class anywhere dependency injection is
available.
from expanse.common.configuration.config import Config
from expanse.container.container import Container
def route_endpoint(container: Container, config: Config) -> None:
# Retrieve config from container
config2 = container.make(Config)
assert config == config2
To retrieve a specific setting, you can use the get() method on the Config class:
config = container.make(Config)
value = config.get("app.name")
# You can also give a default value if the setting is not currently set
value = config.get("app.name", "My app")