Major refactor of the code

A lot of function are now using classes instead of parameters or tuples
isort was added to the dev requirements
Comments were adjusted
This commit is contained in:
2022-12-25 18:01:12 +03:00
parent bbc9650357
commit 3f744723a9
12 changed files with 195 additions and 186 deletions

View File

@ -1,37 +1,50 @@
import io
from typing import Iterator, Self, Type
from typing import Iterable, Self
import pydantic
from .classes import DecryptedAccount
class _Account(pydantic.BaseModel):
name: str
login: str
password: str
@classmethod
def from_tuple(cls: Type[Self], tuple_: tuple[str, str, str]) -> Self:
return cls(name=tuple_[0], login=tuple_[1], password=tuple_[2])
def to_usual_account(self, user_id: int) -> DecryptedAccount:
return DecryptedAccount(
user_id=user_id,
name=self.name,
login=self.login,
password=self.password,
)
def as_tuple(self: Self) -> tuple[str, str, str]:
return (self.name, self.login, self.password)
@classmethod
def from_usual_account(cls, account: DecryptedAccount) -> Self:
return cls(
name=account.name,
login=account.login,
password=account.password,
)
class _Accounts(pydantic.BaseModel):
accounts: list[_Account] = pydantic.Field(default_factory=list)
def _accounts_list_to_json(accounts: Iterator[tuple[str, str, str]]) -> str:
accounts = _Accounts(accounts=[_Account.from_tuple(i) for i in accounts])
return accounts.json(ensure_ascii=False)
def _accounts_list_to_json(accounts: Iterable[DecryptedAccount]) -> str:
result = _Accounts(
accounts=[_Account.from_usual_account(i) for i in accounts],
).json(ensure_ascii=False)
return result
def json_to_accounts(json_: str) -> list[tuple[str, str, str]]:
def json_to_accounts(json_: str, user_id: int) -> list[DecryptedAccount]:
accounts = _Accounts.parse_raw(json_)
return [i.as_tuple() for i in accounts.accounts]
return [account.to_usual_account(user_id) for account in accounts.accounts]
def accounts_to_json(accounts: Iterator[tuple[str, str, str]]) -> io.StringIO:
def accounts_to_json(accounts: Iterable[DecryptedAccount]) -> io.StringIO:
file = io.StringIO(_accounts_list_to_json(accounts))
file.name = "passwords.json"
return file