class Container(DeclarativeContainer): config = Configuration(default={"cell": 0.0, "shape": (2, 2)}) matrix = Factory(Mock, ABCMinimalMatrix, get_cell=Mock(return_value=config.cell()), get_shape=Mock(return_value=config.shape())) formatter = Factory(JsonFormat, matrix=matrix)
class DumpContainer(DeclarativeContainer): config = Configuration() write_factory = Factory(FileWriteFactory, path=config.path) format_factory = Factory(JsonFormatFactory, matrix=config.matrix) dumper = Factory(MatrixDump, write_factory=write_factory, format_factory=format_factory)
class SummarizeContainer(DeclarativeContainer): config = Configuration() matrix_factory = Factory(MinimalMatrixFactory) summarize_pair_factory = Factory(SummarizePairFactory, matrix_factory=matrix_factory) summarize = Factory(Summarize, matrices=config.matrices, summarize_pair_factory=summarize_pair_factory)
class Container(DeclarativeContainer): logger = Factory(Mock, Logger) next_handler = Factory(Mock, ABCFileHandler) name = Factory(Mock, AnyStr) handler = Factory(LoggingHandler, logger=logger, next_handler=next_handler, name=name)
class FileLoadContainer(DeclarativeContainer): config = Configuration() read_factory = Factory(FileReadFactory, path=config.path) parser_factory = Factory(JsonParserFactory) matrix_factory = Factory(MinimalMatrixFactory) loader = Factory(FileLoadMatrices, read_factory=read_factory, parser_factory=parser_factory, matrix_factory=matrix_factory)
class ServiceContainer(DeclarativeContainer): basedir = os.path.abspath(os.path.dirname(__file__)) db_client = Factory(sqlite3.connect, basedir + '/../data/database.sqlite') db_service = Factory(SQLiteService, db_client=db_client) doctor_data_service = Factory(DoctorDataService, db_service=db_service) appointments_data_service = Factory(DoctorAppointmentDataService, db_service=db_service)
class HandleContainer(DeclarativeContainer): config = Configuration() base_file_handler = Factory(BaseFileHandler, write=config.write) txt_handler = Factory(LoggingHandler, logger=config.logger, next_handler=base_file_handler, name="txt") csv_handler = Factory(LoggingHandler, logger=config.logger, next_handler=base_file_handler, name="csv") json_handler = Factory(LoggingHandler, logger=config.logger, next_handler=base_file_handler, name="json") xml_handler = Factory(LoggingHandler, logger=config.logger, next_handler=base_file_handler, name="xml") routing_map = Factory(dict, txt=txt_handler, csv=csv_handler, json=json_handler, xml=xml_handler) routing_table = Factory(SimpleRoutingTable, routing_map=routing_map) routing_handler = Factory(RoutingHandler, routing_table=routing_table)
class RootContainer(DeclarativeContainer): """Application IoC container""" config = Configuration('config') loop = Singleton(get_event_loop) # Remote services engine = Singleton(_create_engine_wrapper, config.db.connect_string, config.db.options) http = Factory(ClientSession, loop=loop, raise_for_status=True) sessionmaker = Singleton(_sessionmaker, bind=engine) scoped_session = Singleton(_scoped_session, sessionmaker, scopefunc=event_context.get) context_factory = DelegatedFactory(Context, scoped_session=scoped_session) bot = Singleton(Bot, command_prefix=config.cmd_prefix, context_factory=context_factory, default_game=config.default_game, loop=loop, scoped_session=scoped_session) # Main run_bot = Callable(Bot.run, bot, config.token)
class Container(DeclarativeContainer): config = Configuration(default={"matrix_count": 2}) matrix = Factory(Mock, ABCMinimalMatrix, get_cell=Mock(return_value=config.cell), get_shape=Mock(return_value=config.shape)) matrices = Factory( lambda matrix_factory, matrix_count: [matrix_factory() for i in range(0, matrix_count)], matrix.provider, config.matrix_count) summarize_pair = Factory(Mock, ABCSummarize, return_value=matrix) summarize_pair_factory = Factory(Mock, ABCSummarizePairFactory, return_value=summarize_pair) summarize = Factory(Summarize, matrices=matrices, summarize_pair_factory=summarize_pair_factory)
class WeatherForecastContainer(DeclarativeContainer): weather_forecast_repository = Dependency() weather_forecast_loader = Dependency() timestamp_round_algorithm = Factory(CeilTimestampRoundAlgorithm, round_step=TIME_TICK) weather_forecast_preprocessor = Factory( SoftMWeatherProcessor, timestamp_round_algorithm=timestamp_round_algorithm, timestamp_interpolation_algorithm=Factory( TimestampInterpolationAlgorithm, timestamp_round_algorithm, TIME_TICK), timestamp_filter_algorithm=Factory(FullClosedTimestampFilterAlgorithm), border_values_interpolation_algorithm=Factory( LinearInsideValueInterpolationAlgorithm), internal_values_interpolation_algorithm=Factory( LinearOutsideValueInterpolationAlgorithm)) weather_forecast_service = Factory( SimpleWeatherForecastService, weather_forecast_loader=weather_forecast_loader, weather_forecast_processor=weather_forecast_preprocessor, weather_forecast_repository=weather_forecast_repository, preload_timedelta=Object(pd.Timedelta(hours=3)), executor=None)
class TempGraphContainer(DeclarativeContainer): temp_graph_repository = Dependency() temp_graph_loader = Dependency() temp_graph_update_service = Factory( SimpleTempGraphUpdateService, temp_graph_loader=temp_graph_loader, temp_graph_dumper=temp_graph_repository )
class ControlActionReportContainer(DeclarativeContainer): config = Configuration(strict=True) control_action_repository = Dependency() control_action_report_service = Factory( ControlActionReportService, timestamp_report_pattern_v1=config.timestamp_report_pattern_v1, control_action_repository=control_action_repository)
class Container(DeclarativeContainer): config = Configuration(default={"matrix_count": 2}) reader = Factory(Mock, ABCRead, return_value=config.content) read_factory = Factory(Mock, ABCReadFactory, return_value=reader) matrix_like = Factory(Mock, ArrayLike) matrix_like_list = Factory(lambda matrix_like_factory, matrix_count: [matrix_like_factory() for i in range(0, matrix_count)], matrix_like.provider, config.matrix_count) parser = Factory(Mock, ABCParser, return_value=matrix_like_list) parser_factory = Factory(Mock, ABCParserFactory, return_value=parser) matrix = Factory(Mock, ABCMinimalMatrix, get_cell=Mock(return_value=config.cell), get_shape=Mock(return_value=config.shape)) matrix_factory = Factory(Mock, ABCMinimalMatrixFactory, return_value=matrix) load = Factory(FileLoadMatrices, read_factory=read_factory, parser_factory=parser_factory, matrix_factory=matrix_factory)
class UIContainer(DeclarativeContainer): application: Dependency[QApplication] = Dependency() library_manager: Dependency[LibraryManager] = Dependency() settings_window = Factory(SettingsWindow) window_controller = Singleton(WindowController, application, library_manager) libraries_model = Factory(LibrariesModel, library_manager=library_manager) libraries_window = Factory( LibrariesWindow, library_manager=library_manager, libraries_model=libraries_model, ) main_window = Factory( MainWindow, library_manager=library_manager, window_controller=window_controller, libraries_window_factory=libraries_window.provider, settings_window_factory=settings_window.provider, )
class Container(DeclarativeContainer): """The Container class wires all reusable components together.""" logger = Singleton(Logger) task_manager = Singleton(TaskManager, logger) name_generator = Singleton(NameGenerator) path_manager = Singleton(PathManager) temp_manager = Singleton(TempManager) xml_manager = Singleton(XMLManager) general_storage = Singleton(Storage, file=GENERAL_CONFIG_PATH) credentials_storage = Singleton(Storage, file=CREDENTIALS_CONFIG_PATH) cache_storage = Singleton(Storage, file=CACHE_PATH) project_config_manager = Singleton(ProjectConfigManager, xml_manager) cli_config_manager = Singleton(CLIConfigManager, general_storage, credentials_storage) lean_config_manager = Singleton(LeanConfigManager, cli_config_manager, project_config_manager) optimizer_config_manager = Singleton(OptimizerConfigManager, logger) project_manager = Singleton(ProjectManager, project_config_manager, xml_manager) api_client = Factory( APIClient, logger, user_id=cli_config_manager.provided.user_id.get_value()(), api_token=cli_config_manager.provided.api_token.get_value()()) cloud_runner = Singleton(CloudRunner, logger, api_client, task_manager) pull_manager = Singleton(PullManager, logger, api_client, project_manager, project_config_manager) push_manager = Singleton(PushManager, logger, api_client, project_manager, project_config_manager) data_downloader = Singleton(DataDownloader, logger, api_client, lean_config_manager) cloud_project_manager = Singleton(CloudProjectManager, api_client, project_config_manager, pull_manager, push_manager, path_manager) docker_manager = Singleton(DockerManager, logger, temp_manager) lean_runner = Singleton(LeanRunner, logger, project_config_manager, lean_config_manager, docker_manager, temp_manager) update_manager = Singleton(UpdateManager, logger, cache_storage, docker_manager)
class WSGI(DeclarativeContainer): config = Configuration(strict=True) app = Resource(FastAPIApp, api_routers=Object([ api_v1.api_router, api_v2.api_router, api_v3.api_router ])) server = Singleton( uvicorn.Server, config=Factory( uvicorn.Config, app=app, host=config.host, port=config.port, # log_config=None ))
class Repositories(DeclarativeContainer): config = Configuration(strict=True) temp_graph_repository = Singleton(SyncTempGraphInMemoryDumperLoader) weather_forecast_repository = Singleton( WeatherForecastRepository, filter_algorithm=Factory(FullClosedTimestampFilterAlgorithm)) control_actions_repository = Singleton(ControlActionsRepository) dynamic_settings_repository = Resource( DynamicSettingsRepositoryResource, session_factory=Resource(AsyncSettingsDBSessionFactory, db_engine=Resource( AsyncSettingsDBEngine, db_url=config.db_settings_url)), dtype_converters=Object([ dtype_converters.BooleanDTypeConverter(), dtype_converters.DatetimeDTypeConverter(), dtype_converters.FloatDTypeConverter(), dtype_converters.IntDTypeConverter(), dtype_converters.StrDTypeConverter(), dtype_converters.NoneDTypeConverter(), dtype_converters.TimedeltaDTypeConverter() ]), default_settings=Object(default_config.DICT))
class Gateways(DeclarativeContainer): config = Configuration(strict=True) temp_graph_reader = Factory(SoftMSyncTempGraphJSONReader) temp_graph_loader = Factory(SoftMAsyncTempGraphOnlineLoader, reader=temp_graph_reader) weather_forecast_timezone = Callable( gettz, config.weather_forecast_loader.weather_server_timezone) weather_forecast_reader = Factory( SoftMSyncWeatherForecastJSONReader, weather_data_timezone=weather_forecast_timezone) weather_forecast_loader = Factory(SoftMAsyncWeatherForecastOnlineLoader, reader=weather_forecast_reader) time_delta_loader = Factory( SyncTimedeltaFileLoader, filepath=config.time_delta_loader.heating_objects_time_delta_path, reader=Factory(SyncTimedeltaCSVReader, separator=","))
class Container(DeclarativeContainer): config = Configuration() parser = Factory(JsonParser, content=config.content)
class Service(DeclarativeContainer): """Services.""" user: Callable[..., UserService] = Factory(Factories.user)
class Container(DeclarativeContainer): config = Configuration() writer = Factory(FileWrite, path=config.path, content=config.content)
class Factories(DeclarativeContainer): """Factories.""" user: Callable[..., UserService] = Factory(UserService)
class Container(DeclarativeContainer): config = Configuration() json_format = Factory(MatrixPairJsonFormat, matrix1=config.matrix1, matrix2=config.matrix2)
class Container(DeclarativeContainer): config = Configuration() summarize_adapter = Factory(SummarizeAdapter, input_path=config.input_path, output_path=config.output_path)
from typing import Any, List from sqlalchemy import inspect from dependency_injector.providers import Factory from src.db.crud.crud_base import CRUDBase from src.db.models.book import Book as BookDbModel from src.schemas.book import Book, BookCreate, BookUpdate class CRUDBook(CRUDBase[BookDbModel, Book, BookCreate, BookUpdate]): def get_by_column(self, column_name: str, value: Any) -> List[Book]: insp = inspect(BookDbModel) books_db = (self.db.query(BookDbModel).filter( insp.all_orm_descriptors[column_name].like(f"%{value}%")).all()) books_schema = [self.schema.from_orm(book) for book in books_db] return books_schema CRUDBookFactory = Factory(CRUDBook, model=BookDbModel, schema=Book)
username=obj_in.username, is_superuser=obj_in.is_superuser, password_hash=get_password_hash(obj_in.password), ) self.db.add(db_obj) self.db.commit() self.db.refresh(db_obj) return self.schema.from_orm(db_obj) def update( self, *, db_obj: UserDbModel, obj_in: Union[UserUpdate, Dict[str, Any]] ) -> User: if isinstance(obj_in, dict): update_data = obj_in else: update_data = obj_in.dict(exclude_unset=True) if update_data["password"]: hashed_password = get_password_hash(update_data["password"]) update_data.pop("password") update_data["password_hash"] = hashed_password return super().update(db_obj=db_obj, obj_in=update_data) def is_active(self, user: User) -> bool: return user.confirmed def is_superuser(self, user: User) -> bool: return user.is_superuser CRUDUserFactory = Factory(CRUDUser, model=UserDbModel, schema=User)
def factory(self, alias, instance, *args, **kwargs): setattr(self.container, alias, Factory(instance, *args, **kwargs))
class Container(DeclarativeContainer): stream = Factory(Mock, AbcStream) formatter = Factory(Mock, AbcFormatter) dump = Factory(Dump, stream=stream, formatter=formatter)
class Container(DeclarativeContainer): routing_table = Factory(Mock, ABCRoutingTable) handler = Factory(RoutingHandler, routing_table=routing_table)
class ControlActionContainer(DeclarativeContainer): config = Configuration(strict=True) temp_graph_repository = Dependency() weather_forecast_repository = Dependency() control_actions_repository = Dependency() dynamic_settings_repository = Dependency() time_delta_loader = Dependency() # TODO: перевести на репозиторий temp_correlation_table = Resource( TempCorrelationTable, config.temp_correlation_table_path ) # TODO: перевести на репозиторий time_delta_df = Resource( HeatingObjTimedeltaResource, loader=time_delta_loader ) model_requirements = Factory( TimedeltaModelRequirementsWithoutHistory, time_delta_df ) timestamp_round_algo = Factory( CeilTimestampRoundAlgorithm, round_step=TIME_TICK ) temp_constrains = Factory( SingleTypeHeatingObjOnWeatherConstraint, temp_requirements_predictor=Factory( TempGraphRequirementsPredictor, temp_graph=temp_graph_repository.provided.load_temp_graph.call(), weather_temp_round_algorithm=Factory(ArithmeticFloatRoundAlgorithm) ), timestamp_round_algo=timestamp_round_algo, temp_requirements_coefficient=Coroutine( get_one_setting, dynamic_settings_repository, config_names.APARTMENT_HOUSE_MIN_TEMP_COEFFICIENT ), min_model_error=Coroutine( get_one_setting, dynamic_settings_repository, config_names.MODEL_ERROR_SIZE ) ) heating_system_model = Factory( CorrTableHeatingSystemModel, temp_correlation_df=temp_correlation_table, timedelta_df=time_delta_df, ) control_action_predictor = Factory( SingleCircuitControlActionPredictor, heating_system_model=heating_system_model, temp_requirements_constraint=temp_constrains, min_boiler_temp=Coroutine( get_one_setting, dynamic_settings_repository, config_names.MIN_BOILER_TEMP ), max_boiler_temp=Coroutine( get_one_setting, dynamic_settings_repository, config_names.MAX_BOILER_TEMP ), min_regulation_step=0.3 ) temp_prediction_service = Factory( ControlActionPredictionService, weather_forecast_repository=weather_forecast_repository, control_actions_repository=control_actions_repository, control_action_predictor=control_action_predictor, model_requirements=model_requirements, timestamp_round_algo=timestamp_round_algo, timedelta=TIME_TICK, timedelta_predict_forward=pd.Timedelta(seconds=3600), executor=None )