pickle.py
来自「SQLAlchemy. 经典的Python ORM框架。学习必看。」· Python 代码 · 共 66 行
PY
66 行
"""illustrates a quick and dirty way to persist an XML document expressed using ElementTree and pickle.This is a trivial example using PickleType to marshal/unmarshal the ElementTree document into a binary column. Compare to explicit.py which stores the individual components of the ElementTreestructure in distinct rows using two additional mapped entities. Note that the usage of bothstyles of persistence are identical, as is the structure of the main Document class."""from sqlalchemy import *from sqlalchemy.orm import *import sys, osimport logginglogging.basicConfig()# uncomment to show SQL statements#logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)# uncomment to show SQL statements and result sets#logging.getLogger('sqlalchemy.engine').setLevel(logging.DEBUG)from elementtree import ElementTreeengine = create_engine('sqlite://')meta = MetaData(engine)# stores a top level record of an XML document. # the "element" column will store the ElementTree document as a BLOB.documents = Table('documents', meta, Column('document_id', Integer, primary_key=True), Column('filename', String(30), unique=True), Column('element', PickleType))meta.create_all()# our document class. contains a string name,# and the ElementTree root element. class Document(object): def __init__(self, name, element): self.filename = name self.element = element# setup mapper.mapper(Document, documents)###### time to test ! ########## get ElementTree documentfilename = os.path.join(os.path.dirname(sys.argv[0]), "test.xml")doc = ElementTree.parse(filename) # save to DBsession = create_session()session.save(Document("test.xml", doc))session.flush()# clear session (to illustrate a full load), restoresession.clear()document = session.query(Document).filter_by(filename="test.xml").first()# printdocument.element.write(sys.stdout)
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?