【发布时间】:2015-06-21 05:07:31
【问题描述】:
我正在使用 Flask 和 SQLAlchemy 开发 API,这就是我想做的事情:
我有一个客户端应用程序,在多个平板电脑上工作,它必须发送多个请求才能将内容添加到服务器。 但我不想在每个 API 请求结束时使用自动回滚(flask-sqlalchemy 的默认行为),因为数据的发送是通过多个请求完成的,就像在这个非常简化的示例中一样:
1. beginTransaction/?id=transactionId -> 为发出该请求的客户端打开一个新会话。 SessionManager.new_session() 在下面的代码中。
2。 addObject/?id=objectAid -> 将对象添加到 PostGreSQL 数据库并刷新
3. addObject/?id=objectBid -> 将对象添加到 PostGreSQL 数据库并刷新
4. commitTransaction/?id= transactionId -> 提交自 beginTransaction 以来发生的事情。 SessionManager.commit() 在下面的代码中。
这里的重点是如果客户端应用程序在发送 «commitTransaction» 之前崩溃/失去连接,则不要将数据添加到服务器,从而防止服务器上的数据不完整。
由于我不想使用自动回滚,我不能真正使用 flask-SQLAlchemy,所以我自己在我的烧瓶应用程序中实现 SQLAlchemy,但我不确定如何使用会话。
这是我在 __ init __.py 中所做的实现:
db = create_engine('postgresql+psycopg2://admin:pwd@localhost/postgresqlddb',
pool_reset_on_return=False,
echo=True, pool_size=20, max_overflow=5)
Base = declarative_base()
metadata = Base.metadata
metadata.bind = db
# create a configured "Session" class
Session = scoped_session(sessionmaker(bind=db, autoflush=False))
class SessionManager(object):
currentSession = Session()
@staticmethod
def new_session():
#if a session is already opened by the client, close it
#create a new session
try:
SessionManager.currentSession.rollback()
SessionManager.currentSession.close()
except Exception, e:
print(e)
SessionManager.currentSession = Session()
return SessionManager.currentSession
@staticmethod
def flush():
try:
SessionManager.currentSession.flush()
return True
except Exception, e:
print(e)
SessionManager.currentSession.rollback()
return False
@staticmethod
def commit():
#commit and close the session
#create a new session in case the client makes a single request without using beginTransaction/
try:
SessionManager.currentSession.commit()
SessionManager.currentSession.close()
SessionManager.currentSession = Session()
return True
except Exception, e:
print(e)
SessionManager.currentSession.rollback()
SessionManager.currentSession.close()
SessionManager.currentSession = Session()
return False
但现在 API 在多个客户端发出请求时不起作用,似乎每个客户端都共享同一个会话。
我应该如何实现会话,以便每个客户端都有不同的会话并可以同时发出请求?
谢谢。
【问题讨论】:
-
@SeanVieira 根据this page,第 791 行,SQLALCHEMY_COMMIT_ON_TEARDOWN 默认已经是 False。这并不能解决使用 flask-sqlalchemy 在每个请求结束时进行回滚的问题。
标签: python postgresql session flask sqlalchemy