Skip to content

Commit

Permalink
Изменения из aiogram'а и улучшение Ruff'а
Browse files Browse the repository at this point in the history
Fix missing error logging (by @unintended)
loosened pydantic upper bound to <2.8 (by @jorenham)
Bump actions versions (by @Olegt0rr)
  • Loading branch information
K1rL3s committed May 10, 2024
1 parent 94830c2 commit 5c4dad9
Show file tree
Hide file tree
Showing 98 changed files with 305 additions and 241 deletions.
5 changes: 3 additions & 2 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ jobs:
uses: actions/checkout@v4

- name: Set up Python ${{ matrix.python-version }} on ${{ matrix.os }}
uses: actions/setup-python@v4
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
cache: "pip"
Expand Down Expand Up @@ -102,6 +102,7 @@ jobs:
python-version:
- 'pypy3.8'
- 'pypy3.9'
- 'pypy3.10'

defaults:
# Windows sucks. Force use bash instead of PowerShell
Expand All @@ -115,7 +116,7 @@ jobs:
uses: actions/checkout@v4

- name: Set up Python ${{ matrix.python-version }} on ${{ matrix.os }}
uses: actions/setup-python@v4
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
cache: "pip"
Expand Down
2 changes: 1 addition & 1 deletion aliceio/client/context_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class SkillContextController(BaseModel):
def __init__(
__pydantic_self__,
*,
_skill: Optional["Skill"] = PrivateAttr(),
_skill: Optional["Skill"],
**__pydantic_kwargs: Any,
) -> None:
super().__init__(
Expand Down
15 changes: 6 additions & 9 deletions aliceio/client/session/aiohttp.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
Any,
Dict,
Iterable,
List,
Optional,
Tuple,
Type,
Expand Down Expand Up @@ -63,7 +62,7 @@ def _retrieve_basic(basic: _ProxyBasic) -> Dict[str, Any]:

def _prepare_connector(
chain_or_plain: _ProxyType,
) -> Tuple[Type["TCPConnector"], Dict[str, Any]]:
) -> Tuple[Type[TCPConnector], Dict[str, Any]]:
from aiohttp_socks import ( # type: ignore
ChainProxyConnector,
ProxyConnector,
Expand All @@ -80,9 +79,7 @@ def _prepare_connector(
return ProxyConnector, _retrieve_basic(chain_or_plain)

chain_or_plain = cast(_ProxyChain, chain_or_plain)
infos: List[ProxyInfo] = []
for basic in chain_or_plain:
infos.append(ProxyInfo(**_retrieve_basic(basic)))
infos = [ProxyInfo(**_retrieve_basic(basic)) for basic in chain_or_plain]

return ChainProxyConnector, {"proxy_infos": infos}

Expand All @@ -105,7 +102,7 @@ def __init__(self, proxy: Optional[_ProxyType] = None, **kwargs: Any) -> None:
except ImportError as exc: # pragma: no cover
raise RuntimeError(
"In order to use aiohttp client for proxy requests, install "
"https://pypi.org/project/aiohttp-socks/"
"https://pypi.org/project/aiohttp-socks/",
) from exc

def _setup_proxy_connector(self, proxy: _ProxyType) -> None:
Expand Down Expand Up @@ -205,10 +202,10 @@ async def make_request(
headers=self._build_request_headers(skill),
) as resp:
raw_result = await resp.text()
except asyncio.TimeoutError:
raise AliceNetworkError(message="AliceRequest timeout error")
except asyncio.TimeoutError as e:
raise AliceNetworkError(message="AliceRequest timeout error") from e
except ClientError as e:
raise AliceNetworkError(message=f"{type(e).__name__}: {e}")
raise AliceNetworkError(message=f"{type(e).__name__}: {e}") from e
response = self.check_response(
skill=skill,
method=method,
Expand Down
12 changes: 7 additions & 5 deletions aliceio/client/session/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def check_response(
except Exception as e:
# Обрабатываемая ошибка не может быть поймана конкретным типом,
# поскольку декодер можно кастомизировать и вызвать любое исключение.
raise ClientDecodeError("Failed to decode object", e, content)
raise ClientDecodeError("Failed to decode object", e, content) from e

if HTTPStatus.OK <= status_code <= HTTPStatus.IM_USED:
try:
Expand All @@ -73,19 +73,22 @@ def check_response(
context={"skill": skill},
)
except ValidationError as e:
raise ClientDecodeError("Failed to deserialize object", e, json_data)
raise ClientDecodeError(
"Failed to deserialize object",
e,
json_data,
) from e

try:
response = ErrorResult.model_validate(json_data)
except ValidationError as e:
raise ClientDecodeError("Failed to deserialize object", e, json_data)
raise ClientDecodeError("Failed to deserialize object", e, json_data) from e

raise AliceAPIError(message=response.message)

@abc.abstractmethod
async def close(self) -> None: # pragma: no cover
"""Закрыть клиентскую сессию."""
pass

@abc.abstractmethod
async def make_request(
Expand All @@ -103,7 +106,6 @@ async def make_request(
:return:
:raise AliceApiError:
"""
pass

async def __call__(
self,
Expand Down
7 changes: 3 additions & 4 deletions aliceio/client/session/middlewares/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
class NextRequestMiddlewareType(Protocol[AliceType]): # pragma: no cover
async def __call__(
self,
skill: "Skill",
skill: Skill,
method: AliceMethod[AliceType],
) -> ApiResponse[AliceType]:
pass
Expand All @@ -23,7 +23,7 @@ class RequestMiddlewareType(Protocol): # pragma: no cover
async def __call__(
self,
make_request: NextRequestMiddlewareType[AliceType],
skill: "Skill",
skill: Skill,
method: AliceMethod[AliceType],
) -> ApiResponse[AliceType]:
pass
Expand All @@ -36,7 +36,7 @@ class BaseRequestMiddleware(ABC):
async def __call__(
self,
make_request: NextRequestMiddlewareType[AliceType],
skill: "Skill",
skill: Skill,
method: AliceMethod[AliceType],
) -> ApiResponse[AliceType]:
"""
Expand All @@ -49,4 +49,3 @@ async def __call__(
:return: :class:`aiolice.methods.ApiResponse`
"""
pass
18 changes: 12 additions & 6 deletions aliceio/dispatcher/dispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def __init__(
:param kwargs: Остальные аргументы,
будут переданы в обработчики как именованные аргументы
"""
super(Dispatcher, self).__init__(name=name)
super().__init__(name=name)

self.update = self.observers["update"] = AliceEventObserver(
router=self,
Expand Down Expand Up @@ -82,7 +82,7 @@ def __init__(
self.update.outer_middleware(self.fsm)
if use_api_storage:
self.update.outer_middleware(
FSMApiStorageMiddleware(strategy=fsm_strategy)
FSMApiStorageMiddleware(strategy=fsm_strategy),
)
self.update.outer_middleware(ResponseConvertMiddleware())
self.shutdown.register(self.fsm.close)
Expand Down Expand Up @@ -116,7 +116,7 @@ def parent_router(self) -> Optional[Router]:
У диспетчера нет родительского маршрутизатора
и он не может быть включен ни в какие другие роутеры или диспетчеры.
"""
return None # noqa: RET501
return None

@parent_router.setter
def parent_router(self, value: Router) -> None:
Expand Down Expand Up @@ -207,7 +207,11 @@ async def feed_raw_update(
:param kwargs:
"""
parsed_update = Update.model_validate(update, context={"skill": skill})
return await self.feed_update(skill=skill, update=parsed_update, **kwargs)
return await self._feed_webhook_update(
skill=skill,
update=parsed_update,
**kwargs,
)

async def _listen_update(self, update: Update, **kwargs: Any) -> Any:
"""
Expand All @@ -228,8 +232,9 @@ async def _listen_update(self, update: Update, **kwargs: Any) -> Any:
"installed not latest version of aliceio framework"
f"\nUpdate: {update.model_dump_json(exclude_unset=True)}",
RuntimeWarning,
stacklevel=1,
)
raise SkipHandler() from e
raise SkipHandler from e

kwargs.update(event_update=update)

Expand Down Expand Up @@ -287,7 +292,7 @@ def release_waiter(*_: Any) -> None:
timeout_handle = loop.call_later(self.response_timeout, release_waiter)

process_updates: Future[Optional[AliceResponse]] = asyncio.ensure_future(
self._feed_webhook_update(skill=skill, update=update, **kwargs)
self._feed_webhook_update(skill=skill, update=update, **kwargs),
)
process_updates.add_done_callback(release_waiter, context=ctx)

Expand Down Expand Up @@ -325,6 +330,7 @@ async def _process_timeouted_update(
"the skill dialog, so be careful and register ultra-fast handlers "
"by `@<router>.timeout` to respond to timeouted updates.",
RuntimeWarning,
stacklevel=1,
)
return await self._feed_webhook_update(
skill=skill,
Expand Down
2 changes: 1 addition & 1 deletion aliceio/dispatcher/event/alice.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def register(
callback=callback,
filters=[FilterObject(filter_) for filter_ in filters],
flags=flags,
)
),
)

return callback
Expand Down
6 changes: 3 additions & 3 deletions aliceio/dispatcher/event/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ class CallableObject:
def __post_init__(self) -> None:
callback = inspect.unwrap(self.callback)
self.awaitable = inspect.isawaitable(callback) or inspect.iscoroutinefunction(
callback
callback,
)
spec = inspect.getfullargspec(callback)
self.params = {*spec.args, *spec.kwonlyargs}
Expand Down Expand Up @@ -71,7 +71,7 @@ def __post_init__(self) -> None:
stacklevel=6,
)

super(FilterObject, self).__post_init__()
super(FilterObject, self).__post_init__() # noqa: UP008

if isinstance(self.callback, Filter):
self.awaitable = True
Expand All @@ -83,7 +83,7 @@ class HandlerObject(CallableObject):
flags: Dict[str, Any] = field(default_factory=dict)

def __post_init__(self) -> None:
super(HandlerObject, self).__post_init__()
super(HandlerObject, self).__post_init__() # noqa: UP008
callback = inspect.unwrap(self.callback)
if inspect.isclass(callback) and issubclass(callback, BaseHandler):
self.awaitable = True
Expand Down
2 changes: 1 addition & 1 deletion aliceio/dispatcher/flags.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def __call__(
) -> Union[Callable[..., Any], "FlagDecorator"]:
if value and kwargs:
raise ValueError(
"The arguments `value` and **kwargs can not be used together"
"The arguments `value` and **kwargs can not be used together",
)

if value is not None and callable(value):
Expand Down
1 change: 0 additions & 1 deletion aliceio/dispatcher/middlewares/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,3 @@ async def __call__(
:param data: Данные контекста. Будет сопоставлен с аргументами обработчика.
:return: :class:`Any`
"""
pass
2 changes: 1 addition & 1 deletion aliceio/dispatcher/middlewares/error.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@


class ErrorsMiddleware(BaseMiddleware[Update]):
def __init__(self, router: Router):
def __init__(self, router: Router) -> None:
self.router = router

async def __call__(
Expand Down
15 changes: 9 additions & 6 deletions aliceio/dispatcher/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,16 @@ def __init__(self, *, name: Optional[str] = None) -> None:
self.purchase = AliceEventObserver(router=self, event_name=EventType.PURCHASE)
self.show_pull = AliceEventObserver(router=self, event_name=EventType.SHOW_PULL)
self.button_pressed = AliceEventObserver(
router=self, event_name=EventType.BUTTON_PRESSED
router=self,
event_name=EventType.BUTTON_PRESSED,
)
self.audio_player = AliceEventObserver(
router=self, event_name=EventType.AUDIO_PLAYER
router=self,
event_name=EventType.AUDIO_PLAYER,
)
self.errors = self.error = AliceEventObserver(
router=self, event_name=EventType.ERROR
router=self,
event_name=EventType.ERROR,
)
self.timeout = AliceEventObserver(router=self, event_name=EventType.TIMEOUT)

Expand Down Expand Up @@ -157,7 +160,7 @@ def parent_router(self, router: Router) -> None:
"""
if not isinstance(router, Router):
raise ValueError(
f"router should be instance of Router not {type(router).__name__!r}"
f"router should be instance of Router not {type(router).__name__!r}",
)
if self._parent_router:
raise RuntimeError(f"Router is already attached to {self._parent_router!r}")
Expand All @@ -172,7 +175,7 @@ def parent_router(self, router: Router) -> None:
parent = parent.parent_router

self._parent_router = router
router._sub_routers.append(self)
router._sub_routers.append(self) # noqa: SLF001

def include_routers(self, *routers: Router) -> None:
"""
Expand All @@ -195,7 +198,7 @@ def include_router(self, router: Router) -> Router:
if not isinstance(router, Router):
raise ValueError(
f"router should be instance of Router, "
f"not {type(router).__class__.__name__}"
f"not {type(router).__class__.__name__}",
)
router.parent_router = self
return router
Expand Down
8 changes: 3 additions & 5 deletions aliceio/filters/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from aliceio.filters.logic import _InvertFilter


class Filter(ABC):
class Filter(ABC): # noqa: B024
"""
Если вы хотите сделать собственные фильтры, такие же как встроенные фильтры,
вам нужно будет написать подкласс с переопределением метода :code:`__call__`
Expand All @@ -29,21 +29,19 @@ async def __call__(
:return: :class:`bool` или :class:`Dict[str, Any]`
"""
pass

def __invert__(self) -> "_InvertFilter":
from aliceio.filters.logic import invert_f

return invert_f(self)

def update_handler_flags(self, flags: Dict[str, Any]) -> None:
def update_handler_flags(self, flags: Dict[str, Any]) -> None: # noqa: B027
"""
Также, если вы хотите расширить флаги обработчика с помощью этого фильтра,
вам следует реализовать этот метод
:param flags: Существующие флаги, могут быть обновлены напрямую.
"""
pass

def _signature_to_string(self, *args: Any, **kwargs: Any) -> str:
"""
Expand All @@ -57,6 +55,6 @@ def _signature_to_string(self, *args: Any, **kwargs: Any) -> str:

return f"{type(self).__name__}({', '.join(items)})"

def __await__(self): # type: ignore # pragma: no cover
def __await__(self): # type: ignore # pragma: no cover # noqa: ANN204
# Этот метод нужен только для проверки, никогда не вызывается
return self.__call__
2 changes: 1 addition & 1 deletion aliceio/filters/exception.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ class ExceptionTypeFilter(Filter):

__slots__ = ("exceptions",)

def __init__(self, *exceptions: Type[Exception]):
def __init__(self, *exceptions: Type[Exception]) -> None:
"""
:param exceptions: Типы исключений, на которые должен реагировать фильтр.
"""
Expand Down
Loading

0 comments on commit 5c4dad9

Please sign in to comment.