简体   繁体   English

Flask-SQLAlchemy - “MySQL连接不可用”。

[英]Flask-SQLAlchemy -“MySQL Connection not available.”

After about an hour of inactivity, any attempt to query the database hangs for about 30 seconds and then results in a 500 Internal Server Error. 大约一个小时不活动后,任何查询数据库的尝试都会挂起大约30秒,然后导致500内部服务器错误。 The basic error message is as follows: 基本错误消息如下:

sqlalchemy.exc.OperationalError: (mysql.connector.errors.OperationalError) MySQL Connection not available.

I've put the full stack trace at the end of the question. 我在问题的最后给出了完整的堆栈跟踪。

Now I've visited this question and tried the solution there, but to no avail. 现在我已经访问了这个问题并尝试了解决方案,但无济于事。 I've made the pool_recycle value greater than, equal to, and less than the MySQL timeout value (28800s currently). 我已经使pool_recycle值大于,等于和小于MySQL超时值(当前为28800s)。

What are some other things worth trying? 还有什么值得尝试的其他事情?

Traceback (most recent call last):
  File "/var/www/html/benefits_app/benefits_app/venv/lib/python3.4/site-packages/flask/app.py", line 1817, in wsgi_app
    response = self.full_dispatch_request()
  File "/var/www/html/benefits_app/benefits_app/venv/lib/python3.4/site-packages/flask/app.py", line 1477, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/var/www/html/benefits_app/benefits_app/venv/lib/python3.4/site-packages/flask/app.py", line 1381, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/var/www/html/benefits_app/benefits_app/venv/lib/python3.4/site-packages/flask/_compat.py", line 33, in reraise
    raise value
  File "/var/www/html/benefits_app/benefits_app/venv/lib/python3.4/site-packages/flask/app.py", line 1475, in full_dispatch_request
    rv = self.dispatch_request()
  File "/var/www/html/benefits_app/benefits_app/venv/lib/python3.4/site-packages/flask/app.py", line 1461, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/var/www/html/benefits_app/benefits_app/auth.py", line 18, in login
    user = User.query.filter_by(username=form.username.data).first()
  File "/var/www/html/benefits_app/benefits_app/venv/lib/python3.4/site-packages/sqlalchemy/orm/query.py", line 2445, in first
    ret = list(self[0:1])
  File "/var/www/html/benefits_app/benefits_app/venv/lib/python3.4/site-packages/sqlalchemy/orm/query.py", line 2281, in __getitem__
    return list(res)
  File "/var/www/html/benefits_app/benefits_app/venv/lib/python3.4/site-packages/sqlalchemy/orm/query.py", line 2516, in __iter__
    return self._execute_and_instances(context)
  File "/var/www/html/benefits_app/benefits_app/venv/lib/python3.4/site-packages/sqlalchemy/orm/query.py", line 2531, in _execute_and_instances
    result = conn.execute(querycontext.statement, self._params)
  File "/var/www/html/benefits_app/benefits_app/venv/lib/python3.4/site-packages/sqlalchemy/engine/base.py", line 914, in execute
    return meth(self, multiparams, params)
  File "/var/www/html/benefits_app/benefits_app/venv/lib/python3.4/site-packages/sqlalchemy/sql/elements.py", line 323, in _execute_on_connection
    return connection._execute_clauseelement(self, multiparams, params)
  File "/var/www/html/benefits_app/benefits_app/venv/lib/python3.4/site-packages/sqlalchemy/engine/base.py", line 1010, in _execute_clauseelement
    compiled_sql, distilled_params
  File "/var/www/html/benefits_app/benefits_app/venv/lib/python3.4/site-packages/sqlalchemy/engine/base.py", line 1078, in _execute_context
    None, None)
  File "/var/www/html/benefits_app/benefits_app/venv/lib/python3.4/site-packages/sqlalchemy/engine/base.py", line 1341, in _handle_dbapi_exception
    exc_info
  File "/var/www/html/benefits_app/benefits_app/venv/lib/python3.4/site-packages/sqlalchemy/util/compat.py", line 188, in raise_from_cause
    reraise(type(exception), exception, tb=exc_tb, cause=exc_value)
  File "/var/www/html/benefits_app/benefits_app/venv/lib/python3.4/site-packages/sqlalchemy/util/compat.py", line 181, in reraise
    raise value.with_traceback(tb)
  File "/var/www/html/benefits_app/benefits_app/venv/lib/python3.4/site-packages/sqlalchemy/engine/base.py", line 1073, in _execute_context
    context = constructor(dialect, self, conn, *args)
  File "/var/www/html/benefits_app/benefits_app/venv/lib/python3.4/site-packages/sqlalchemy/engine/default.py", line 556, in _init_compiled
    self.cursor = self.create_cursor()
  File "/var/www/html/benefits_app/benefits_app/venv/lib/python3.4/site-packages/sqlalchemy/engine/default.py", line 745, in create_cursor
    return self._dbapi_connection.cursor()
  File "/var/www/html/benefits_app/benefits_app/venv/lib/python3.4/site-packages/sqlalchemy/pool.py", line 847, in cursor
    return self.connection.cursor(*args, **kwargs)
  File "/var/www/html/benefits_app/benefits_app/venv/lib/python3.4/site-packages/mysql/connector/connection.py", line 1383, in cursor
    raise errors.OperationalError("MySQL Connection not available.")
