From d6ab1a7afc15b5cbcbd8163cf5acb274fd0893fc Mon Sep 17 00:00:00 2001 From: Nikita <43146729+gabbhack@users.noreply.github.com> Date: Sun, 31 Mar 2019 13:49:30 +0500 Subject: [PATCH] Update handler.py Now the func, specs and filters are put in the dataclass --- aiogram/dispatcher/handler.py | 30 +++++++++++++++++------------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/aiogram/dispatcher/handler.py b/aiogram/dispatcher/handler.py index 31aae135..073747c9 100644 --- a/aiogram/dispatcher/handler.py +++ b/aiogram/dispatcher/handler.py @@ -1,5 +1,6 @@ import inspect from contextvars import ContextVar +from dataclasses import dataclass ctx_data = ContextVar('ctx_handler_data') current_handler = ContextVar('current_handler') @@ -21,7 +22,7 @@ def _get_spec(func: callable): return spec, func -def _check_spec(spec, kwargs: dict): +def _check_spec(spec: inspect.FullArgSpec, kwargs: dict): if spec.varkw: return kwargs @@ -34,7 +35,6 @@ class Handler: self.once = once self.handlers = [] - self.specs = {} self.middleware_key = middleware_key def register(self, handler, filters=None, index=None): @@ -48,11 +48,10 @@ class Handler: :param index: you can reorder handlers """ spec, handler = _get_spec(handler) - self.specs[handler] = spec if filters and not isinstance(filters, (list, tuple, set)): filters = [filters] - record = (filters, handler) + record = Handler.HandlerObj(handler=handler, spec=spec, filters=filters) if index is None: self.handlers.append(record) else: @@ -65,11 +64,10 @@ class Handler: :param handler: callback :return: """ - for handler_with_filters in self.handlers: - _, registered = handler_with_filters + for handler_obj in self.handlers: + registered = handler_obj.handler if handler is registered: - self.specs.pop(handler, None) - self.handlers.remove(handler_with_filters) + self.handlers.remove(handler_obj) return True raise ValueError('This handler is not registered!') @@ -94,18 +92,18 @@ class Handler: return results try: - for filters, handler in self.handlers: + for handler_obj in self.handlers: try: - data.update(await check_filters(self.dispatcher, filters, args)) + data.update(await check_filters(self.dispatcher, handler_obj.filters, args)) except FilterNotPassed: continue else: - ctx_token = current_handler.set(handler) + ctx_token = current_handler.set(handler_obj.handler) try: if self.middleware_key: await self.dispatcher.middleware.trigger(f"process_{self.middleware_key}", args + (data,)) - partial_data = _check_spec(self.specs[handler], data) - response = await handler(*args, **partial_data) + partial_data = _check_spec(handler_obj.spec, data) + response = await handler_obj.handler(*args, **partial_data) if response is not None: results.append(response) if self.once: @@ -122,3 +120,9 @@ class Handler: args + (results, data,)) return results + + @dataclass + class HandlerObj: + handler: callable + spec: inspect.FullArgSpec + filters: list = None