make models
This commit is contained in:
8
database/bills.json
Normal file
8
database/bills.json
Normal file
@@ -0,0 +1,8 @@
|
||||
[
|
||||
{
|
||||
"id": 7356609804429
|
||||
},
|
||||
{
|
||||
"id": 7619314604429
|
||||
}
|
||||
]
|
||||
59
models.py
Normal file
59
models.py
Normal file
@@ -0,0 +1,59 @@
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
|
||||
class Model:
|
||||
drive: str = 'json'
|
||||
|
||||
attributes: dict[str, Any] = {}
|
||||
|
||||
def __init__(self, attributes: None | dict[str, Any] = None):
|
||||
if attributes is None:
|
||||
attributes = {}
|
||||
|
||||
for key, value in attributes.items():
|
||||
self.__setattr__(key, value)
|
||||
|
||||
@staticmethod
|
||||
def all() -> list['Model']:
|
||||
model = Model()
|
||||
|
||||
with open(f'database/{model.get_table()}.json', 'r', encoding='utf-8') as f:
|
||||
data = json.load(f)
|
||||
|
||||
return list(map(lambda attr: Model(attr), data))
|
||||
|
||||
|
||||
def save(self) -> bool:
|
||||
models = self.all()
|
||||
models.append(self)
|
||||
|
||||
data = list(map(lambda model: dict(model), models))
|
||||
with open(f'database/{self.get_table()}.json', 'w+', encoding='utf-8') as f:
|
||||
json.dump(data, f, ensure_ascii=False, indent=2)
|
||||
|
||||
return True
|
||||
|
||||
def get_table(self) -> str:
|
||||
return 'bills'
|
||||
|
||||
def __dict__(self):
|
||||
return self.attributes
|
||||
|
||||
def __getattr__(self, item):
|
||||
return self.attributes.get(item)
|
||||
|
||||
def __setattr__(self, key, value):
|
||||
self.attributes[key] = value
|
||||
|
||||
def __eq__(self, other):
|
||||
return self.attributes == other.attributes
|
||||
|
||||
|
||||
|
||||
class Bill(Model):
|
||||
...
|
||||
|
||||
bills = Bill.all()
|
||||
|
||||
print(Bill.all()[0].attributes)
|
||||
Reference in New Issue
Block a user