我现在正在做的是在通过数据库连接(MySQL)运行反射之后对元数据进行腌制,一旦腌制可用,就使用腌制的元数据来反映模式,并将元数据绑定到 SQLite 引擎。
cachefile='orm.p'
dbfile='database'
engine_dev = create_engine(#db connect, echo=True)
engine_meta = create_engine('sqlite:///%s' % dbfile,echo=True)
Base = declarative_base()
Base.metadata.bind = engine_dev
metadata = MetaData(bind=engine_dev)
# load from pickle
try:
with open(cachefile, 'r') as cache:
metadata2 = pickle.load(cache)
metadata2.bind = engine_meta
cache.close()
class Users(Base):
__table__ = Table('users', metadata2, autoload=True)
print "ORM loaded from pickle"
# if no pickle, use reflect through database connection
except:
class Users(Base):
__table__ = Table('users', metadata, autoload=True)
print "ORM through database autoload"
# create metapickle
metadata.create_all()
with open(cachefile, 'w') as cache:
pickle.dump(metadata, cache)
cache.close()
如果这没问题(它有效)或有什么我可以改进的,有什么意见吗?