| 25 | |
| 26 | |
| 27 | class Apps: |
| 28 | def __init__( |
| 29 | self, |
| 30 | config: dict[str, dict[str, Any]] | None, |
| 31 | connections: ConnectionHandler, |
| 32 | table_name_generator: Callable[[type[Model]], str] | None = None, |
| 33 | *, |
| 34 | validate_connections: bool = True, |
| 35 | ) -> None: |
| 36 | self.apps: dict[str, dict[str, type[Model]]] = {} |
| 37 | self._config = config or {} |
| 38 | self._connections = connections |
| 39 | self._table_name_generator = table_name_generator |
| 40 | self._validate_connections = validate_connections |
| 41 | if self._config: |
| 42 | self._load_from_config() |
| 43 | |
| 44 | @staticmethod |
| 45 | def _discover_models(models_path: ModuleType | str, app_label: str) -> list[type[Model]]: |
| 46 | if isinstance(models_path, ModuleType): |
| 47 | module = models_path |
| 48 | else: |
| 49 | try: |
| 50 | module = importlib.import_module(models_path) |
| 51 | except ImportError: |
| 52 | raise ConfigurationError(f'Module "{models_path}" not found') |
| 53 | discovered_models: list[type[Model]] = [] |
| 54 | if possible_models := getattr(module, "__models__", None): |
| 55 | try: |
| 56 | possible_models = [*possible_models] |
| 57 | except TypeError: |
| 58 | possible_models = None |
| 59 | if not possible_models: |
| 60 | possible_models = [getattr(module, attr_name) for attr_name in dir(module)] |
| 61 | for attr in possible_models: |
| 62 | if isclass(attr) and issubclass(attr, Model) and not attr._meta.abstract: |
| 63 | if attr._meta.app and attr._meta.app != app_label: |
| 64 | continue |
| 65 | attr._meta.app = app_label |
| 66 | discovered_models.append(attr) |
| 67 | if not discovered_models: |
| 68 | warnings.warn(f'Module "{models_path}" has no models', RuntimeWarning, stacklevel=4) |
| 69 | return discovered_models |
| 70 | |
| 71 | def init_app( |
| 72 | self, |
| 73 | label: str, |
| 74 | module_list: Iterable[ModuleType | str], |
| 75 | _init_relations: bool = True, |
| 76 | ) -> dict[str, type[Model]]: |
| 77 | app_models: list[type[Model]] = [] |
| 78 | for module in module_list: |
| 79 | app_models += self._discover_models(module, label) |
| 80 | |
| 81 | self.apps[label] = {model.__name__: model for model in app_models} |
| 82 | |
| 83 | if _init_relations: |
| 84 | self._init_relations() |
no outgoing calls
no test coverage detected
searching dependent graphs…