serializer.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. # ext/serializer.py
  2. # Copyright (C) 2005-2017 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: http://www.opensource.org/licenses/mit-license.php
  7. """Serializer/Deserializer objects for usage with SQLAlchemy query structures,
  8. allowing "contextual" deserialization.
  9. Any SQLAlchemy query structure, either based on sqlalchemy.sql.*
  10. or sqlalchemy.orm.* can be used. The mappers, Tables, Columns, Session
  11. etc. which are referenced by the structure are not persisted in serialized
  12. form, but are instead re-associated with the query structure
  13. when it is deserialized.
  14. Usage is nearly the same as that of the standard Python pickle module::
  15. from sqlalchemy.ext.serializer import loads, dumps
  16. metadata = MetaData(bind=some_engine)
  17. Session = scoped_session(sessionmaker())
  18. # ... define mappers
  19. query = Session.query(MyClass).
  20. filter(MyClass.somedata=='foo').order_by(MyClass.sortkey)
  21. # pickle the query
  22. serialized = dumps(query)
  23. # unpickle. Pass in metadata + scoped_session
  24. query2 = loads(serialized, metadata, Session)
  25. print query2.all()
  26. Similar restrictions as when using raw pickle apply; mapped classes must be
  27. themselves be pickleable, meaning they are importable from a module-level
  28. namespace.
  29. The serializer module is only appropriate for query structures. It is not
  30. needed for:
  31. * instances of user-defined classes. These contain no references to engines,
  32. sessions or expression constructs in the typical case and can be serialized
  33. directly.
  34. * Table metadata that is to be loaded entirely from the serialized structure
  35. (i.e. is not already declared in the application). Regular
  36. pickle.loads()/dumps() can be used to fully dump any ``MetaData`` object,
  37. typically one which was reflected from an existing database at some previous
  38. point in time. The serializer module is specifically for the opposite case,
  39. where the Table metadata is already present in memory.
  40. """
  41. from ..orm import class_mapper
  42. from ..orm.session import Session
  43. from ..orm.mapper import Mapper
  44. from ..orm.interfaces import MapperProperty
  45. from ..orm.attributes import QueryableAttribute
  46. from .. import Table, Column
  47. from ..engine import Engine
  48. from ..util import pickle, byte_buffer, b64encode, b64decode, text_type
  49. import re
  50. __all__ = ['Serializer', 'Deserializer', 'dumps', 'loads']
  51. def Serializer(*args, **kw):
  52. pickler = pickle.Pickler(*args, **kw)
  53. def persistent_id(obj):
  54. # print "serializing:", repr(obj)
  55. if isinstance(obj, QueryableAttribute):
  56. cls = obj.impl.class_
  57. key = obj.impl.key
  58. id = "attribute:" + key + ":" + b64encode(pickle.dumps(cls))
  59. elif isinstance(obj, Mapper) and not obj.non_primary:
  60. id = "mapper:" + b64encode(pickle.dumps(obj.class_))
  61. elif isinstance(obj, MapperProperty) and not obj.parent.non_primary:
  62. id = "mapperprop:" + b64encode(pickle.dumps(obj.parent.class_)) + \
  63. ":" + obj.key
  64. elif isinstance(obj, Table):
  65. id = "table:" + text_type(obj.key)
  66. elif isinstance(obj, Column) and isinstance(obj.table, Table):
  67. id = "column:" + \
  68. text_type(obj.table.key) + ":" + text_type(obj.key)
  69. elif isinstance(obj, Session):
  70. id = "session:"
  71. elif isinstance(obj, Engine):
  72. id = "engine:"
  73. else:
  74. return None
  75. return id
  76. pickler.persistent_id = persistent_id
  77. return pickler
  78. our_ids = re.compile(
  79. r'(mapperprop|mapper|table|column|session|attribute|engine):(.*)')
  80. def Deserializer(file, metadata=None, scoped_session=None, engine=None):
  81. unpickler = pickle.Unpickler(file)
  82. def get_engine():
  83. if engine:
  84. return engine
  85. elif scoped_session and scoped_session().bind:
  86. return scoped_session().bind
  87. elif metadata and metadata.bind:
  88. return metadata.bind
  89. else:
  90. return None
  91. def persistent_load(id):
  92. m = our_ids.match(text_type(id))
  93. if not m:
  94. return None
  95. else:
  96. type_, args = m.group(1, 2)
  97. if type_ == 'attribute':
  98. key, clsarg = args.split(":")
  99. cls = pickle.loads(b64decode(clsarg))
  100. return getattr(cls, key)
  101. elif type_ == "mapper":
  102. cls = pickle.loads(b64decode(args))
  103. return class_mapper(cls)
  104. elif type_ == "mapperprop":
  105. mapper, keyname = args.split(':')
  106. cls = pickle.loads(b64decode(mapper))
  107. return class_mapper(cls).attrs[keyname]
  108. elif type_ == "table":
  109. return metadata.tables[args]
  110. elif type_ == "column":
  111. table, colname = args.split(':')
  112. return metadata.tables[table].c[colname]
  113. elif type_ == "session":
  114. return scoped_session()
  115. elif type_ == "engine":
  116. return get_engine()
  117. else:
  118. raise Exception("Unknown token: %s" % type_)
  119. unpickler.persistent_load = persistent_load
  120. return unpickler
  121. def dumps(obj, protocol=0):
  122. buf = byte_buffer()
  123. pickler = Serializer(buf, protocol)
  124. pickler.dump(obj)
  125. return buf.getvalue()
  126. def loads(data, metadata=None, scoped_session=None, engine=None):
  127. buf = byte_buffer(data)
  128. unpickler = Deserializer(buf, metadata, scoped_session, engine)
  129. return unpickler.load()