Serializing entity instances using pickle
Pony allows pickling entity instances, query results and collections. You might want to use it if you want to cache entity instances in an external cache (e.g. memcache). When Pony pickles entity instances, it saves all attributes except collections in order to avoid pickling a large set of data. If you need to pickle a collection attribute, you must pickle it separately. Example:
>>> from pony.orm.examples.estore import *
>>> products = select(p for p in Product if p.price > 100)[:]
>>> products
[Product[1], Product[2], Product[6]]
>>> import cPickle
>>> pickled_data = cPickle.dumps(products)
Now we can put the pickled data to a cache. Later, when we need our instances again, we can unpickle it:
>>> products = cPickle.loads(pickled_data)
>>> products
[Product[1], Product[2], Product[6]]
You can use pickling for storing objects in an external cache for improving application performance. When you unpickle objects, Pony adds them to the current db_session()
as if they were just loaded from the database. Pony doesn’t check if objects hold the same state in the database.