繁体   English   中英

使用sqlalchemy延迟更改

[英]Delayed change using sqlalchemy

我在多进程环境中面临着奇怪的行为。

我的第一个进程(后来称为P1)通过sqa写入db。 我的第二个进程(后来称为P2)通过sqa从db读取。 第二个过程是一个Web应用程序,该应用程序要求通过ajax调用获取最新数据。

当P1更新数据(写)时,P2不会立即看到更改(读)。 它必须先轮询几次,然后才能实际看到数据库更改(issuing session.query(...)) 如果我运行另一个P3进程,则可以看到实际上是在db中完成的更改,但是P2(Web应用程序)没有立即看到它。

我在Ubuntu 13.04上运行sqa 0.8.4 (underlying db: sqlite) ,并且我的Web应用程序基于cherrypy framework (3.2.0)

SQLAlchemy文档中所述,我使用作用域会话来获取线程安全的会话对象

这是我所有进程使用的OrmManager类:

class OrmManager:

    def  __init__(self, database, metadata, echo=False):
        self.database = database

        engine = create_engine('sqlite:///' + database,
                               echo=echo,
                               connect_args={'detect_types': sqlite3.PARSE_DECLTYPES|
                                              sqlite3.PARSE_COLNAMES},
                               native_datetime=True,
                               poolclass=NullPool,
                               convert_unicode=True
                           )

    metadata.create_all(engine)

    # this factory is thread safe: a session object is returned (always the same) to the
    # caller. If called from another thread, the returned session object will be different
    session_factory = sessionmaker(bind=engine, expire_on_commit=False)
    self.session = scoped_session(session_factory)

def get_session(self):

    session = self.session()
    return session

P1,P2和P3实现OrmManager并使用返回的会话,如下所示:

orm_mgr = OrmManager(database=<path/to/my/.sqlite/file>, metadata=METADATA)

session = orm_mgr.get_session()

# do some stuff here

session.commit()

我检查了P1代码。 数据库更改已(call to session.commit())但与P3 (cmd line process)相比, P2 (web app)无法实时看到更改。 P2可能需要几秒钟才能获得更改...

有任何想法吗 ?

非常感谢,

皮埃尔

找到了问题。 根据SQLAlchemy文档,必须在每个Web请求之后调用Session.remove()。

我将以下代码添加到我的cherrypy应用程序:

def on_end_request():
    """As mentioned in SQLAlchemy documentation,
    scoped_session .remove() method has to be called
    at the end of each request"""

    Session.remove()

和:

cherrypy.config.update({'tools.dbsession_close.on' : True})

# As mentioned in SQLAlchemy documentation, call the .remove() method
# of the scoped_session object at the end of each request
cherrypy.tools.dbsession_close = cherrypy.Tool('on_end_request', on_end_request)

现在工作正常。

还有其他人

皮埃尔

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM