Configure Deserializable object. (Set bot for types) and stop using __slots__

This commit is contained in:
Alex Root Junior 2017-05-26 05:17:26 +03:00
parent a703fc9587
commit 716865695c
21 changed files with 24 additions and 69 deletions

View file

@ -34,6 +34,10 @@ class AIOGramBot:
def _on_exit(self): def _on_exit(self):
self.session.close() self.session.close()
def prepare_object(self, obj):
obj.bot = self
return obj
@property @property
async def me(self) -> User: async def me(self) -> User:
if not hasattr(self, '_me'): if not hasattr(self, '_me'):
@ -45,12 +49,12 @@ class AIOGramBot:
async def get_me(self) -> User: async def get_me(self) -> User:
raw = await self.request(ApiMethods.GET_ME) raw = await self.request(ApiMethods.GET_ME)
return User.de_json(raw) return self.prepare_object(User.de_json(raw))
async def get_chat(self, chat_id) -> Chat: async def get_chat(self, chat_id) -> Chat:
payload = generate_payload(**locals()) payload = generate_payload(**locals())
raw = await self.request(ApiMethods.GET_CHAT, payload) raw = await self.request(ApiMethods.GET_CHAT, payload)
return Chat.de_json(raw) return self.prepare_object(Chat.de_json(raw))
async def get_updates(self, offset=None, limit=None, timeout=None, allowed_updates=None): async def get_updates(self, offset=None, limit=None, timeout=None, allowed_updates=None):
""" """
@ -64,4 +68,4 @@ class AIOGramBot:
""" """
payload = generate_payload(**locals()) payload = generate_payload(**locals())
raw = await self.request(ApiMethods.GET_UPDATES, payload) raw = await self.request(ApiMethods.GET_UPDATES, payload)
return [Update.de_json(raw_update) for raw_update in raw] return [self.prepare_object(Update.de_json(raw_update)) for raw_update in raw]

View file

@ -22,17 +22,29 @@ class Deserializable:
def to_json(self): def to_json(self):
result = {} result = {}
for item in self.__slots__ or list(self.__dict__.keys()): for name, attr in self.__dict__.items():
attr = getattr(self, item) if not attr or name == '_bot':
if not attr:
continue continue
if hasattr(attr, 'to_json'): if hasattr(attr, 'to_json'):
attr = getattr(attr, 'to_json')() attr = getattr(attr, 'to_json')()
elif isinstance(attr, datetime.datetime): elif isinstance(attr, datetime.datetime):
attr = int(time.mktime(attr.timetuple())) attr = int(time.mktime(attr.timetuple()))
result[item] = attr result[name] = attr
return result return result
@property
def bot(self):
if not hasattr(self, '_bot'):
raise AttributeError(f"{self.__class__.__name__} is not configured.")
return getattr(self, '_bot')
@bot.setter
def bot(self, bot):
setattr(self, '_bot', bot)
for name, attr in self.__dict__.items():
if isinstance(attr, Deserializable):
attr.bot = bot
@classmethod @classmethod
def de_json(cls, raw_data): def de_json(cls, raw_data):
""" """

View file

@ -2,8 +2,6 @@ from . import Deserializable
class Audio(Deserializable): class Audio(Deserializable):
__slots__ = ('file_id', 'duration', 'performer', 'title', 'mime_type', 'file_size')
def __init__(self, file_id, duration, performer, title, mime_type, file_size): def __init__(self, file_id, duration, performer, title, mime_type, file_size):
self.file_id = file_id self.file_id = file_id
self.duration = duration self.duration = duration

View file

@ -2,8 +2,6 @@ from . import Deserializable
class CallbackQuery(Deserializable): class CallbackQuery(Deserializable):
__slots__ = ('id', 'from_user', 'message', 'inline_message_id', 'chat_instance', 'data', 'game_short_name')
def __init__(self, id, from_user, message, inline_message_id, chat_instance, data, game_short_name): def __init__(self, id, from_user, message, inline_message_id, chat_instance, data, game_short_name):
self.data = data self.data = data
self.id = id self.id = id

View file

