title: Flask-SQLAlchemy error MySQL server has gone away
body: <p>I'm newbie running a Flask app connected to a MySQL remote server with Flask-SQLAlchemy.</p>
  <p>The app has very little traffic and it's usual to stay idle for more than 8 hours, I then get disconnected from the MySQL server.</p>
  <p>this is my app code:</p>
  <pre><code>from flask import Flask, render_template, request, redirect, jsonify, make_response
  from flask_sqlalchemy import SQLAlchemy
  from sqlalchemy import or_    
  
  app = Flask(__name__)
  app.config['DEBUG'] = True
  app.config['SQLALCHEMY_ENGINE_OPTIONS'] = {'pool_pre_ping': True, 'pool_recycle': 300, 'echo':'debug',}
  app.config['SQLALCHEMY_DATABASE_URI']='mysql+pymysql://user:pass@myipcode/db'
  db = SQLAlchemy(app)
  </code></pre>
  <p>Everything works ok until no querys are performed for 8 hours, then I lose db connection and logs show this error code:</p>
  <p><code>&quot;MySQL server has gone away (%r)&quot; % (e,)) sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2006, &quot;MySQL server has gone away (BrokenPipeError(32, 'Broken pipe'))</code></p>
  <p>I did some research and was adviced to set 'SQLALCHEMY_ENGINE_OPTIONS' as written in the code sample but it behaves the same with or without such engine options, connection is not recycled every 300 seconds as It should, and pool_pre_ping doesn't seem to make any difference. <code>'echo':'debug'</code> option works as intended since I get every transaction logged.</p>
  <p>What should I do to prevent the connection from being disconnected even after a long period of inactivty?</p>
  <p>EDIT:</p>
  <p>To add some additional info:</p>
  <p>The database is hosted in Cloud SQL from GCP .</p>
  <p>I'm lost...
  Any help would be greatly appreciated.</p>