Flask-SQLAlchemy and Gevent not closing mysql connections

1.2k views Asked by At

I am currently using Flask-uWSGI-Websockets to provide websocket functionality for my application. I use Flask-SQLAlchemy to connect to my MySQL database.

Flask-uWSGI-Websockets uses gevent to manage websocket connections.

The problem I am currently having is that when a websocket connection is ended, the database connection set up by Flask-SQLAlchemy will keep on living.

I have tried calling db.session.close() and db.engine.dispose() after every websocket connection, but this had no effect.

Calling gevent.monkey.patch_all() at the beginning of my app does not make a difference.

A simple representation of what I am doing is this:

from gevent.monkey import patch_all
patch_all()

from flask import Flask
from flask_uwsgi_websocket import GeventWebSocket
from flask_sqlalchemy import SQLAlchemy

app = Flask()
ws = GeventWebSocket()
db = SQLAlchemy()

db.init_app(app)
ws.init_app(app)


@ws.route('/ws')
def websocket(client):
    """ handle messages """
    while client.connected is True:
        msg = client.recv()
        # do some db stuff with the message

    # The following part is executed when the connection is broken,
    # i tried this for removing the connection, but the actual
    # connection will stay open (i can see this on the mysql server).
    db.session.close()
    db.engine.dispose()
1

There are 1 answers

0
vanzhiganov On

I have same situation. and solution for me located in mysql configuration file my.cnf:

[mysqld]
interactive_timeout=180
wait_timeout=180

you must restart mysql service after save my.cnf.

if you don't want to restart mysql service you can use sql queries:

SET GLOBAL interactive_timeout = 180;
SET GLOBAL wait_timeout = 180;

See also wait_timeout and interactive_timeout on mysql.com