@ -2,8 +2,6 @@ from . import Deserializable
class Chat(Deserializable): class Chat(Deserializable):
__slots__ = ('id', 'type', 'title', 'username', 'first_name', 'last_name', 'all_members_are_administrators')
def __init__(self, id, type, title, username, first_name, last_name, all_members_are_administrators): def __init__(self, id, type, title, username, first_name, last_name, all_members_are_administrators):
self.id: int = id self.id: int = id
self.type: str = type self.type: str = type

View file

@ -2,8 +2,6 @@ from . import Deserializable
class ChatMember(Deserializable): class ChatMember(Deserializable):
__slots__ = ('user', 'status')
def __init__(self, user, status): def __init__(self, user, status):
self.user = user self.user = user
self.status = status self.status = status
@ -16,19 +14,3 @@ class ChatMember(Deserializable):
status = raw_data.get('status') status = raw_data.get('status')
return ChatMember(user, status) return ChatMember(user, status)
class ChatMemberStatus:
CREATOR = 'creator'
ADMINISTRATOR = 'administrator'
MEMBER = 'member'
LEFT = 'left'
KICKED = 'kicked'
@classmethod
def is_admin(cls, role):
return role in [cls.ADMINISTRATOR, cls.CREATOR]
@classmethod
def is_member(cls, role):
return role in [cls.MEMBER, cls.ADMINISTRATOR, cls.CREATOR]

View file

@ -2,8 +2,6 @@ from . import Deserializable
class Contact(Deserializable): class Contact(Deserializable):
__slots__ = ('phone_number', 'first_name', 'last_name', 'user_id')
def __init__(self, phone_number, first_name, last_name, user_id): def __init__(self, phone_number, first_name, last_name, user_id):
self.phone_number = phone_number self.phone_number = phone_number
self.first_name = first_name self.first_name = first_name

View file

@ -2,8 +2,6 @@ from . import Deserializable
class Document(Deserializable): class Document(Deserializable):
__slots__ = ('file_id', 'thumb', 'file_name', 'mime_type', 'file_size')
def __init__(self, file_id, thumb, file_name, mime_type, file_size): def __init__(self, file_id, thumb, file_name, mime_type, file_size):
self.file_id = file_id self.file_id = file_id
self.thumb = thumb self.thumb = thumb

View file

@ -2,8 +2,6 @@ from . import Deserializable
class File(Deserializable): class File(Deserializable):
__slots__ = ('file_id', 'file_size', 'file_path')
def __init__(self, file_id, file_size, file_path): def __init__(self, file_id, file_size, file_path):
self.file_id = file_id self.file_id = file_id
self.file_size = file_size self.file_size = file_size

View file

@ -2,9 +2,7 @@ from . import Deserializable
class Location(Deserializable): class Location(Deserializable):
__slots__ = ('longitude', 'latitude') def __init__(self, longitude, latitude):
def __init__(self, data, longitude, latitude):
self.longitude = longitude self.longitude = longitude
self.latitude = latitude self.latitude = latitude

View file

@ -7,14 +7,6 @@ from .user import User
class Message(Deserializable): class Message(Deserializable):
__slots__ = (
'message_id', 'from_user', 'date', 'chat', 'forward_from', 'forward_from_chat', 'forward_from_message_id',
'forward_date', 'reply_to_message', 'edit_date', 'text', 'entities', 'audio', 'document', 'game', 'photo',
'sticker', 'video', 'voice', 'video_note', 'new_chat_members', 'caption', 'contact', 'location', 'venue',
'new_chat_member', 'left_chat_member', 'new_chat_title', 'new_chat_photo', 'delete_chat_photo',
'group_chat_created', 'supergroup_chat_created', 'channel_chat_created', 'migrate_to_chat_id',
'migrate_from_chat_id', 'pinned_message', 'invoice', 'successful_payment', 'content_type')
def __init__(self, message_id, from_user, date, chat, forward_from, forward_from_chat, def __init__(self, message_id, from_user, date, chat, forward_from, forward_from_chat,
forward_from_message_id, forward_date, reply_to_message, edit_date, text, entities, audio, document, forward_from_message_id, forward_date, reply_to_message, edit_date, text, entities, audio, document,
game, photo, sticker, video, voice, video_note, new_chat_members, caption, contact, location, venue, game, photo, sticker, video, voice, video_note, new_chat_members, caption, contact, location, venue,

View file

@ -3,8 +3,6 @@ from .user import User
class MessageEntity(Deserializable): class MessageEntity(Deserializable):
__slots__ = ('type', 'offset', 'length', 'url', 'user')
def __init__(self, type, offset, length, url, user): def __init__(self, type, offset, length, url, user):
self.type = type self.type = type
self.offset = offset self.offset = offset

View file

@ -2,8 +2,6 @@ from . import Deserializable
class PhotoSize(Deserializable): class PhotoSize(Deserializable):
__slots__ = ('file_id', 'width', 'height', 'file_size')
def __init__(self, file_id, width, height, file_size): def __init__(self, file_id, width, height, file_size):
self.file_id = file_id self.file_id = file_id
self.width = width self.width = width

View file

@ -2,8 +2,6 @@ from . import Deserializable
class Sticker(Deserializable): class Sticker(Deserializable):
__slots__ = ('file_id', 'width', 'height', 'thumb', 'emoji', 'file_size')
def __init__(self, file_id, width, height, thumb, emoji, file_size): def __init__(self, file_id, width, height, thumb, emoji, file_size):
self.file_id = file_id self.file_id = file_id
self.width = width self.width = width

View file

@ -3,9 +3,6 @@ from .message import Message
class Update(Deserializable): class Update(Deserializable):
__slots__ = ('update_id', 'message', 'edited_message', 'channel_post', 'edited_channel_post', 'inline_query',
'chosen_inline_result', 'callback_query', 'shipping_query', 'pre_checkout_query')
def __init__(self, update_id, message, edited_message, channel_post, edited_channel_post, inline_query, def __init__(self, update_id, message, edited_message, channel_post, edited_channel_post, inline_query,
chosen_inline_result, callback_query, shipping_query, pre_checkout_query): chosen_inline_result, callback_query, shipping_query, pre_checkout_query):
self.update_id = update_id self.update_id = update_id

View file

@ -3,8 +3,6 @@ from ..utils.user_language import get_language
class User(Deserializable): class User(Deserializable):
__slots__ = ('id', 'first_name', 'last_name', 'username', 'language_code')
def __init__(self, id, first_name, last_name, username, language_code): def __init__(self, id, first_name, last_name, username, language_code):
self.id: int = id self.id: int = id
self.first_name: str = first_name self.first_name: str = first_name

View file

@ -2,8 +2,6 @@ from . import Deserializable
class UserProfilePhotos(Deserializable): class UserProfilePhotos(Deserializable):
__slots__ = ('total_count', 'photos')
def __init__(self, total_count, photos): def __init__(self, total_count, photos):
self.total_count = total_count self.total_count = total_count
self.photos = photos self.photos = photos

View file

@ -2,8 +2,6 @@ from . import Deserializable
class Venue(Deserializable): class Venue(Deserializable):
__slots__ = ('location', 'title', 'address', 'foursquare_id')
def __init__(self, location, title, address, foursquare_id): def __init__(self, location, title, address, foursquare_id):
self.location = location self.location = location
self.title = title self.title = title

View file

@ -2,8 +2,6 @@ from . import Deserializable
class Video(Deserializable): class Video(Deserializable):
__slots__ = ('file_id', 'width', 'height', 'duration', 'thumb', 'mime_type', 'file_size')
def __init__(self, file_id, width, height, duration, thumb, mime_type, file_size): def __init__(self, file_id, width, height, duration, thumb, mime_type, file_size):
self.file_id = file_id self.file_id = file_id
self.width = width self.width = width

View file

@ -2,8 +2,6 @@ from . import Deserializable
class VideoNote(Deserializable): class VideoNote(Deserializable):
__slots__ = ('file_id', 'length', 'duration', 'thumb', 'file_size')
def __init__(self, file_id, length, duration, thumb, file_size): def __init__(self, file_id, length, duration, thumb, file_size):
self.file_id = file_id self.file_id = file_id
self.length = length self.length = length

View file

@ -2,8 +2,6 @@ from . import Deserializable
class Voice(Deserializable): class Voice(Deserializable):
__slots__ = ('file_id', 'duration', 'mime_type', 'file_size')
def __init__(self, file_id, duration, mime_type, file_size): def __init__(self, file_id, duration, mime_type, file_size):
self.file_id = file_id self.file_id = file_id
self.duration = duration self.duration = duration