mirror of
https://github.com/aiogram/aiogram.git
synced 2026-04-08 16:37:47 +00:00
add RequestMiddleware
This commit is contained in:
parent
79c59b34f9
commit
c7491efc67
2 changed files with 33 additions and 0 deletions
|
|
@ -22,6 +22,10 @@ class CancelHandler(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class SkipRequest(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
def _get_spec(func: callable):
|
def _get_spec(func: callable):
|
||||||
while hasattr(func, '__wrapped__'): # Try to resolve decorated callbacks
|
while hasattr(func, '__wrapped__'): # Try to resolve decorated callbacks
|
||||||
func = func.__wrapped__
|
func = func.__wrapped__
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,9 @@
|
||||||
import logging
|
import logging
|
||||||
import typing
|
import typing
|
||||||
|
from aiogram import Bot
|
||||||
|
from aiogram.types import base
|
||||||
|
from aiogram.utils.helper import HelperMode
|
||||||
|
from aiogram.dispatcher.handler import SkipRequest
|
||||||
|
|
||||||
log = logging.getLogger('aiogram.Middleware')
|
log = logging.getLogger('aiogram.Middleware')
|
||||||
|
|
||||||
|
|
@ -106,6 +110,31 @@ class BaseMiddleware:
|
||||||
await handler(*args)
|
await handler(*args)
|
||||||
|
|
||||||
|
|
||||||
|
class RequestMiddleware(BaseMiddleware):
|
||||||
|
bot: Bot
|
||||||
|
orig_request: typing.Callable
|
||||||
|
|
||||||
|
def setup(self, manager: MiddlewareManager):
|
||||||
|
self._manager = manager
|
||||||
|
self._configured = True
|
||||||
|
bot = manager.dispatcher.bot
|
||||||
|
self.orig_request = bot.request
|
||||||
|
bot.request = self.request
|
||||||
|
|
||||||
|
async def request(self, method: base.String,
|
||||||
|
data: typing.Optional[typing.Dict] = None,
|
||||||
|
files: typing.Optional[typing.Dict] = None, **kwargs
|
||||||
|
) -> typing.Union[typing.List, typing.Dict, base.Boolean]:
|
||||||
|
handler_name = f"on_{HelperMode.apply(method, HelperMode.snake_case)}"
|
||||||
|
handler = getattr(self, handler_name, None)
|
||||||
|
if handler:
|
||||||
|
try:
|
||||||
|
await handler(data, files, **kwargs)
|
||||||
|
except SkipRequest:
|
||||||
|
return {}
|
||||||
|
return await self.orig_request(method, data, files)
|
||||||
|
|
||||||
|
|
||||||
class LifetimeControllerMiddleware(BaseMiddleware):
|
class LifetimeControllerMiddleware(BaseMiddleware):
|
||||||
# TODO: Rename class
|
# TODO: Rename class
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue