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

断了今生、忘了曾经 提交于 2019-12-11 11:13:07

问题


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;

回答1:


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;


来源:https://stackoverflow.com/questions/36258154/sqlalchemy-returns-different-results-of-the-select-command-query-all

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!