Search code examples
pythonnginxflasksqlalchemyuwsgi

Sqlalchemy returns different results of the SELECT command (query.all)


I have web server (512 RAM) with: FLASK + SQLAlchemy (SQLite) -> uWSGI -> Nginx

PROBLEM: Sqlalchemy returns different results of the SELECT command (query.all).

Example:

  • Added a few records in the database.
  • I reload the page: new records have not returned (but old returned).
  • Reload the page: all the records returned. Excellent.
  • Reload the page: again new records have not returned. (But old returned).

This happens as long as I do not restart Flask app.

The code below:

DECLARATIVE_BASE = declarative_base()
engine = create_engine('sqlite:///database.db')
Session = sessionmaker(bind=engine)
session = Session()

class Order(DECLARATIVE_BASE):
    __tablename__ = 'orders'
    __table_args__ = (
        {'mysql_engine': 'InnoDB', 'sqlite_autoincrement': True, 'mysql_charset': 'utf8'}
    )

    id = Column(INTEGER, autoincrement=True, primary_key=True, nullable=False)  # pylint: disable=invalid-name
    name = Column(TEXT, nullable=False)
    address = Column(TEXT)
    phone = Column(TEXT, nullable=False)
    email = Column(TEXT)
    comment = Column(TEXT)
    totalPrice = Column(DECIMAL(asdecimal=False))
    orderItems = relationship(Orderitem)
    time = Column(TEXT, default=time.strftime("%H:%m %d.%m.%y"))

    def __repr__(self):
        return self.__str__()

    def __str__(self):
        return "<Order(%s)>" % self.__dict__

@app.route('/api/orders', methods=['GET'])
def getAllOrders():
    allOrders = session.query(Order).all()
    return json.dumps(allOrders, cls=new_alchemy_encoder(False, ['orderItems', 'product']), check_circular=False, ensure_ascii=False) #ensure_ascii=False -- for rigth out cyrlic;

Solution

  • You have one SQLAlchemy session per Worker and probably use 2 Workers with uwsgi. SQLAlchemy caches results per session, so session of worker 1 returns the new results, because you have added the records with this worker, but the session of worker 2 is not updated and returns only the old records.

    Solution: don't create global sessions, but a new session for each request.

    @app.route('/api/orders', methods=['GET'])
    def getAllOrders():
        session = Session()
        allOrders = session.query(Order).all()
        return json.dumps(allOrders, cls=new_alchemy_encoder(False, ['orderItems', 'product']), check_circular=False, ensure_ascii=False) #ensure_ascii=False -- for rigth out cyrlic;