1. DirDBM: 基于目录的存储系统(DirDBM: Directory-based Storage)

1.1. dirdbm.DirDBM

twisted.persisted.dirdbm.DirDBM是一种类似于DBM的存储系统。它可以像Python里的字典(Dictionary)一样保存键-值映射。与字典不同的是,DirDBM的每一条映射都保存为一个单独的文件,而且键与值都要求是字符串。除此之外,DirDBM的行为与Python里的字典是基本一致的。

twisted.persisted.dirdbm.DirDBM is a DBM-like storage system. That is, it stores mappings between keys and values, like a Python dictionary, except that it stores the values in files in a directory - each entry is a different file. The keys must always be strings, as are the values. Other than that, DirDBM objects act just like Python dictionaries.


如果你想保存少量的数据,而且又不想用复杂的关系数据库系统或其它高深的数据库,那么,DirDBM非常的适合您。与Python自带的DBM模块不同的是,它小巧,易用,跨平台而且还不用任何外部的C库。

DirDBM is useful for cases when you want to store small amounts of data in an organized fashion, without having to deal with the complexity of a RDBMS or other sophisticated database. It is simple, easy to use, cross-platform, and doesn't require any external C libraries, unlike Python's built-in DBM modules.

   1 >>> from twisted.persisted import dirdbm
   2 >>> d = dirdbm.DirDBM("/tmp/dir")
   3 >>> d["librarian"] = "ook"
   4 >>> d["librarian"]
   5 'ook'
   6 >>> d.keys()
   7 ['librarian']
   8 >>> del d["librarian"]
   9 >>> d.items()
  10 []

1.2. dirdbm.Shelf

我们有时会想要保存一些比字符串更复杂的对象。稍微小心一点的话,dirdbm.Shelf可以保存这些更复杂的对象。Shelf和DirDBM的功能非常相似,而且Shelf的值(不是键)可以为任意对象,只要这个对象可以被保存。不过,一个对象在保存后被改变过的话,后来的改变不会被保存。如果改变了对象,你需要在改变后显式的再保存一次:

Sometimes it is neccessary to persist more complicated objects than strings. With some care, dirdbm.Shelf can transparently persist them. Shelf works exactly like DirDBM, except that the values (but not the keys) can be arbitrary picklable objects. However, notice that mutating an object after it has been stored in the Shelf has no effect on the Shelf. When mutating objects, it is neccessary to explictly store them back in the Shelf afterwards:

   1 >>> from twisted.persisted import dirdbm
   2 >>> d = dirdbm.Shelf("/tmp/dir2")
   3 >>> d["key"] = [1, 2]
   4 >>> d["key"]
   5 [1, 2]
   6 >>> l = d["key"]
   7 >>> l.append(3)
   8 >>> d["key"]
   9 [1, 2]
  10 >>> d["key"] = l
  11 >>> d["key"]
  12 [1, 2, 3]