簡單的一個MySQL類的實現:

來源:互聯網
上載者:User

標籤:屬性   分享圖片   mys   setting   erro   存在   turn   random   open   

‘‘‘
定義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 timeimport hashlibimport osimport pickleimport randomimport settingsclass MySQL:    BASE_DIR = os.path.dirname(os.path.abspath(__file__))    def __init__(self,host,port):        self.host = host        self.port = port        #注意返回的是int型的,需要轉化為str類型        self.id = str(self.create_id())    def create_id(self):        return random.randint(1,5555)        #或者用下面的產生時間戳記的MD5編碼        # m = hashlib.md5(str(time.time()).encode(‘utf-8‘))        # return m.hexdigest()    def save(self):        file_name = os.path.join(self.BASE_DIR,‘DB_PATH‘,str(self.id))        #os.walk方法——files為檔案夾下的檔案名稱列表        for root,dirs,files in os.walk(os.path.join(self.BASE_DIR,‘DB_PATH‘)):            if self.id in files:                raise FileNotFoundError(‘檔案已存在!‘)        with open(file_name,‘wb‘) as f:            pickle.dump(self,f)            print(‘檔案已儲存‘.center(50, ‘*‘))    def get_obj_by_id(self,id):        file_name = os.path.join(self.BASE_DIR, ‘DB_PATH‘,str(id))        with open(file_name,‘rb‘) as f:            #pickle的load方法            data = pickle.load(f)            return  dataif __name__ == ‘__main__‘:    mysql = MySQL(settings.HOST,settings.PORT)    print(‘檔案初始化的資料‘.center(50, ‘*‘))    print(mysql.host)    print(mysql.port)    print(mysql.id)    mysql.save()    data = mysql.get_obj_by_id(mysql.id)    print(‘檔案中讀出來的資料‘.center(50,‘*‘))    print(data.host)    print(data.port)    print(data.id)

  結果:

簡單的一個MySQL類的實現:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.