examples/elementtree/pickle.py

20 months ago

author
zzzeek
date
Mon May 31 14:47:07 2010 -0400
changeset 6615
bb99158e5821
parent 5485
fc0a4d90d4da
child 6845
b0cef732d9cc
permissions
-rw-r--r--

0.6.1

     1 """illustrates a quick and dirty way to persist an XML document expressed using ElementTree and pickle.
     3 This is a trivial example using PickleType to marshal/unmarshal the ElementTree 
     4 document into a binary column.  Compare to explicit.py which stores the individual components of the ElementTree
     5 structure in distinct rows using two additional mapped entities.  Note that the usage of both
     6 styles of persistence are identical, as is the structure of the main Document class.
     7 """
     9 from sqlalchemy import (create_engine, MetaData, Table, Column, Integer, String,
    10     PickleType)
    11 from sqlalchemy.orm import mapper, create_session
    13 import sys, os
    15 from xml.etree import ElementTree
    17 engine = create_engine('sqlite://')
    18 meta = MetaData(engine)
    20 # setup a comparator for the PickleType since it's a mutable
    21 # element.
    22 def are_elements_equal(x, y):
    23     return x == y
    25 # stores a top level record of an XML document.  
    26 # the "element" column will store the ElementTree document as a BLOB.
    27 documents = Table('documents', meta,
    28     Column('document_id', Integer, primary_key=True),
    29     Column('filename', String(30), unique=True),
    30     Column('element', PickleType(comparator=are_elements_equal))
    31 )
    33 meta.create_all()
    35 # our document class.  contains a string name,
    36 # and the ElementTree root element.  
    37 class Document(object):
    38     def __init__(self, name, element):
    39         self.filename = name
    40         self.element = element
    42 # setup mapper.
    43 mapper(Document, documents)
    45 ###### time to test ! #########
    47 # get ElementTree document
    48 filename = os.path.join(os.path.dirname(__file__), "test.xml")
    49 doc = ElementTree.parse(filename)
    51 # save to DB
    52 session = create_session()
    53 session.add(Document("test.xml", doc))
    54 session.flush()
    56 # clear session (to illustrate a full load), restore
    57 session.expunge_all()
    58 document = session.query(Document).filter_by(filename="test.xml").first()
    60 # print
    61 document.element.write(sys.stdout)

mercurial