StNicolay
3f744723a9
A lot of function are now using classes instead of parameters or tuples isort was added to the dev requirements Comments were adjusted
51 lines
1.3 KiB
Python
51 lines
1.3 KiB
Python
import io
|
|
from typing import Iterable, Self
|
|
|
|
import pydantic
|
|
|
|
from .classes import DecryptedAccount
|
|
|
|
|
|
class _Account(pydantic.BaseModel):
|
|
name: str
|
|
login: str
|
|
password: str
|
|
|
|
def to_usual_account(self, user_id: int) -> DecryptedAccount:
|
|
return DecryptedAccount(
|
|
user_id=user_id,
|
|
name=self.name,
|
|
login=self.login,
|
|
password=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: 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, user_id: int) -> list[DecryptedAccount]:
|
|
accounts = _Accounts.parse_raw(json_)
|
|
return [account.to_usual_account(user_id) for account in accounts.accounts]
|
|
|
|
|
|
def accounts_to_json(accounts: Iterable[DecryptedAccount]) -> io.StringIO:
|
|
file = io.StringIO(_accounts_list_to_json(accounts))
|
|
file.name = "passwords.json"
|
|
return file
|