'Flask-SQLAlchemy not storing object between requests

I start from following very basic code:

from flask_sqlalchemy import SQLAlchemy, Model
from flask import Flask

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = "mysql+pymysql://titi:[email protected]:3306/test"
db = SQLAlchemy(app)


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=False, nullable=False)
    email = db.Column(db.String(120), unique=False, nullable=False)


@app.route("/test")
def test():
    return User.query.get(1).email


if __name__ == '__main__':
    app.run(host="127.0.0.1", port=5000)

Here is what happens at the DB query log level:

220301 12:20:13     62 Connect  titi@localhost on testFAC using TCP/IP
            62 Query    SET AUTOCOMMIT = 0
            62 Query    SET NAMES utf8
            62 Query    SELECT @@sql_mode
            62 Query    SELECT @@lower_case_table_names
            62 Query    SELECT VERSION()
            62 Query    SELECT DATABASE()
            62 Query    SELECT @@tx_isolation
            62 Query    ROLLBACK
            62 Query    SELECT user.id AS user_id, user.username AS user_username, user.email AS user_email 
FROM user 
WHERE user.id = 1
            62 Query    ROLLBACK
            62 Query    ROLLBACK
220301 12:20:28     62 Query    SELECT user.id AS user_id, user.username AS user_username, user.email AS user_email 
FROM user 
WHERE user.id = 1
            62 Query    ROLLBACK
            62 Query    ROLLBACK

I don't want to comment here the insane 'ROLLBACK' statement after each SELECT and at request end hopefully ignored by the database engine... But I am very surprised to see that each new request to http://localhost:5000/test issues a new SQL query, meaning that SQLAlchemy is not storing User object by its primary key between 2 requests, what one could expect from a standard ORM/EntityManager...

Digging a little bit, I noticed that object storing/caching only effective at request scope:

@app.route("/test2")
def test2():
    user1 = User.query.get(1)
    user2 = User.query.get(1)
    assert user1 == user2
    return User.query.get(1).email

is only issuing one SQL Query...

Did I miss something at SQLAlchemy configuration level ?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source