mirror of
https://github.com/aiogram/aiogram.git
synced 2026-04-08 16:37:47 +00:00
Add possibility to include router via string
This commit is contained in:
parent
b943ea2207
commit
dadedc80a9
6 changed files with 86 additions and 3 deletions
|
|
@ -1,8 +1,9 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict, List, Optional
|
||||
from typing import Any, Dict, List, Optional, Union
|
||||
|
||||
from ..api.types import Chat, Update, User
|
||||
from ..utils.imports import import_module
|
||||
from .event.observer import EventObserver, SkipHandler, TelegramEventObserver
|
||||
from .filters import BUILTIN_FILTERS
|
||||
|
||||
|
|
@ -76,7 +77,13 @@ class Router:
|
|||
|
||||
self._parent_router = router
|
||||
|
||||
def include_router(self, router: Router) -> Router:
|
||||
def include_router(self, router: Union[Router, str]) -> Router:
|
||||
if isinstance(router, str):
|
||||
router = import_module(router)
|
||||
if not isinstance(router, Router):
|
||||
raise ValueError(
|
||||
f"router should be instance of Router not {type(router).__class__.__name__}"
|
||||
)
|
||||
router.parent_router = self
|
||||
self.sub_routers.append(router)
|
||||
return router
|
||||
|
|
|
|||
23
aiogram/utils/imports.py
Normal file
23
aiogram/utils/imports.py
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
import importlib
|
||||
from typing import Any
|
||||
|
||||
|
||||
def import_module(target: str) -> Any:
|
||||
if not isinstance(target, str):
|
||||
raise ValueError(f"Target should be string not {type(target).__class__.__name__}")
|
||||
|
||||
module_name, _, attr_name = target.partition(":")
|
||||
if not module_name or not attr_name:
|
||||
raise ValueError(f'Import string "{target}" must be in format "<module>:<attribute>"')
|
||||
|
||||
try:
|
||||
module = importlib.import_module(module_name)
|
||||
except ImportError:
|
||||
raise ValueError(f'Could not import module "{module_name}".')
|
||||
|
||||
try:
|
||||
attribute = getattr(module, attr_name)
|
||||
except AttributeError:
|
||||
raise ValueError(f'Module "{module_name}" has no attribute "{attr_name}"')
|
||||
|
||||
return attribute
|
||||
Loading…
Add table
Add a link
Reference in a new issue