Flask-SQLAlchemy and Gevent do not close mysql connections

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

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

The problem I'm currently facing is that when the connection to the websocket ends, the database connection configured by Flask-SQLAlchemy will continue to live.

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

Calling gevent.monkey.patch_all() at the beginning of my application does not matter.

A simple representation of what I am doing is the following:

 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() 
+7
flask-sqlalchemy sqlalchemy gevent uwsgi
source share
1 answer

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

 [mysqld] interactive_timeout=180 wait_timeout=180 

you must restart the mysql service after saving my.cnf.

If you do not want to restart the mysql service, you can use SQL queries:

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

See also wait_timeout and interactive_timeout at mysql.com

0
source share

All Articles