dbm --- Unix "数据库" 接口

源代码: Lib/dbm/__init__.py


dbm 是一个针对多种 DBM 数据库的泛用接口:

If none of these modules are installed, the slow-but-simple implementation in module dbm.dumb will be used. There is a third party interface to the Oracle Berkeley DB.

备注

None of the underlying modules will automatically shrink the disk space used by the database file. However, dbm.sqlite3, dbm.gnu and dbm.dumb provide a reorganize() method that can be used for this purpose.

exception dbm.error

一个元组,其中包含每个受支持的模块可引发的异常,另外还有一个名为 dbm.error 的特殊异常作为第一项 --- 后者最在引发 dbm.error 时被使用。

dbm.whichdb(filename)

此函数会尝试猜测几种简单数据库模块中哪一个是可用的 --- dbm.sqlite3, dbm.gnu, dbm.ndbmdbm.dumb --- 并应当被用来打开给定的文件。

返回下列值中的一个:

  • 如果文件因其不可读或不存在而无法打开则返回 None

  • 如果文件格式无法猜测则返回空字符串 ('')

  • 包含所需模块名称的字符串,如 'dbm.ndbm''dbm.gnu'

在 3.11 版本发生变更: filename 接受一个 path-like object

dbm.open(file, flag='r', mode=0o666)

打开一个数据库并返回相应的数据库对象。

参数:
  • file (path-like object) -- 要打开的数据库文件。 如果数据库文件已存在,则使用 whichdb() 来确定其类型和要使用的适当模块;如果文件不存在,则会使用上述可导入子模块中的第一个。

  • flag (str) --

    • 'r' (default): Open existing database for reading only.

    • 'w': Open existing database for reading and writing.

    • 'c': Open database for reading and writing, creating it if it doesn't exist.

    • 'n': Always create a new, empty database, open for reading and writing.

  • mode (int) -- The Unix file access mode of the file (default: octal 0o666), used only when the database has to be created.

在 3.11 版本发生变更: file 接受一个 path-like object

The object returned by open() supports the basic functionality of mutable mappings; keys and their corresponding values can be stored, retrieved, and deleted, and iteration, the in operator and methods keys(), get(), setdefault() and clear() are available. The keys() method returns a list instead of a view object. The setdefault() method requires two arguments.

键和值总是被存储为 bytes。 这意味着当使用字符串时它们会在被存储之前隐式地转换至默认编码格式。

这些对象也支持在 with 语句中使用,当语句结束时将自动关闭它们。

在 3.2 版本发生变更: 现在 get()setdefault() 方法对所有 dbm 后端均可用。

在 3.4 版本发生变更: open() 所返回的对象添加了对上下文管理协议的原生支持。

在 3.8 版本发生变更: 从只读数据库中删除键将引发数据库模块专属的异常而不是 KeyError

在 3.13 版本发生变更: clear() methods are now available for all dbm backends.

以下示例记录了一些主机名和对应的标题,随后将数据库的内容打印出来。:

import dbm

# 打开数据库,如有必要则创建它。
with dbm.open('cache', 'c') as db:

    # 记录一些值
    db[b'hello'] = b'there'
    db['www.python.org'] = 'Python Website'
    db['www.cnn.com'] = 'Cable News Network'

    # 请注意现在键被作为字节串。
    assert db[b'www.python.org'] == b'Python Website'
    # 可以看到值现在被作为字节串。
    assert db['www.cnn.com'] == b'Cable News Network'

    # 常用的字典接口方法同样可用。
    print(db.get('python.org', b'not present'))

    # 存储非字符串的键或值将引发异常
    # (通常为 TypeError)。
    db['www.yahoo.com'] = 4

# 当离开 with 语句时 db 将被自动关闭。

参见

模块 shelve

存储非字符串数据的持久化模块。

以下部分描述了各个单独的子模块。

dbm.sqlite3 --- 针对 dbm 的 SQLite 后端

Added in version 3.13.

源代码: Lib/dbm/sqlite3.py


此模块使用标准库 sqlite3 模块来提供针对 dbm 模块的 SQLite 后端。 这样由 dbm.sqlite3 创建的文件可通过 sqlite3,或任何其他 SQLite 浏览器,包括 SQLite CLI 打开。

Availability: not WASI.

此模块在 WebAssembly 平台上无效或不可用。 请参阅 WebAssembly 平台 了解详情。

dbm.sqlite3.open(filename, /, flag='r', mode=0o666)

Open an SQLite database.

