在以新的,打开,保存和关闭类型方式使用sqlite文件作为文档的应用程序中,配置引擎的适当方法是什么,以便我可以使用ORM?
from sqlalchemy.sql import *
from sqlalchemy import schema, create_engine, Table, Column, Integer, String
from sqlalchemy.orm import scoped_session, sessionmaker, mapper
class User(object):
def __init__(self, name=None, email=None):
self.name = name
self.email = email
def __repr__(self):
return '<User %r>' % (self.name)
class Document(object):
def __init__(self):
self.database = Database()
self.database.init_db()
def close(self):
self.database.session.remove()
class Database(object):
def __init__(self):
self.engine = create_engine('sqlite://', echo=False)
self.metadata = schema.MetaData()
self.session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=self.engine))
self.tables = {}
users = Table('users', self.metadata,
Column('id', Integer, primary_key=True),
Column('name', String(50), unique=True),
Column('email', String(120), unique=True)
)
self.tables['users'] = users
# mapper(User, users)
def init_db(self):
self.metadata.create_all(bind=self.engine)
document1 = Document()
document2 = Document()
document1.close()
document2.close()
我可以轻松使用常规的sql命令,例如
ins = database1.tables['users'].insert(
values = dict(name=u'Test User', email=u'user@localhost')
)
result = database1.session.execute(ins)
s = select([database1.tables['users']])
result = database1.session.execute(s)
for row in result:
print row
但我希望能够使用sqlalchemy的完整orm功能。我遇到的问题是,当创建一个文档时,会话被映射到User对象,阻止创建任何其他文档。
由于