1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
|
Using :mod:`persistent` in your application
===========================================
Inheriting from :class:`persistent.Persistent`
----------------------------------------------
The basic mechanism for making your application's objects persistent
is mix-in interitance. Instances whose classes derive from
:class:`persistent.Persistent` are automatically capable of being
created as :term:`ghost` instances, being associated with a database
connection (called the :term:`jar`), and notifying the connection when
they have been changed.
Relationship to a Data Manager and its Cache
--------------------------------------------
Except immediately after their creation, persistent objects are normally
associated with a :term:`data manager` (also referred to as a :term:`jar`).
An object's data manager is stored in its ``_p_jar`` attribute.
The data manager is responsible for loading and saving the state of the
persistent object to some sort of backing store, including managing any
interactions with transaction machinery.
Each data manager maintains an :term:`object cache`, which keeps track of
the currently loaded objects, as well as any objects they reference which
have not yet been loaded: such an object is called a :term:`ghost`.
The cache is stored on the data manager in its ``_cache`` attribute.
A persistent object remains in the ghost state until the application
attempts to access or mutate one of its attributes: at that point, the
object requests that its data manager load its state. The persistent
object also notifies the cache that it has been loaded, as well as on
each subsequent attribute access. The cache keeps a "most-recently-used"
list of its objects, and removes objects in least-recently-used order
when it is asked to reduce its working set.
The examples below use a stub data manager class, and its stub cache class:
.. doctest::
>>> class Cache(object):
... def __init__(self):
... self._mru = []
... def mru(self, oid):
... self._mru.append(oid)
>>> from zope.interface import implements
>>> from persistent.interfaces import IPersistentDataManager
>>> class DM(object):
... implements(IPersistentDataManager)
... def __init__(self):
... self._cache = Cache()
... self.registered = 0
... def register(self, ob):
... self.registered += 1
... def setstate(self, ob):
... ob.__setstate__({'x': 42})
.. note::
Notic that the ``DM`` class always sets the ``x`` attribute to the value
``42`` when activating an object.
Persistent objects without a Data Manager
-----------------------------------------
Before aersistent instance has been associtated with a a data manager (
i.e., its ``_p_jar`` is still ``None``).
The examples below use a class, ``P``, defined as:
.. doctest::
>>> from persistent import Persistent
>>> from persistent.interfaces import GHOST, UPTODATE, CHANGED
>>> class P(Persistent):
... def __init__(self):
... self.x = 0
... def inc(self):
... self.x += 1
Instances of the derived ``P`` class which are not (yet) assigned to
a :term:`data manager` behave as other Python instances, except that
they have some extra attributes:
.. doctest::
>>> p = P()
>>> p.x
0
The :attr:`_p_changed` attribute is a three-state flag: it can be
one of ``None`` (the object is not loaded), ``False`` (the object has
not been changed since it was loaded) or ``True`` (the object has been
changed). Until the object is assigned a :term:`jar`, this attribute
will always be ``False``.
.. doctest::
>>> p._p_changed
False
The :attr:`_p_state` attribute is an integaer, representing which of the
"persistent lifecycle" states the object is in. Until the object is assigned
a :term:`jar`, this attribute will always be ``0`` (the ``UPTODATE``
constant):
.. doctest::
>>> p._p_state == UPTODATE
True
The :attr:`_p_jar` attribute is the object's :term:`data manager`. Since
it has not yet been assigned, its value is ``None``:
.. doctest::
>>> print p._p_jar
None
The :attr:`_p_oid` attribute is the :term:`object id`, a unique value
normally assigned by the object's :term:`data manager`. Since the object
has not yet been associated with its :term:`jar`, its value is ``None``:
.. doctest::
>>> print p._p_oid
None
Without a data manager, modifying a persistent object has no effect on
its ``_p_state`` or ``_p_changed``.
.. doctest::
>>> p.inc()
>>> p.inc()
>>> p.x
2
>>> p._p_changed
False
>>> p._p_state
0
Try all sorts of different ways to change the object's state:
.. doctest::
>>> p._p_deactivate()
>>> p._p_state
0
>>> p._p_changed
False
>>> p._p_changed = True
>>> p._p_changed
False
>>> p._p_state
0
>>> del p._p_changed
>>> p._p_changed
False
>>> p._p_state
0
>>> p.x
2
Associating an Object with a Data Manager
-----------------------------------------
Once associated with a data manager, a persistent object's behavior changes:
.. doctest::
>>> p = P()
>>> dm = DM()
>>> p._p_oid = "00000012"
>>> p._p_jar = dm
>>> p._p_changed
False
>>> p._p_state
0
>>> p.__dict__
{'x': 0}
>>> dm.registered
0
Modifying the object marks it as changed and registers it with the data
manager. Subsequent modifications don't have additional side-effects.
.. doctest::
>>> p.inc()
>>> p.x
1
>>> p.__dict__
{'x': 1}
>>> p._p_changed
True
>>> p._p_state
1
>>> dm.registered
1
>>> p.inc()
>>> p._p_changed
True
>>> p._p_state
1
>>> dm.registered
1
Object which register themselves with the data manager are candidates
for storage to the backing store at a later point in time.
Explicitly controlling ``_p_state``
-----------------------------------
Persistent objects expose three methods for moving an object into and out
of the "ghost" state:: :meth:`persistent.Persistent._p_activate`,
:meth:`persistent.Persistent._p_activate_p_deactivate`, and
:meth:`persistent.Persistent._p_invalidate`:
.. doctest::
>>> p = P()
>>> p._p_oid = '00000012'
>>> p._p_jar = DM()
After being assigned a jar, the object is initially in the ``UPTODATE``
state:
.. doctest::
>>> p._p_state
0
From that state, ``_p_deactivate`` rests the object to the ``GHOST`` state:
.. doctest::
>>> p._p_deactivate()
>>> p._p_state
-1
From the ``GHOST`` state, ``_p_activate`` reloads the object's data and
moves it to the ``UPTODATE`` state:
.. doctest::
>>> p._p_activate()
>>> p._p_state
0
>>> p.x
42
Changing the object puts it in the ``CHANGED`` state:
.. doctest::
>>> p.inc()
>>> p.x
43
>>> p._p_state
1
Attempting to deactivate in the ``CHANGED`` state is a no-op:
.. doctest::
>>> p._p_deactivate()
>>> p.__dict__
{'x': 43}
>>> p._p_changed
True
>>> p._p_state
1
``_p_invalidate`` forces objects into the ``GHOST`` state; it works even on
objects in the ``CHANGED`` state, which is the key difference between
deactivation and invalidation:
.. doctest::
>>> p._p_invalidate()
>>> p.__dict__
{}
>>> p._p_state
-1
You can manually reset the ``_p_changed`` field to ``False``: in this case,
the object changes to the ``UPTODATE`` state but retains its modifications:
.. doctest::
>>> p.inc()
>>> p.x
43
>>> p._p_changed = False
>>> p._p_state
0
>>> p._p_changed
False
>>> p.x
43
For an object in the "ghost" state, assigning ``True`` (or any value which is
coercible to ``True``) to its ``_p_changed`` attributes activates the object,
which is exactly the same as calling ``_p_activate``:
.. doctest::
>>> p._p_invalidate()
>>> p._p_state
-1
>>> p._p_changed = True
>>> p._p_changed
True
>>> p._p_state
1
>>> p.x
42
The pickling protocol
---------------------
Because persistent objects need to control how they are pickled and
unpickled, the :class:`persistent.Persistent` base class overrides
the implementations of ``__getstate__()`` and ``__setstate__()``:
.. doctest::
>>> p = P()
>>> dm = DM()
>>> p._p_oid = "00000012"
>>> p._p_jar = dm
>>> p.__getstate__()
{'x': 0}
>>> p._p_state
0
Calling ``__setstate__`` always leaves the object in the uptodate state.
.. doctest::
>>> p.__setstate__({'x': 5})
>>> p._p_state
0
A :term:`volatile attribute` is an attribute those whose name begins with a
special prefix (``_v__``). Unlike normal attributes, volatile attributes do
not get stored in the object's :term:`pickled data`.
.. doctest::
>>> p._v_foo = 2
>>> p.__getstate__()
{'x': 5}
Assigning to volatile attributes doesn't cause the object to be marked as
changed:
.. doctest::
>>> p._p_state
0
The ``_p_serial`` attribute is not affected by calling setstate.
.. doctest::
>>> p._p_serial = "00000012"
>>> p.__setstate__(p.__getstate__())
>>> p._p_serial
'00000012'
Estimated Object Size
---------------------
We can store a size estimation in ``_p_estimated_size``. Its default is 0.
The size estimation can be used by a cache associated with the data manager
to help in the implementation of its replacement strategy or its size bounds.
.. doctest::
>>> p._p_estimated_size
0
>>> p._p_estimated_size = 1000
>>> p._p_estimated_size
1024
Huh? Why is the estimated size coming out different than what we put
in? The reason is that the size isn't stored exactly. For backward
compatibility reasons, the size needs to fit in 24 bits, so,
internally, it is adjusted somewhat.
Of course, the estimated size must not be negative.
.. doctest::
>>> p._p_estimated_size = -1
Traceback (most recent call last):
....
ValueError: _p_estimated_size must not be negative
Overriding the attribute protocol
---------------------------------
Subclasses which override the attribute-management methods provided by
:class:`persistent.Persistent`, but must obey some constraints:
:meth:`__getattribute__``
When overriding ``__getattribute__``, the derived class implementation
**must** first call :meth:`persistent.Persistent._p_getattr`, passing the
name being accessed. This method ensures that the object is activated,
if needed, and handles the "special" attributes which do not require
activation (e.g., ``_p_oid``, ``__class__``, ``__dict__``, etc.)
If ``_p_getattr`` returns ``True``, the derived class implementation
**must** delegate to the base class implementation for the attribute.
:meth:`__setattr__`
When overriding ``__setattr__``, the derived class implementation
**must** first call :meth:`persistent.Persistent._p_setattr`, passing the
name being accessed and the value. This method ensures that the object is
activated, if needed, and handles the "special" attributes which do not
require activation (``_p_*``). If ``_p_setattr`` returns ``True``, the
derived implementation must assume that the attribute value has been set by
the base class.
:meth:`__detattr__`
When overriding ``__detattr__``, the derived class implementation
**must** first call :meth:`persistent.Persistent._p_detattr`, passing the
name being accessed. This method ensures that the object is
activated, if needed, and handles the "special" attributes which do not
require activation (``_p_*``). If ``_p_delattr`` returns ``True``, the
derived implementation must assume that the attribute has been deleted
base class.
:meth:`__getattr__`
For the `__getattr__` method, the behavior is like that for regular Python
classes and for earlier versions of ZODB 3.
|