Search code examples
pythonsqlalchemytornado

SQLAlchemy query not consistent between multi Tornado instances


I start 2 tornado instances, eg. tornado-8000 and tornado-8001, using nginx upstream.

When I insert data at one instance, query on another instance cannot find this data.

The SQLAlchemy query is as following:

topics = self.db.query(Topic).order_by(Topic.updated_at.desc()).limit(20)

And my SQLAlchemy is initialized as following:

class Application(tornado.web.Application):
    def __init__(self):
        # setup app
        from urls import handlers,ui_modules
        settings = dict(
            debug = options.debug,
            static_path = os.path.join(root_dir, "static"),
            xsrf_cookies = True,
            cookie_secret = "nzjxcjasduuqwheazmu293nsadhaslzkci9023nsadnua9sdads/Vo=",
            ui_modules = ui_modules,
        )
        tornado.web.Application.__init__(self, handlers, **settings)

        self.db = scoped_session(sessionmaker(bind=engine,autocommit=False,autoflush=False))

BaseHandler:

class BaseHandler(web.RequestHandler):
    @property
    def db(self):
        return self.application.db

My insert:

topic = Topic()
topic.title = u'abcdefg'
self.db.add(topic)
self.db.commit()

Where is the error?


Solution

  • Thanks to @van. Solved. I override on_finish method of tornado.web.RequestHandler and added session.remove().