Expression Serializer Extension

Serializer/Deserializer objects for usage with SQLAlchemy query structures,allowing “contextual” deserialization.

Any SQLAlchemy query structure, either based on sqlalchemy.sql.or sqlalchemy.orm. can be used. The mappers, Tables, Columns, Sessionetc. which are referenced by the structure are not persisted in serializedform, but are instead re-associated with the query structurewhen it is deserialized.

Usage is nearly the same as that of the standard Python pickle module:

  1. from sqlalchemy.ext.serializer import loads, dumps
  2. metadata = MetaData(bind=some_engine)
  3. Session = scoped_session(sessionmaker())
  4.  
  5. # ... define mappers
  6.  
  7. query = Session.query(MyClass).
  8. filter(MyClass.somedata=='foo').order_by(MyClass.sortkey)
  9.  
  10. # pickle the query
  11. serialized = dumps(query)
  12.  
  13. # unpickle. Pass in metadata + scoped_session
  14. query2 = loads(serialized, metadata, Session)
  15.  
  16. print query2.all()

Similar restrictions as when using raw pickle apply; mapped classes must bethemselves be pickleable, meaning they are importable from a module-levelnamespace.

The serializer module is only appropriate for query structures. It is notneeded for:

  • instances of user-defined classes. These contain no references to engines,sessions or expression constructs in the typical case and can be serializeddirectly.

  • Table metadata that is to be loaded entirely from the serialized structure(i.e. is not already declared in the application). Regularpickle.loads()/dumps() can be used to fully dump any MetaData object,typically one which was reflected from an existing database at some previouspoint in time. The serializer module is specifically for the opposite case,where the Table metadata is already present in memory.

  • sqlalchemy.ext.serializer.Serializer(*args, **kw)

  • sqlalchemy.ext.serializer.Deserializer(file, metadata=None, scoped_session=None, engine=None)
  • sqlalchemy.ext.serializer.dumps(obj, protocol=4)
  • sqlalchemy.ext.serializer.loads(data, metadata=None, scoped_session=None, engine=None)