参数:
  • filename (path-like object) -- 要打开的数据库的路径。

  • flag (str) --

    • 'r' (default): Open existing database for reading only.

    • 'w': Open existing database for reading and writing.

    • 'c': Open database for reading and writing, creating it if it doesn't exist.

    • 'n': Always create a new, empty database, open for reading and writing.

  • mode -- 文件的 Unix 文件访问模式 (默认值: 八进制数 0o666),仅在需要创建数据为时使用。

The returned database object behaves similar to a mutable mapping, but the keys() method returns a list, and the setdefault() method requires two arguments. It also supports a "closing" context manager via the with keyword.

The following methods are also provided:

sqlite3.close()

Close the SQLite database.

sqlite3.reorganize()

If you have carried out a lot of deletions and would like to shrink the space used on disk, this method will reorganize the database; otherwise, deleted file space will be kept and reused as new (key, value) pairs are added.

备注

While reorganizing, as much as two times the size of the original database is required in free disk space. However, be aware that this factor changes for each dbm submodule.

Added in version 3.15.0a0 (unreleased).

dbm.gnu --- GNU 数据库管理器

源代码: Lib/dbm/gnu.py


dbm.gnu 模块提供了针对 GDBM 库的接口,类似于 dbm.ndbm 模块,但带有额外的功能如对崩溃的容忍。

备注

dbm.gnudbm.ndbm 创建的文件格式是不兼容的因而无法互换使用。

Availability: not Android, not iOS, not WASI.

此模块在 移动平台WebAssembly 平台 上不受支持。

exception dbm.gnu.error

针对 dbm.gnu 专属错误例如 I/O 错误引发。 KeyError 的引发则针对一般映射错误例如指定了不正确的键。

dbm.gnu.open_flags

open()flag 形参所支持的字符组成的字符串。

dbm.gnu.open(filename, flag='r', mode=0o666, /)

打开 GDBM 数据库并返回一个 gdbm 对象。

参数:
  • filename (path-like object) -- 要打开的数据库文件。

  • flag (str) --

    • 'r' (default): Open existing database for reading only.

    • 'w': Open existing database for reading and writing.

    • 'c': Open database for reading and writing, creating it if it doesn't exist.

    • 'n': Always create a new, empty database, open for reading and writing.

    可以添加下列额外字符来控制数据库的打开方式:

    • 'f': 以快速模式打开数据库。 对数据库的写入将不是同步的。

    • 's': 同步模式。 对数据库的修改将立即写入到文件。

    • 'u': 不锁定数据库。

    • 'm': Do not use mmap(2). This may harm performance, but improve crash tolerance. .. versionadded:: next

    并非所有旗标都对所有 GDBM 版本可用。 请参阅 open_flags 成员获取受支持旗标字符的列表。

  • mode (int) -- The Unix file access mode of the file (default: octal 0o666), used only when the database has to be created.

抛出:

error -- 如果传入了不可用的 flag 参数。

在 3.11 版本发生变更: filename 接受一个 path-like object

gdbm objects behave similar to mutable mappings, but methods items(), values(), pop(), popitem(), and update() are not supported, the keys() method returns a list, and the setdefault() method requires two arguments. It also supports a "closing" context manager via the with keyword.

在 3.2 版本发生变更: Added the get() and setdefault() methods.

在 3.13 版本发生变更: Added the clear() method.

The following methods are also provided:

gdbm.close()

关闭 GDBM 数据库。

gdbm.firstkey()

可以使用此方法和 nextkey() 方法循环遍历数据库中的每个键。 遍历的顺序是按照 GDBM 的内部哈希值,而不会根据键的值排序。 此方法将返回起始的键。

gdbm.nextkey(key)

在遍历中返回 key 之后的的下一个键。 以下代码将打印数据库 db 中的每个键,而不会在内存中创建一个包含所有键的列表:

k = db.firstkey()
while k is not None:
    print(k)
    k = db.nextkey(k)
gdbm.reorganize()

如果你进行了大量删除操作并且想要缩减 GDBM 文件所使用的空间,此例程可将可重新组织数据库。 除非使用此重组功能否则 gdbm 对象不会缩减数据库文件大小;在其他情况下,被删除的文件空间将会保留并在添加新的 (键, 值) 对时被重用。

备注

While reorganizing, as much as one time the size of the original database is required in free disk space. However, be aware that this factor changes for each dbm submodule.

gdbm.sync()

当以快速模式打开数据库时,此方法会将任何未写入数据强制写入磁盘。

dbm.ndbm --- 新数据库管理器

源代码: Lib/dbm/ndbm.py


