多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
>[success] # 数据处理模块model ~~~ 1.save --- 数据保存的方法 2.load --- 数据读取的方法 3.Model --- 数据存储的基类 活用__dict__方法 db_path --- 方法用来获取对应的子类名字数据保存的地址 all --- 方法参考django的all方法 find_all --- django fittler().all() find_by --- 类似djangofirst 返回第一个值 find --- 根据id查询 delete --- 删除 __repr__ --- 简单来说, 它的作用是得到类的 字符串表达 形式 save --- 用来保存数据 4.User --- 用来处理用户的类 salted_password --- 密码加盐的方法 ~~~ >[danger] ##### 代码 ~~~ 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) class User(Model): def __init__(self, form): self.id = form.get('id', None) self.username = form.get('username', '') self.password = form.get('password', '') # 加密 def salted_password(self, password, salt='$!@><?>HUI&DWQa`'): """$!@><?>HUI&DWQa`""" import hashlib def sha256(ascii_str): return hashlib.sha256(ascii_str.encode('ascii')).hexdigest() hash1 = sha256(password) hash2 = sha256(hash1 + salt) return hash2 def hashed_password(self, pwd): import hashlib # 用 ascii 编码转换成 bytes 对象 p = pwd.encode('ascii') s = hashlib.sha256(p) # 返回摘要字符串 return s.hexdigest() def validate_register(self): pwd = self.password self.password = self.salted_password(pwd) # 查找用户是否存在 if User.find_by(username=self.username) is None: self.save() return self else: return None def validate_login(self): u = User.find_by(username=self.username) if u is not None: return u.password == self.salted_password(self.password) else: return False ~~~