‘‘‘
Define the MySQL class:
1. Object has ID, host, port three properties
2. Define tool create_id, randomly generate ID for each object at instantiation, guarantee ID unique
3. Provide two kinds of instantiation mode, one: User incoming host and port mode two: Read host and port from configuration file to instantiate
4. To customize the method for the object, save and Get_obj_by_id,save can automatically serialize the object to a file, the file path is db_path in the configuration file, the file name is the ID number, before saving to verify whether the object already exists, if present throws an exception; Get_obj_by_ The ID method is used to deserialize the object from the file
‘‘‘
Code:
Import TimeImportHashlibImportOSImportPickleImportRandomImportSettingsclassMysql:base_dir= Os.path.dirname (Os.path.abspath (__file__)) def __init__(self,host,port): Self.host=host Self.port=Port#Note that the return is of type int and need to be converted to STR typeSelf.id =Str (self.create_id ())defcreate_id (self):returnRandom.randint (1,5555) #or use the following MD5 encoding to generate the timestamp #m = hashlib.md5 (str (time.time ()). Encode (' Utf-8 ')) #return m.hexdigest () defSave (self): file_name= Os.path.join (self. Base_dir,'Db_path', str (self.id))#Os.walk Method--files A list of file names under a folder forRoot,dirs,filesinchOs.walk (Os.path.join (self). Base_dir,'Db_path')): ifSelf.idinchFiles:RaiseFilenotfounderror ('file already exists! ') with open (file_name,'WB') as F:pickle.dump (self,f)Print('file is saved'. Center (50,'*')) defget_obj_by_id (self,id): file_name= Os.path.join (self. Base_dir,'Db_path', str (ID)) with open (file_name,'RB') as F:#the Load method of pickledata =pickle.load (f)returnDataif __name__=='__main__': MySQL=MySQL (settings. Host,settings. PORT)Print('data initialized by the file'. Center (50,'*')) Print(mysql.host)Print(Mysql.port)Print(mysql.id) mysql.save () data=mysql.get_obj_by_id (mysql.id)Print('the data read in the file'. Center (50,'*')) Print(data.host)Print(Data.port)Print(data.id)
Results:
The simple implementation of a MySQL class: