ZODB

6.3 · active · verified Thu Apr 16

ZODB (Zope Object Database) is a Python native, object-oriented database designed for transparently and persistently storing Python objects without the need for object-relational mapping (ORM). It provides ACID transactions, multi-version concurrency control (MVCC), and a pluggable storage framework (e.g., FileStorage, ZEO for client-server, RelStorage for RDBMS backends). ZODB is actively maintained, with version 6.3 being the latest, and receives regular updates to support new Python versions and address bugs.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a basic ZODB `FileStorage`, store a `Persistent` object, modify it within a transaction, and then retrieve the persisted data. It highlights the use of `FileStorage`, `DB`, `Connection`, the `root` object (a dictionary-like container), and `transaction.manager` for managing commits and rollbacks. It also shows a common gotcha: marking mutable nested objects as changed.

import transaction
from ZODB.FileStorage import FileStorage
from ZODB.DB import DB
from persistent import Persistent

# Define a simple persistent class
class MyPersistentObject(Persistent):
    def __init__(self, value):
        self.value = value
        self.data = {}

# Create a FileStorage (e.g., 'mydata.fs')
# For in-memory, use `DB(None)`
storage = FileStorage('mydata.fs')
db = DB(storage)
connection = db.open()
root = connection.root()

# Perform a transaction
with transaction.manager:
    if 'my_app_root' not in root:
        root['my_app_root'] = MyPersistentObject('initial value')
        root['my_app_root'].data['first'] = 'Hello ZODB'

    # Modify an object
    app_root = root['my_app_root']
    app_root.value = 'updated value'
    app_root.data['second'] = 'Another entry'
    # Manually mark as changed for mutable nested objects like dicts/lists
    app_root.data._p_changed = True 
    print(f"Stored value: {app_root.value}")
    print(f"Stored data: {app_root.data}")
    # The 'with' statement automatically commits if no exception, aborts otherwise

# Re-open the database to verify persistence
db.close()
storage = FileStorage('mydata.fs') # Re-open storage
db = DB(storage)
connection = db.open()
root = connection.root()

app_root = root['my_app_root']
print(f"Retrieved value: {app_root.value}")
print(f"Retrieved data: {app_root.data}")

db.close()
storage.close()

view raw JSON →