Skip to content

Commit

Permalink
Move and upgrade TelegramBotContextMixin from serializers
Browse files Browse the repository at this point in the history
  • Loading branch information
EXG1O committed Oct 8, 2024
1 parent 24a8c49 commit 853ddef
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 19 deletions.
14 changes: 14 additions & 0 deletions telegram_bots/mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,17 @@ def get_serializer_context(self) -> dict[str, Any]:
context.update({'telegram_bot': self.telegram_bot})

return context


class TelegramBotContextMixin:
@cached_property
def telegram_bot(self) -> TelegramBot:
telegram_bot: Any = self.context.get('telegram_bot') # type: ignore [attr-defined]

if not isinstance(telegram_bot, TelegramBot):
raise TypeError(
'You not passed a TelegramBot instance as '
'telegram_bot to the serializer context.'
)

return telegram_bot
20 changes: 1 addition & 19 deletions telegram_bots/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from .base_models import AbstractCommandMedia
from .base_serializers import CommandMediaSerializer, DiagramSerializer
from .enums import ConnectionObjectType
from .mixins import TelegramBotContextMixin
from .models import (
BackgroundTask,
BackgroundTaskAPIRequest,
Expand All @@ -37,25 +38,6 @@
import os


class TelegramBotContextMixin:
_telegram_bot: TelegramBot | None = None

@property
def telegram_bot(self) -> TelegramBot:
if self._telegram_bot is None:
telegram_bot: Any = self.context.get('telegram_bot') # type: ignore [attr-defined]

if not isinstance(telegram_bot, TelegramBot):
raise TypeError(
'You not passed a TelegramBot instance as '
'telegram_bot to the serializer context.'
)

self._telegram_bot = telegram_bot

return self._telegram_bot


class TelegramBotSerializer(serializers.ModelSerializer[TelegramBot]):
class Meta:
model = TelegramBot
Expand Down

0 comments on commit 853ddef

Please sign in to comment.