Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Stateless dialogs#140

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Draft
Tishka17 wants to merge3 commits intodevelop
base:develop
Choose a base branch
Loading
fromfeature/stateless
Draft
Show file tree
Hide file tree
Changes from1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
PrevPrevious commit
NextNext commit
storage proxy factory
  • Loading branch information
@Tishka17
Tishka17 committedApr 24, 2022
commitac52bc3b9f6ec43e7a01b960a5c72b76672ceca6
44 changes: 17 additions & 27 deletionsaiogram_dialog/context/intent_filter.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
from logging import getLogger
from typing import Optional, Type, Dict, Union, Any
from typing import Optional, Type, Dict, Union, Any, Protocol

from aiogram.dispatcher.filters import BoundFilter
from aiogram.dispatcher.filters.state import StatesGroup
Expand All@@ -23,11 +23,15 @@
logger = getLogger(__name__)


class StorageProxyFactoryProtocol(Protocol):
def __call__(self, user_id: int, chat_id: int):
raise NotImplementedError


class IntentFilter(BoundFilter):
key = 'aiogd_intent_state_group'

def __init__(self,
aiogd_intent_state_group: Optional[Type[StatesGroup]] = None):
def __init__(self, aiogd_intent_state_group: Optional[Type[StatesGroup]] = None):
self.intent_state_group = aiogd_intent_state_group

async def check(self, obj: TelegramObject):
Expand All@@ -41,21 +45,16 @@ async def check(self, obj: TelegramObject):


class IntentMiddleware(BaseMiddleware):
def __init__(self, storage: BaseStorage,
state_groups: Dict[str, Type[StatesGroup]]):
def __init__(self, storage_proxy_factory: StorageProxyFactoryProtocol):
super().__init__()
self.storage = storage
self.state_groups = state_groups
self.storage_proxy_factory = storage_proxy_factory