dbm.ndbm 模块提供了对 NDBM 库的接口。 此模块可与 "经典" NDBM 接口或 GDBM 兼容接口配合使用。

备注

dbm.gnudbm.ndbm 创建的文件格式是不兼容的因而无法互换使用。

警告

作为 macOS 的组成部分提供的 NDBM 库对值的大小有一个未写入文档的限制,当存储的值大于此限制时可能会导致数据库文件损坏。 读取这种已损坏的文件可能会导致硬崩溃(段错误)。

Availability: not Android, not iOS, not WASI.

此模块在 移动平台WebAssembly 平台 上不受支持。

exception dbm.ndbm.error

针对 dbm.ndbm 专属错误例如 I/O 错误引发。 KeyError 的引发则针对一般映射错误例如指定了不正确的键。

dbm.ndbm.library

所使用的 NDBM 实现库的名称。

dbm.ndbm.open(filename, flag='r', mode=0o666, /)

打开 NDBM 数据库并返回一个 ndbm 对象。

参数:
  • filename (path-like object) -- 数据库文件的基本名(不带 .dir.pag 扩展名)。

  • flag (str) --

    • 'r' (default): Open existing database for reading only.

    • 'w': Open existing database for reading and writing.

    • 'c': Open database for reading and writing, creating it if it doesn't exist.

    • 'n': Always create a new, empty database, open for reading and writing.

  • mode (int) -- The Unix file access mode of the file (default: octal 0o666), used only when the database has to be created.

在 3.11 版本发生变更: 接受 path-like object 作为文件名。

ndbm objects behave similar to mutable mappings, but methods items(), values(), pop(), popitem(), and update() are not supported, the keys() method returns a list, and the setdefault() method requires two arguments. It also supports a "closing" context manager via the with keyword.

在 3.2 版本发生变更: Added the get() and setdefault() methods.

在 3.13 版本发生变更: Added the clear() method.

The following method is also provided:

ndbm.close()

关闭 NDBM 数据库。

dbm.dumb --- 便携式 DBM 实现

源代码: Lib/dbm/dumb.py

备注

dbm.dumb 模块的目的是在更健壮的模块不可用时作为 dbm 模块的最终回退项。 dbm.dumb 不是为高速运行而编写的,也不像其他数据库模块一样被经常使用。


dbm.dumb 模块提供了一个完全以 Python 编写的持久化 dict 型接口。 不同于其他 dbm 后端,例如 dbm.gnu,它不需要外部库。

dbm.dumb 模块定义了以下对象:

exception dbm.dumb.error

针对 dbm.dumb 专属错误例如 I/O 错误引发。 KeyError 的引发则针对一般映射例如指定了不正确的键。

dbm.dumb.open(filename, flag='c', mode=0o666)

Open a dbm.dumb database.

参数:
  • filename -- 数据库文件的基本名(不带扩展名)。 新数据库将会创建以下文件: - filename.dat - filename.dir

  • flag (str) --

    • 'r': Open existing database for reading only.

    • 'w': Open existing database for reading and writing.

    • 'c' (default): Open database for reading and writing, creating it if it doesn't exist.

    • 'n': Always create a new, empty database, open for reading and writing.

  • mode (int) -- The Unix file access mode of the file (default: octal 0o666), used only when the database has to be created.

警告

当载入包含足够巨大/复杂条目的数据库时有可能导致 Python 解释器的崩溃,这是由于 Python AST 编译器有栈深度限制。

警告

dbm.dumb does not support concurrent read/write access. (Multiple simultaneous read accesses are safe.) When a program has the database open for writing, no other program should have it open for reading or writing.

在 3.5 版本发生变更: open()flag'n' 时将总是创建一个新数据库。

在 3.8 版本发生变更: 如果 flag'r' 则打开的数据库将为只读的。 如果 flag'r''w' 则当数据库不存在时不会自动创建它。

在 3.11 版本发生变更: filename 接受一个 path-like object

The returned database object behaves similar to a mutable mapping, but the keys() and items() methods return lists, and the setdefault() method requires two arguments. It also supports a "closing" context manager via the with keyword.

The following methods are also provided:

dumbdbm.close()

关闭数据库。

dumbdbm.reorganize()

If you have carried out a lot of deletions and would like to shrink the space used on disk, this method will reorganize the database; otherwise, deleted file space will not be reused.

备注

While reorganizing, no additional free disk space is required. However, be aware that this factor changes for each dbm submodule.

Added in version 3.15.0a0 (unreleased).

dumbdbm.sync()

同步磁盘上的目录和数据文件。 此方法将被 shelve.Shelf.sync() 方法调用。