sqlalchemy.exc.OperationalError: (mysql.connector.errors.OperationalError) MySQL Connection not available. [SQL:'blah blah query']

So I got to an acceptable solution, but not a perfect one. 所以我得到了一个可接受的解决方案,但不是一个完美的方案。 The one only time this error occurred was when I was attempting to log in after a period of inactivity. 发生此错误的唯一一次是我在一段时间不活动后尝试登录时。 My original code is as follows: 我原来的代码如下:

@auth_blueprint.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        try:
            user = User.query.filter_by(username=form.username.data).first()
        except:
            user = User.query.filter_by(username=form.username.data).first()

Here is the change I made that stopped the 500 internal server errors from occurring. 以下是我所做的更改,它阻止了500个内部服务器错误的发生。

@auth_blueprint.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        try:
            user = User.query.filter_by(username=form.username.data).first()
        except:
            db.session.rollback()
            user = User.query.filter_by(username=form.username.data).first()

The reason this is not a perfect solution is that there is a delay while I wait for the first User.query to fail and try the same query again. 这不是一个完美的解决方案的原因是,当我等待第一个User.query失败并再次尝试相同的查询时,有一个延迟。 It is also not very nice solution, but I no longer see an error message and the page works as intended even after an extended period of inactivity. 它也不是一个很好的解决方案,但是我不再看到错误消息,即使在长时间不活动之后页面也按预期工作。

UPDATE UPDATE

As it turns out, the REAL solution that removed this error and made everything work great again was to change the MySQL wait_timeout and interactive_timeout from 28800 seconds down to the same value as my pool recycle option for sqlalchemy, which was set to 1600. 事实证明,删除此错误并使一切恢复正常的REAL解决方案是将MySQL wait_timeout和interactive_timeout从28800秒更改为与sqlalchemy的池回收选项相同的值,该选项设置为1600。

Problems Gone! 问题已经消失!

Half the time you will probably need to host your application on a shared server where you dont have access to tune the mysql parameters. 有一半时间您可能需要在共享服务器上托管您的应用程序,在该服务器上您无权调整mysql参数。

and while my app was not timing out on my localhost ,when i ported it to python anywhere , i had inactivity errors and my solutions was this below 虽然我的应用程序没有在我的本地主机上超时,当我将它移植到任何地方的python时,我有不活动错误,我的解决方案如下

SQLALCHEMY_DATABASE_URI = 'mysql://root:beautiful@localhost/service_compare'
SQLALCHEMY_POOL_RECYCLE = 280
SQLALCHEMY_POOL_SIZE = 20
SQLALCHEMY_TRACK_MODIFICATIONS = True

You can read though here 你可以在这里阅读

http://docs.sqlalchemy.org/en/latest/faq/connections.html http://docs.sqlalchemy.org/en/latest/faq/connections.html

and on this line below 在下面这一行

except:
        #db.session.rollback()
        user = User.query.filter_by(username=form.username.data).first()

i think you need to add a db.session.remove() 我想你需要添加一个db.session.remove()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM