Created
April 21, 2021 09:46
-
-
Save dmig/f3d552c2f7062541679bcd2936b960b1 to your computer and use it in GitHub Desktop.
paged query model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import typing | |
from cryptography.fernet import Fernet | |
from pydantic import BaseModel | |
from lib.conf import config | |
fernet = Fernet(config.FEED_FERNET_KEY) | |
class BasePageQuery(BaseModel): | |
""" | |
This class generate **next_page** parameter for pagination. Encrypted | |
string contains all attributes described in child class. | |
Example: | |
>>> class MyPageQuery(BasePageQuery): | |
>>> filter_by: str = 'date' | |
>>> order: str = 'asc' | |
>>> | |
>>> query = MyPageQuery(filter_by='users', order='desc') | |
>>> | |
>>> encrypted_next_page = query.as_str | |
>>> assert MyPageQuery.from_str(encrypted_next_page) == query | |
>>> | |
>>> encrypted_next_page = str(query) | |
>>> assert MyPageQuery.from_str(encrypted_next_page) == query | |
""" | |
@classmethod | |
def from_str(cls, text: str) -> "BasePageQuery": | |
""" | |
Decrypt dictionary and return BasePageQuery from encrypted | |
json string | |
@param text: encrypted with Fernet text | |
@return: assembled NextPageObject | |
""" | |
data = fernet.decrypt(text.encode()) | |
return cls.parse_raw(data) | |
@property | |
def as_str(self) -> str: | |
""" | |
Dump BasePageQuery into encrypted with Fernet json representation | |
@return: encrypted text | |
""" | |
data = fernet.encrypt(self.json(exclude_unset=True).encode()) | |
return data.decode() | |
def __str__(self) -> str: | |
return self.as_str | |
class NextPageQueryStressTrend(BasePageQuery): | |
last_id: typing.Any = None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment