Python 炼金术-2013年失去联系

Python 炼金术-2013年失去联系,python,mysql,flask,sqlalchemy,flask-sqlalchemy,Python,Mysql,Flask,Sqlalchemy,Flask Sqlalchemy,所以我尝试使用数据库和flask动态构建一个站点。从现在起,该网站按我所希望的方式运行,但只运行了大约一分钟,我就收到了一条错误消息,上面说: sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2013, 'Lost connection to MySQL server during query') 数据库包含4个我想为每个页面抓取的条目,以及一个主页面,其中我只从数据库中的每个条目中抓取2个条目。 在此过程中,它

所以我尝试使用数据库和flask动态构建一个站点。从现在起,该网站按我所希望的方式运行,但只运行了大约一分钟,我就收到了一条错误消息,上面说:

sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2013, 'Lost connection to MySQL server during query')
数据库包含4个我想为每个页面抓取的条目,以及一个主页面,其中我只从数据库中的每个条目中抓取2个条目。 在此过程中,它遇到了一个错误,无法再访问数据库,因此不允许加载更多使用数据库的页面

有人能帮我弄清楚为什么会发生这种事吗?我对烧瓶和炼金术很陌生

下面是我的代码:

Database.py
首先,为什么要在app.py和Database.py中两次实例化Flask对象?您的项目应该只实例化一个Flask对象。如果您想使您的Flask项目更加模块化,请检查此处的Blueprint对象

现在,请尝试以下操作,并注意我尚未测试此功能,如果它不起作用,请告诉我:

Database.py app.py
这个问题与sqlalchemy或flask无关。它实际上是在mysql服务器端。正在使用的服务器正在超时并断开与非本地主机的任何连接的连接


切换到本地sqlite数据库为我解决了这个问题,直到我能够找到另一台服务器来托管mysql数据库,该服务器允许远程连接/托管数据库本地主机上的站点。

我遇到了类似的问题。以下是我的解决方案:

从DB MariaDB/MySQL获取等待超时

SHOW GLOBAL VARIABLES LIKE "wait_timeout";
设置SQLALCHEMY\u池\u烧瓶内循环代码:

app = Flask(__name__)
app.config['SQLALCHEMY_POOL_RECYCLE'] = <db_wait_timeout> - 1
根据来自的建议和互联网上的许多其他文章,使用以下decorator包装我的所有功能帮助我解决了mariadb作为后端数据库的连接丢失问题。请注意,下面的db是flask_sqlalchemy.sqlalchemy的一个实例


我还在Flask SQLAlchemy config中添加了50秒的pool_recycle,但这对解决方案没有明显的帮助。

