如何使用ZODB

如何使用ZODB

首先要下载安装python-zodb包,地址:http://packages.ubuntu.com/zh-cn/lucid/python-zodb

 

建立和断开与 ZODB 的连接

from ZODB import FileStorage, DB
import transaction

class MyZODB(object):

    def __init__(self, path):
        self.storage = FileStorage.FileStorage(path)
        self.db = DB(self.storage)
        self.connection = self.db.open()
        self.dbroot = self.connection.root()

    def close(self):
        self.connection.close()
        self.db.close()
        self.storage.close()

 

存储简单 Python 数据

from myzodb import MyZODB, transaction
db = MyZODB('./var/Data.fs')
dbroot = db.dbroot
dbroot['a_number'] = 3
dbroot['a_string'] = 'Gift'
dbroot['a_list'] = [1, 2, 3, 5, 7, 12]
dbroot['a_dictionary'] = { 1918: 'Red Sox', 1919: 'Reds' }
dbroot['deeply_nested'] = {
  1918: [ ('Red Sox', 4), ('Cubs', 2) ],
  1919: [ ('Reds', 5), ('White Sox', 3) ],
  }
transaction.commit()
db.close()

 

获取简单数据

from myzodb import MyZODB, transaction
db = MyZODB('./var/Data.fs')
dbroot = db.dbroot
for key in dbroot.keys():
  print key + ':', dbroot[key]
db.close()

 

使用 ZEO 提供远程访问

 

由于一次只有一个程序能够安全地打开“Data.fs”文件,ZEO 服务器是支持来自多个客户端的连接的唯一方法。

 

可通过与不同的zeo服务器通信来连接zodb,启动plone4时,启动了三个进程,其中一个就为zeoserver

from ZEO.ClientStorage import ClientStorage
from ZODB import DB

class MyRemoteZODB(object):
    def __init__(self, server, port):
        server_and_port = (server, port)
        self.storage = ClientStorage(server_and_port)
        self.db = DB(self.storage)
        self.connection = self.db.open()
        self.dbroot = self.connection.root()

    def close(self):
        self.connection.close()
        self.db.close()
        self.storage.close()

mydb = MyRemoteZODB('localhost', 8100) //端口号可从zeo配置文件中读出
dbroot = mydb.dbroot

for key in dbroot.keys():
  print key + ':', dbroot[key]
mydb.close()

 

 

详细参考: http://www.ibm.com/developerworks/cn/aix/library/au-zodb/

 

你可能感兴趣的:(DB)