1

I'm using Flask SQLAlchemy to connect to my mysql db, but it has defualt wait_timeout 120 seconds, so after I query my users and web isn't used for a while I get an error

(2013, 'Lost connection to MySQL server during query')

Important piece of my db.py

app = Flask(__name__)
db = SQLAlchemy(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://urltomyserver'
app.config['SQLALCHEMY_POOL_RECYCLE'] = 10
app.config['SQLALCHEMY_POOL_TIMEOUT'] = 120
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)

if __name__ == 'createdb':
    db.reflect()
    db.drop_all()
    db = SQLAlchemy(app)

And piece of my views.py

  @core.route('/')
    def index():
        userzy = sftpuser.query.all()
        return render_template('index.html', userzy=userzy)
        #I'D LIKE TO CLOSE MY CONNECTION HERE

I've tried these under after I return template in def index

  db.session.close()
    db.close()
    db.dispose()
    db.session.close()
    db.engine.dispose()
    db.session.commit()

And this

@app.teardown_appcontext
def teardown_db(error):
    db.session.close()
    db.engine.dispose()

But it didnt help me that much, anyone knows the solution why do am I keep getting error even if I set the pool?

Gennway
  • 11
  • 3
  • Recent Flask-SQLAlchemy versions introduced config key SQLALCHEMY_ENGINE_OPTIONS to affect the engine creation. Check this https://stackoverflow.com/a/58697109/1161591 and this https://stackoverflow.com/a/58504084/1161591 to see how it's used – dappiu Nov 04 '19 at 16:20

1 Answers1

-1

Did yiu try to change this config: app.config['SQLALCHEMY_POOL_TIMEOUT'] = 120???

  • yep, I was trying many options like 120-1, 60, 30, 40, 100, more than 120. nothing really helped, the question is why? – Gennway Aug 23 '19 at 10:29
  • I also used https://stackoverflow.com/questions/42163359/flask-sqlalchemy-2013-lost-connection but didn't help me. – Gennway Aug 23 '19 at 10:30
  • I also found this https://stackoverflow.com/questions/52992361/flask-sqlalchemy-does-not-close-mysql-database-connections soo is it possible that it's not possible to fix that on "minimal application model" I used? should I reconfigure my whole app to Declarative with engine model? – Gennway Aug 23 '19 at 10:32
  • did you tried to remove app.config['SQLALCHEMY_POOL_TIMEOUT'] = 120? or to change Value to none? also ['SQLALCHEMY_POOL_TIMEOUT'] is Deprecated as of v2.4 and will be removed in v3.0. And check this https://stackoverflow.com/a/35640876/9988043 – Carp-Bezverhnii Maxim Aug 23 '19 at 11:43
  • I'm using v2, and yes. I tried to change value to none, or remove it. In the link you post the SQLAlchemy is based on engine, my isn't. So I'm wondering if it's even possible to fix it on my app or I have to rewrite the config so it will work on engine instead of app.config – Gennway Aug 23 '19 at 12:13
  • flask sqlalchemy v2.1* – Gennway Aug 23 '19 at 12:30