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()
答案 0 :(得分:0)
我有同样的情况。和我的解决方案位于mysql配置文件my.cnf
:
[mysqld]
interactive_timeout=180
wait_timeout=180
保存my.cnf后必须重启mysql服务。
如果您不想重启mysql服务,可以使用sql查询:
SET GLOBAL interactive_timeout = 180;
SET GLOBAL wait_timeout = 180;
另请参阅mysql.com上的wait_timeout和interactive_timeout