首页 > 数据库 > > Python 持久化管理之 Pickle/ZODB
In [3]: import cPickle as pickle In [4]: a1=['apple','banana','orange'] In [5]: b1={'one':1,'two':2,'three':3} In [6]: f=open('temp.pkl','wb') In [7]: pickle.dump(a1,f) In [8]: pickle.dump(b1,f) In [9]: f.close() In [10]: f2 = file('temp.pkl','rb') In [11]: recover1 = pickle.load(f2) In [12]: print recover1 ['apple', 'banana', 'orange'] In [13]: recover2 = pickle.load(f2) In [14]: print recover2 {'one': 1, 'three': 3, 'two': 2} In [15]: f2.close()
import persistent class OutOfFunds(Exception): pass class Account(persistent.Persistent): def __init__(self,name,start_balance=0): self.name = name self.balance = start_balance def __str__(self): return "Account: %s, balance: %s" %(self.name,self.balance) def __repr__(self): return "Account: %s, balance: %s" %(self.name,self.balance) def deposit(self,amount): """save amount into balance""" self.balance += amount def withdraw(self,amount): """withdraw from balance""" if amount > self.balance: raise OutOfFunds self.balance -= amount return self.balance
import ZODB import ZODB.FileStorage as ZFS import transaction import customer class ZODBUtils: conn = None filestorage = None def openConnection(self,file_name): self.filestorage = ZFS.FileStorage(file_name) db = ZODB.DB(self.filestorage) self.conn = db.open() return self.conn def closeConnection(self): self.conn.close() self.filestorage.close() def init_balance(): zodbutils = ZODBUtils() conn = zodbutils.openConnection('zodb_filestorage.db') root = conn.root() noah = customer.Account('noah',1000) print noah root['noah'] = noah jermy = customer.Account('jermy',2000) print jermy root['jermy'] = jermy transaction.commit() zodbutils.closeConnection() def app(): zodbutils = ZODBUtils() conn = zodbutils.openConnection('zodb_filestorage.db') root = conn.root() noah = root['noah'] print "Before Deposit Or Withdraw" print "=" * 30 print noah jermy = root['jermy'] print jermy print '-' * 30 transaction.begin() noah.deposit(300) jermy.withdraw(300) transaction.commit() print "After Deposit Or Withdraw" print "=" * 30 print noah print jermy print "-" * 30 zodbutils.closeConnection() if __name__ == '__main__': # init_balance() app()
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/26692020/viewspace-3142670/ ,如需转载,请注明出处,否则将追究法律责任。