import json
from utils import log
def save(data, path):
"""
data 是 dict 或者 list
path 是保存文件的路径
"""
s = json.dumps(data, indent=2, ensure_ascii=False)
with open(path, 'w+', encoding='utf-8') as f:
# log('save', path, s, data)
f.write(s)
# 读取文件信息
def load(path):
with open(path, 'r', encoding='utf-8') as f:
s = f.read()
# log('load', s)
return json.loads(s)
class Model:
"""
数据存储的基类
"""
# 获取储存地址
@classmethod
def db_path(cls):
"""
那个类使用,获取那个类的类名,和保存文件一直
"""
classname = cls.__name__
path = 'data/{}.txt'.format(classname)
return path
@classmethod
def all(cls):
path = cls.db_path()
# 读取文件将字符串转换成python 对象
models = load(path)
# 参考django orm all方法
ms = [cls(m) for m in models]
return ms
@classmethod
def find_all(cls, **kwargs):
"""
类似 django fittler().all()
:param kwargs:
:return:
"""
ms = []
log('kwargs, ', kwargs, type(kwargs))
k, v ='',''
for key, value in kwargs.items():
k, v =key, value
all = cls.all()
# 得到所有的 对象
for m in all:
# 利用dict的魔方方法获取对应的k,v ,判断查询的对象是否存在
if v == m.__dict__[k]:
ms.append(m)
return ms
@classmethod
def find_by(cls, **kwargs):
"""
用法如下,kwargs 是只有一个元素的 dict
u = User.find_by(username='gua')
类似djangofirst 返回第一个值
"""
log('kwargs, ', kwargs, type(kwargs))
k, v = '', ''
for key, value in kwargs.items():
k, v = key, value
all = cls.all()
for m in all:
# 也可以用 getattr(m, k) 取值
if v == m.__dict__[k]:
return m
return None
@classmethod
def find(cls, id):
"""
只查询 id
:param id:
:return:
"""
return cls.find_by(id=id)
@classmethod
def delete(cls, id):
"""
删除 先找到全部,然后删除指定
"""
models = cls.all()
index = -1
for i,e in enumerate(models):
if e.id == id:
index = i
break
if index == -1:
# 没找到
pass
else:
models.pop(index)
# 根据init 来保存记录文件
l = [m.__dict__ for m in models]
path = cls.db_path()
save(l, path)
return
def __repr__(self):
"""
__repr__ 是一个魔法方法
简单来说, 它的作用是得到类的 字符串表达 形式
比如 print(u) 实际上是 print(u.__repr__())
"""
classname = self.__class__.__name__
properties = ['{}: ({})'.format(k, v) for k, v in self.__dict__.items()]
s = '\n'.join(properties)
return '< {}\n{} \n>\n'.format(classname, s)
def save(self):
"""
先读取所有内容,在吧要添加的内容添加进去
:return:
"""
models = self.all()
if self.id is None:
# 设置 self.id
# 先看看是否是空 list
if len(models) == 0:
# 我们让第一个元素的 id 为 1(当然也可以为 0)
self.id = 1
else:
m = models[-1]
# log('m', m)
self.id = m.id + 1
models.append(self)
else:
# 更改内容
# index = self.find(self.id)
index = -1
for i, m in enumerate(models):
if m.id == self.id:
index = i
break
log('debug', index)
models[index] = self
l = [m.__dict__ for m in models]
path = self.db_path()
save(l, path)
网友评论