async def on_pre_process_message(self,
event: Union[Message, ChatMemberUpdated],
data: dict):
chat = get_chat(event)
proxy = StorageProxy(
storage=self.storage,
user_id=event.from_user.id,
chat_id=chat.id,
state_groups=self.state_groups,
proxy = self.storage_proxy_factory(
user_id=event.from_user.id, chat_id=chat.id,
)
stack = await proxy.load_stack()
if stack.empty():
Expand All@@ -74,11 +73,8 @@ async def on_post_process_message(self, _, result, data: dict):
async def on_pre_process_aiogd_update(self, event: DialogUpdateEvent,
data: dict):
chat = get_chat(event)
proxy = StorageProxy(
storage=self.storage,
user_id=event.from_user.id,
chat_id=chat.id,
state_groups=self.state_groups,
proxy = self.storage_proxy_factory(
user_id=event.from_user.id, chat_id=chat.id,
)
data[STORAGE_KEY] = proxy
if event.intent_id is not None:
Expand DownExpand Up@@ -112,11 +108,8 @@ async def on_pre_process_aiogd_update(self, event: DialogUpdateEvent,
async def on_pre_process_callback_query(self, event: CallbackQuery,
data: dict):
chat = get_chat(event)
proxy = StorageProxy(
storage=self.storage,
user_id=event.from_user.id,
chat_id=chat.id,
state_groups=self.state_groups,
proxy = self.storage_proxy_factory(
user_id=event.from_user.id, chat_id=chat.id,
)
data[STORAGE_KEY] = proxy

Expand DownExpand Up@@ -162,11 +155,8 @@ async def on_pre_process_error(self, update: Update, error: Exception,

chat = get_chat(event)

proxy = StorageProxy(
storage=self.storage,
user_id=event.from_user.id,
chat_id=chat.id,
state_groups=self.state_groups,
proxy = self.storage_proxy_factory(
user_id=event.from_user.id, chat_id=chat.id,
)
data[STORAGE_KEY] = proxy

Expand Down
22 changes: 18 additions & 4 deletionsaiogram_dialog/context/stateless.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,16 @@
from typing import Dict, Type, Optional

from aiogram.dispatcher.filters.state import State, StatesGroup
from aiogram.dispatcher.storage import BaseStorage

from .context import Context
from .stack import Stack, DEFAULT_STACK_ID
from ..exceptions import UnknownState


classFakeStorageProxy:
def __init__(self, storage: BaseStorage,
classStatelessStorageProxy:
def __init__(self,
user_id: int, chat_id: int,
state_groups: Dict[str, Type[StatesGroup]]):
self.storage = storage
self.state_groups = state_groups
self.user_id = user_id
self.chat_id = chat_id
Expand DownExpand Up@@ -54,3 +52,19 @@ def _state(self, state: str) -> State:
if real_state.state == state:
return real_state
raise UnknownState(f"Unknown state {state}")


class StatelessStorageProxyFactory:
def __init__(self, state_groups: Dict[str, Type[StatesGroup]]):
self.state_groups = state_groups

def __call__(
self,
user_id: int, chat_id: int,
state_groups: Dict[str, Type[StatesGroup]]
):
return StatelessStorageProxy(
user_id=user_id,
chat_id=chat_id,
state_groups=self.state_groups,
)
30 changes: 26 additions & 4 deletionsaiogram_dialog/context/storage.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,7 +11,6 @@
from .stack import Stack, DEFAULT_STACK_ID
from ..exceptions import UnknownState, UnknownIntent


ID_SYMS = string.digits + string.ascii_letters


Expand DownExpand Up@@ -55,7 +54,8 @@ async def load_context(self, intent_id: str) -> Context:
user=self._context_key(intent_id)
)
if not data:
raise UnknownIntent(f"Context not found for intent id: {intent_id}")
raise UnknownIntent(
f"Context not found for intent id: {intent_id}")
data["state"] = self._state(data["state"])
return Context(**data)

Expand All@@ -80,10 +80,12 @@ async def save_context(self, context: Optional[Context]) -> None:
)

async def remove_context(self, intent_id: str):
await self.storage.reset_data(chat=self.chat_id, user=self._context_key(intent_id))
await self.storage.reset_data(chat=self.chat_id,
user=self._context_key(intent_id))

async def remove_stack(self, stack_id: str):
await self.storage.reset_data(chat=self.chat_id, user=self._stack_key(stack_id))
await self.storage.reset_data(chat=self.chat_id,
user=self._stack_key(stack_id))

async def save_stack(self, stack: Optional[Stack]) -> None:
if not stack:
Expand DownExpand Up@@ -113,3 +115,23 @@ def _state(self, state: str) -> State:
if real_state.state == state:
return real_state
raise UnknownState(f"Unknown state {state}")


class StorageProxyFactory:
def __init__(self,
storage: BaseStorage,
state_groups: Dict[str, Type[StatesGroup]]):
self.storage = storage
self.state_groups = state_groups

def __call__(
self,
user_id: int, chat_id: int,
state_groups: Dict[str, Type[StatesGroup]]
):
return StorageProxy(
storage=self.storage,
user_id=user_id,
chat_id=chat_id,
state_groups=self.state_groups,
)
14 changes: 10 additions & 4 deletionsaiogram_dialog/manager/registry.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,8 +14,10 @@
)
from .update_handler import handle_update
from ..context.events import DialogUpdateEvent, StartMode
from ..context.intent_filter import IntentFilter, IntentMiddleware
from ..context.intent_filter import IntentFilter, IntentMiddleware, \
StorageProxyFactoryProtocol
from ..context.media_storage import MediaIdStorage
from ..context.storage import StorageProxyFactory
from ..exceptions import UnregisteredDialogError


Expand All@@ -25,6 +27,7 @@ def __init__(
dp: Dispatcher,
dialogs: Sequence[ManagedDialogProto] = (),
media_id_storage: Optional[MediaIdStorageProtocol] = None,
storage_proxy_factory: Optional[StorageProxyFactoryProtocol] = None,
):
self.dp = dp
self.dialogs = {
Expand All@@ -33,6 +36,11 @@ def __init__(
self.state_groups: Dict[str, Type[StatesGroup]] = {
d.states_group_name(): d.states_group() for d in dialogs
}
if storage_proxy_factory is None:
storage_proxy_factory = StorageProxyFactory(
storage=dp.storage, state_groups=self.state_groups
)
self.storage_proxy_factory = storage_proxy_factory
self.update_handler = Handler(dp, middleware_key="aiogd_update")
self.register_update_handler(handle_update, state="*")
self.dp.filters_factory.bind(IntentFilter)
Expand DownExpand Up@@ -68,9 +76,7 @@ def _register_middleware(self):
self.dp.setup_middleware(
ManagerMiddleware(self)
)
self.dp.setup_middleware(
IntentMiddleware(storage=self.dp.storage, state_groups=self.state_groups)
)
self.dp.setup_middleware(IntentMiddleware(self.storage_proxy_factory))

def find_dialog(self, state: State) -> ManagedDialogProto:
try:
Expand Down

[8]ページ先頭

©2009-2025 Movatter.jp