我对更改进行了修改,但我发现了这个错误:回溯最近一次调用:File/home/devin matte/Documents/Coralite/app.py,第3行,在from Database import Kitchen File/home/devin matte/Documents/Coralite/Database.py第1行中,在from app import db File/home/devin matte/Documents/Coralite/app.py第3行中,在from Database import Kitchen ImportError中:无法导入名称“Kitchen”,因此将Kitchens类移动到app.py修复了该错误。但是现在我仍然得到了我在写第一篇文章之前的错误。我理解,这是一个循环导入。在实例化SQLAlchemy对象后,尝试导入Kitchen对象。再次,我很抱歉,在写之前我不能测试这个,我只是想帮上忙。在db=SQLAlchemyapp之后,从数据库导入厨房执行操作,并查看结果。在db=SQLAlchemyapp之后导入对错误没有帮助。也不要担心没有测试,我感谢上面提到的helpOk,发生这种情况的原因是因为循环导入。现在,我通过导入文件并引用厨房对象修复了它,如下所示:导入数据库。这个import语句将与我的第一个响应位于同一位置,在db=SQLAlchemyapp之前。唯一的问题是,您必须执行Database.Kitchen操作,以访问Kitchen对象。试试这个,让我知道!建议:添加app.config['SQLALCHEMY\u POOL\u TIMEOUT']=,对连接稳定有额外的好处。请注意,更新后的方法是使用SQLALCHEMY\u ENGINE\u选项。SQLALCHEMY_POOL_RECYCLE从v2.4开始就被弃用,并在v3.0中删除。我发现一个很好的用例是在这个SO答案中:
[2017-02-10 10:17:31,776] ERROR in app: Exception on /kitchens/ 1 [GET]
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/base.py", line 1182, in _execute_context
context)
File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/default.py", line 470, in do_execute
cursor.execute(statement, parameters)
File "/home/devin-matte/.local/lib/python3.5/site-packages/pymysql/cursors.py", line 166, in execute
result = self._query(query)
File "/home/devin-matte/.local/lib/python3.5/site-packages/pymysql/cursors.py", line 322, in _query
conn.query(q)
File "/home/devin-matte/.local/lib/python3.5/site-packages/pymysql/connections.py", line 835, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "/home/devin-matte/.local/lib/python3.5/site-packages/pymysql/connections.py", line 1019, in _read_query_result
result.read()
File "/home/devin-matte/.local/lib/python3.5/site-packages/pymysql/connections.py", line 1302, in read
first_packet = self.connection._read_packet()
File "/home/devin-matte/.local/lib/python3.5/site-packages/pymysql/connections.py", line 961, in _read_packet
packet_header = self._read_bytes(4)
File "/home/devin-matte/.local/lib/python3.5/site-packages/pymysql/connections.py", line 998, in _read_bytes
2013, "Lost connection to MySQL server during query")
pymysql.err.OperationalError: (2013, 'Lost connection to MySQL server during query')

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/home/devin-matte/.local/lib/python3.5/site-packages/flask/app.py", line 1988, in wsgi_app
response = self.full_dispatch_request()
File "/home/devin-matte/.local/lib/python3.5/site-packages/flask/app.py", line 1641, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/devin-matte/.local/lib/python3.5/site-packages/flask/app.py", line 1544, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/devin-matte/.local/lib/python3.5/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/home/devin-matte/.local/lib/python3.5/site-packages/flask/app.py", line 1639, in full_dispatch_request
rv = self.dispatch_request()
File "/home/devin-matte/.local/lib/python3.5/site-packages/flask/app.py", line 1625, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/devin-matte/Documents/Coralite/Coralite.py", line 18, in kitchens
row = Kitchen.query.count()
File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/orm/query.py", line 3024, in count
return self.from_self(col).scalar()
File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/orm/query.py", line 2778, in scalar
ret = self.one()
File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/orm/query.py", line 2749, in one
ret = self.one_or_none()
File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/orm/query.py", line 2719, in one_or_none
ret = list(self)
File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/orm/query.py", line 2790, in __iter__
return self._execute_and_instances(context)
File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/orm/query.py", line 2813, in _execute_and_instances
result = conn.execute(querycontext.statement, self._params)
File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/base.py", line 945, in execute
return meth(self, multiparams, params)
File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/sql/elements.py", line 263, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/base.py", line 1053, in _execute_clauseelement
compiled_sql, distilled_params
File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/base.py", line 1189, in _execute_context
context)
File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/base.py", line 1393, in _handle_dbapi_exception
exc_info
File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/util/compat.py", line 203, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cause)
File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/util/compat.py", line 186, in reraise
raise value.with_traceback(tb)
File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/base.py", line 1182, in _execute_context
context)
File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/default.py", line 470, in do_execute
cursor.execute(statement, parameters)
File "/home/devin-matte/.local/lib/python3.5/site-packages/pymysql/cursors.py", line 166, in execute
result = self._query(query)
File "/home/devin-matte/.local/lib/python3.5/site-packages/pymysql/cursors.py", line 322, in _query
conn.query(q)
File "/home/devin-matte/.local/lib/python3.5/site-packages/pymysql/connections.py", line 835, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "/home/devin-matte/.local/lib/python3.5/site-packages/pymysql/connections.py", line 1019, in _read_query_result
result.read()
File "/home/devin-matte/.local/lib/python3.5/site-packages/pymysql/connections.py", line 1302, in read
first_packet = self.connection._read_packet()
File "/home/devin-matte/.local/lib/python3.5/site-packages/pymysql/connections.py", line 961, in _read_packet
packet_header = self._read_bytes(4)
File "/home/devin-matte/.local/lib/python3.5/site-packages/pymysql/connections.py", line 998, in _read_bytes
2013, "Lost connection to MySQL server during query")
sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2013, 'Lost connection to MySQL server during query') [SQL: 'SELECT count(*) AS count_1 \nFROM (SELECT kitchens.id AS kitchens_id, kitchens.description AS kitchens_description, kitchens.`galleryId` AS `kitchens_galleryId`, kitchens.cpo AS kitchens_cpo \nFROM kitchens) AS anon_1']
127.0.0.1 - - [10/Feb/2017 10:17:31] "GET /kitchens/%201 HTTP/1.1" 500 -
from flask import Flask
from flask import render_template
from app import db

class Kitchen(db.Model):
    __tablename__ = 'kitchens'
    id = db.Column('id', db.Integer, primary_key=True)
    description = db.Column('description')
    galleryId = db.Column('galleryId')
    cpo = db.Column('cpo')

    def __init__(self, description, galleryId, cpo):
        self.description = description
        self.galleryId = galleryId
        self.cpo = cpo

    def __repr__(self):
        return '<Gallery %r>' % self.description

    def get_description(self):
        return self.description

    def get_galleryId(self):
        return self.galleryId

    def get_cpo(self):
        return self.cpo
from flask import Flask
from flask import render_template
from Database import Kitchen
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://databaseaddress'
db = SQLAlchemy(app)

@app.route('/')
@app.route('/index')
def main():
    return render_template('index.html')


@app.route('/kitchens', methods=['GET'], defaults={'n': 0})
@app.route('/kitchens/<n>', methods=['GET'])
def kitchens(n):
    row = Kitchen.query.count()
    if int(n) is 0:
        description = []
        for num in range(1, row+1):
            data = Kitchen.query.filter_by(id=num).first()
            description.append(Kitchen.get_description(data))
        return render_template('Gallery Directory.html', portfolio='Kitchens', row=row, description=description)
    elif int(n) >= 1:
        data = Kitchen.query.filter_by(id=n).first()
        description = Kitchen.get_description(data)
        galleryId = Kitchen.get_galleryId(data)
        cpo = Kitchen.get_cpo(data)
        return render_template('Gallery Basic.html', portfolio='Kitchens', description=description, id=int(n),
                               galleryId=galleryId, cpo=cpo, row=row)


if __name__ == "__main__":
    db.create_all()
    app.run()
SHOW GLOBAL VARIABLES LIKE "wait_timeout";
app = Flask(__name__)
app.config['SQLALCHEMY_POOL_RECYCLE'] = <db_wait_timeout> - 1
def manage_session(f):
    def inner(*args, **kwargs):

        # MANUAL PRE PING
        try:
            db.session.execute("SELECT 1;")
            db.session.commit()
        except:
            db.session.rollback()
        finally:
            db.session.close()

        # SESSION COMMIT, ROLLBACK, CLOSE
        try:
            res = f(*args, **kwargs)
            db.session.commit()
            return res
        except Exception as e:
            db.session.rollback()
            raise e
            # OR return traceback.format_exc()
        finally:
            db.session.close()
    return inner