Like dataclasses but for config.
Project description
configclasses
Like dataclasses but for config.
Specify your config with a class and load it with your env vars or env files.
import httpx
from configclasses import configclass
class UserAPIClient(httpx.AsyncClient):
def __init__(self, config: ClientConfig, *args, **kwargs):
self.config = config
super().__init__(*args, **kwargs)
async def get_users(self, headers: Optional[Headers] = None) -> Dict[str, Any]:
response = await self.get(f"{self.path}/users", auth=headers)
response.raise_for_status()
return response.json()
@configclass
class ClientConfig:
host: str
port: int
config = ClientConfig.from_path(".env")
async with UserAPIClient(config) as client:
users = await client.get_users(auth_headers)
Features
- Fill your configclasses with existent env vars.
- Define default values in case these variables have no value at all.
- Load your config files in env vars following 12factor apps recommendations.
- Support for .env, yaml, toml, ini and json.
- Convert your env vars with specified type in configclass:
int
,float
,str
orbool
. - Use nested configclasses to more complex configurations.
- Specify a prefix with
@configclass(prefix="<PREFIX>")
to append this prefix to your configclass' attribute names. - Config groups (TODO): https://cli.dev/docs/tutorial/config_groups/
Requirements
Python 3.8+
Installation
Depending on your chosen config file format you can install:
- .env ->
pip install 12factor-configclasses[dotenv]
- .yaml ->
pip install 12factor-configclasses[yaml]
- .toml ->
pip install 12factor-configclasses[toml]
- .ini ->
pip install 12factor-configclasses
- .json ->
pip install 12factor-configclasses
Or install all supported formats with:
pip install 12factor-configclasses[full]
Usage
There are three ways to use it:
- Loading an .env file:
# .env
HOST=0.0.0.0
PORT=8000
DB_URL=sqlite://:memory:
GENERATE_SCHEMAS=True
DEBUG=True
HTTPS_ONLY=False
GZIP=True
SENTRY=False
#config.py
from configclasses import configclass
@configclass
class DB:
user: str
password: str
url: str
@configclass
class AppConfig:
host: str
port: int
db: DB
generate_schemas: bool
debug: bool
https_only: bool
gzip: bool
sentry: bool
# app.py
from api.config import AppConfig
app_config = AppConfig.from_path(".env")
app = Starlette(debug=app_config.debug)
if app_config.https_only:
app.add_middleware(
HTTPSRedirectMiddleware)
if app_config.gzip:
app.add_middleware(GZipMiddleware)
if app_config.sentry:
app.add_middleware(SentryAsgiMiddleware)
...
register_tortoise(
app,
db_url=app_config.db.url,
modules={"models": ["api.models"]},
generate_schemas=app_config.generate_schemas,
)
if __name__ == "__main__":
uvicorn.run(app, host=app_config.host, port=app_config.port)
- Loading predefined environmental variables:
The same than before, but instead of:
app_config = AppConfig.from_path(".env")
You will do:
app_config = AppConfig.from_environ()
- Loading a file from a string:
test_env = """HOST=0.0.0.0
PORT=8000
DB_URL=sqlite://:memory:
GENERATE_SCHEMAS=True
DEBUG=True
HTTPS_ONLY=False
GZIP=True
SENTRY=False"""
app_config = AppConfig.from_string(test_env, ".env")
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Close
Hashes for 12factor-configclasses-1.0.0.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | d5531c17b6c7445d94e48024bd5d37264a376e39dd4088950a9664d020afb197 |
|
MD5 | fa70d51c12ad98f799067e3fd5ee5fad |
|
BLAKE2b-256 | 2586c0e3b447f9b2f210ce7000479175e577aa51ec1507617ec2333323a8726c |
Close
Hashes for 12factor_configclasses-1.0.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 435cf66d2c7f60f9425a2a9d466300f462cf4902b9b8f10e6689ac48c1033531 |
|
MD5 | ac7d8df2d829f3f32c971d22f33f411f |
|
BLAKE2b-256 | cbf0ec7449e4a56596339f62b953968f6400b5883ac4c4da35b1cae8a2be9aa8 |