Set up the bones of a Flask app with configuration
This commit is contained in:
parent
0909fd7e99
commit
a7fdd6cbd0
7 changed files with 131 additions and 1 deletions
38
src/config/__init__.py
Normal file
38
src/config/__init__.py
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
import json
|
||||
from logging import INFO
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from .logging import Logging
|
||||
from .parse import ConfigParseError, assert_key_of_type
|
||||
|
||||
|
||||
@dataclass
|
||||
class Config:
|
||||
host: str | None
|
||||
port: int | None
|
||||
logging: Logging
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, config: dict[str, Any]) -> 'Config':
|
||||
assert_key_of_type(config, 'logging', dict)
|
||||
assert_key_of_type(config, 'host', str)
|
||||
assert_key_of_type(config, 'port', int)
|
||||
try:
|
||||
log_config = Logging.from_dict(config['logging'])
|
||||
return Config(host=config['host'], port=config['port'], logging=log_config)
|
||||
|
||||
except ConfigParseError as e:
|
||||
raise ConfigParseError(['logging', *e.keypath], e.issue) from e
|
||||
|
||||
|
||||
DEFAULT_CONFIG = Config(logging=Logging(level=INFO), port=None, host=None)
|
||||
|
||||
|
||||
def parse_config(filename: str) -> Config:
|
||||
with open(filename, 'r') as infile:
|
||||
config = json.loads(infile.read())
|
||||
return Config.from_dict(config)
|
||||
|
||||
|
||||
__all__ = ['Config', 'parse_config', 'DEFAULT_CONFIG']
|
||||
Loading…
Add table
Add a link
Reference in a new issue