You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
58 lines
1.4 KiB
58 lines
1.4 KiB
from pathlib import Path
|
|
from typing import Dict
|
|
from typing import Optional
|
|
|
|
from dependency_injector import containers
|
|
from dependency_injector import providers
|
|
from flask_api import FlaskAPI
|
|
from serial import Serial
|
|
|
|
DEFAULTS_DIR = Path(__file__).parent / "defaults"
|
|
CONFIG_FILE = DEFAULTS_DIR / "config.yml"
|
|
|
|
|
|
class Container(containers.DeclarativeContainer):
|
|
config = providers.Configuration("config")
|
|
|
|
serial = providers.Factory(
|
|
Serial,
|
|
port=config.device_id.required(),
|
|
baudrate=config.baudrate.required(),
|
|
)
|
|
|
|
|
|
__container: Optional[Container] = None
|
|
|
|
|
|
def initialize_container(
|
|
config: Optional[Dict] = None,
|
|
config_file: Optional[Path] = None,
|
|
) -> Container:
|
|
global __container
|
|
if __container is not None:
|
|
raise RuntimeError("Container already initialized")
|
|
|
|
__container = Container()
|
|
__container.config.from_yaml(CONFIG_FILE)
|
|
|
|
if config is not None:
|
|
__container.config.from_dict(config)
|
|
|
|
if config_file is not None:
|
|
__container.config.from_yaml(config_file)
|
|
|
|
return __container
|
|
|
|
|
|
def init_app(app: FlaskAPI):
|
|
initialize_container(
|
|
config=app.config.get("DI_CONFIG"),
|
|
config_file=app.config.get("DI_CONFIG_FILE"),
|
|
)
|
|
|
|
|
|
def get_container() -> Container:
|
|
global __container
|
|
if __container is None:
|
|
raise RuntimeError("Container not initialized")
|
|
return __container
|
|
|