The Pickle/zodb of Python persistence management

Source: Internet
Author: User
Tags object serialization serialization

1. Object Persistence

If you want to store Python objects transparently without losing information such as their identity and type, you need some form of object serialization:

It is a process of turning arbitrarily complex objects into text or binary representations of objects. Similarly, you must be able to restore an object to its original object in a serialized form.

In Python, this serialization process, called Pickle, can be used to pickle objects into strings, files on disk, or any file-like object, or you can unpickle those strings, files, or any file-like object into the original object.

2. Pickle Module

The pickle module is a module that implements this function, with the following code:

In [3]:ImportCpickle as Picklein [4]: a1=['Apple','Banana','Orange']in [5]: b1={' One': 1,' Both': 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 []: F2 = file ('TEMP.PKL','RB') in [ALL]: Recover1 =pickle.load (F2) in [12]:Printrecover1['Apple','Banana','Orange']in []: Recover2 =pickle.load (F2) in [14]:Printrecover2{' One': 1,'three': 3,' Both': 2}in [[]: F2.close ()

3. ZODB

Pickle modules can provide these benefits, but sometimes it may require more robust and scalable things than this simple pickle file.

For example, using only pickle does not solve the problem of naming and locating pickle files, nor does it support concurrent access to persistent objects. If you need these features, ask for a database similar to ZODB (Z object Database for Python).

ZODB (Zope object database) is a robust, multiuser, and object-oriented database system capable of storing and managing arbitrary complex Python objects and supporting transactional operations and concurrency control.

    • Zodb data storage form, is multi-select, can be normal file (filestorage), DB4 and Zeo connection

    • Python classes can become zodb by inheriting persistent.
    • Zodb is based on the "transaction"
    • The logical structure of ZODB is a network structure, and the most basic zodb is a tree rooted in root.

Here is a small example of a simulated bank deposit withdrawal using ZODB for storage

customer.py an account class that inherits persistent

ImportPersistentclassoutoffunds (Exception):PassclassAccount (persistent. Persistent):def __init__(self,name,start_balance=0): Self.name=name Self.balance=start_balancedef __str__(self):return "Account :%s, balance:%s"%(self.name,self.balance)def __repr__(self):return "Account :%s, balance:%s"%(self.name,self.balance)defDeposit (Self,amount):"""Save amount into balance"""self.balance+=AmountdefWithdraw (self,amount):"""Withdraw from Balance"""        ifAmount >self.balance:Raiseoutoffunds self.balance-=AmountreturnSelf.balance

Analog bank deposit and withdrawal zodb_customer_app.py

ImportZODBImportZODB. Filestorage as ZFSImportTransactionImportCustomerclassZodbutils:conn=None filestorage=NonedefOpenConnection (self,file_name): Self.filestorage=ZFS. Filestorage (file_name) DB=ZODB. DB (self.filestorage) Self.conn=Db.open ()returnSelf.conndefCloseConnection (self): Self.conn.close () self.filestorage.close ()definit_balance (): Zodbutils=zodbutils () conn= Zodbutils.openconnection ('zodb_filestorage.db') Root=Conn.root () Noah= Customer. Account ('Noah', 1000)    PrintNoah root['Noah'] =Noah Jermy= Customer. Account ('Jermy', 2000)    PrintJermy root['Jermy'] =jermy Transaction.commit () zodbutils.closeconnection ()defapp (): Zodbutils=zodbutils () conn= Zodbutils.openconnection ('zodb_filestorage.db') Root=Conn.root () Noah= root['Noah']    Print "before Deposit Or withdraw"    Print "="* 30PrintNoah Jermy= root['Jermy']    PrintJermyPrint '-'* 30Transaction.begin () noah.deposit (300) Jermy.withdraw (300) Transaction.commit ()Print "After Deposit Or withdraw"    Print "="* 30PrintNoahPrintJermyPrint "-"* 30zodbutils.closeconnection ()if __name__=='__main__':    #init_balance ()app ()

The results of the operation are as follows:

The Pickle/zodb of Python persistence management

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.