定义MySQL类
1.对象有id、host、port三个属性
2.定义工具create_id,在实例化时为每个对象随机生成id,保证id唯一
3.提供两种实例化方式,方式一:用户传入host和port 方式二:从配置文件中读取host和port进行实例化
4.为对象定制方法,save和get_obj_by_id,save能自动将对象序列化到文件中,文件路径为配置文件中DB_PATH,文件名为id号,保存之前验证对象是否已经存在,若存在则抛出异常,;get_obj_by_id方法用来从文件中反序列化出对象
import uuid import settings import pickle import os class MySQL: def __init__(self,host,port): self.id=self.create_id() self.host=host self.port=port def save(self): if not self.is_exists: raise PermissionError('对象已存在') file_path=r'%s%s%s'%(settings.DB_PATH,os.sep,self.id)#os.sep是系统文件分隔符 pickle.dump(self,open(file_path,'wb')) @property def is_exists(self): tag=True files=os.listdir(settings.DB_PATH) for file in files: file_abspath=r'%s%s%s'%(settings.DB_PATH,os.sep,file) obj=pickle.load(open(file_abspath,'rb')) if self.host==obj.host and self.port==obj.port: tag=False break return tag @classmethod def from_from(cls): return cls(settings.HOST,settings.PORT) @staticmethod def get_by_obj_id(id): file_abspath=r'%s%s%s'%(settings.DB_PATH,os.sep,id) return pickle.load(open(file_abspath,'rb')) @staticmethod def create_id(): return str(uuid.uuid1()) m1=MySQL.from_from() print(m1.get_by_obj_id('fd60ddf0-b329-11e8-957e-68ecc543ecdf').host) m2=MySQL('172.16.97.3','8000') print(m2.get_by_obj_id('96874f68-b32a-11e8-b54f-68ecc543ecdf').host)
文本内容:settings.py
HOST='127.0.0.1' PORT=3306 DB_PATH=r'D:mypythonprojects基础练习db'