这个例子说明了我在构建的应用程序中遇到的一个谜题。应用程序需要支持一个选项,允许用户在不实际提交数据库更改的情况下执行代码。但是,当我添加此选项时,即使没有调用commit()
方法,我也发现更改仍保留在数据库中。为什么此SQLAlchemy示例将更改提交给数据库?
我的具体问题可以在代码注释中找到。基本目标是更清楚地了解SQLAlchemy何时以及为什么要提交给数据库。
我的更广泛的问题是,我的应用程序应该(a)使用全局的Session
实例,还是(b)使用全局的Session
类,从中实例化特定实例。基于这个例子,我开始认为正确答案是(b)。是对的吗? 编辑:this SQLAlchemy documentation表明推荐(b)。
import sys
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key = True)
name = Column(String)
age = Column(Integer)
def __init__(self, name, age = 0):
self.name = name
self.age = 0
def __repr__(self):
return "<User(name='{0}', age={1})>".format(self.name, self.age)
engine = create_engine('sqlite://', echo = False)
Base.metadata.create_all(engine)
Session = sessionmaker()
Session.configure(bind=engine)
global_session = Session() # A global Session instance.
commit_ages = False # Whether to commit in modify_ages().
use_global = True # If True, modify_ages() will commit, regardless
# of the value of commit_ages. Why?
def get_session():
return global_session if use_global else Session()
def add_users(names):
s = get_session()
s.add_all(User(nm) for nm in names)
s.commit()
def list_users():
s = get_session()
for u in s.query(User): print ' ', u
def modify_ages():
s = get_session()
n = 0
for u in s.query(User):
n += 10
u.age = n
if commit_ages: s.commit()
add_users(('A', 'B', 'C'))
print '\nBefore:'
list_users()
modify_ages()
print '\nAfter:'
list_users()
我试图回答您的具体问题,但是,是的,在参考你的**编辑:**,我肯定会去的(B)的路线。全局会话实例只是要求问题与此类似。 – snapshoe 2010-10-26 05:28:41