加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

postgresql – 重新启动数据库服务器后,Flask-sqlalchemy失去连

发布时间:2020-12-13 16:03:34 所属栏目:百科 来源:网络整理
导读:我在我的应用程序中使用flask-sqlalchemy. DB是 postgresql 9.3. 我有简单的db,模型和视图初始化: from config import *from flask import Flask,request,render_templatefrom flask.ext.sqlalchemy import SQLAlchemyapp = Flask(__name__)app.config['SQL
我在我的应用程序中使用flask-sqlalchemy. DB是 postgresql 9.3.
我有简单的db,模型和视图初始化:

from config import *
from flask import Flask,request,render_template
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://%s:%s@%s/%s' % (DB_USER,DB_PASSWORD,HOST,DB_NAME)
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer,primary_key=True)
    login = db.Column(db.String(255),unique=True,index=True,nullable=False)

db.create_all()
db.session.commit()

@app.route('/users/')
def users():
    users = User.query.all()
    return '1'

一切正常.但是当DB服务器重启时(sudo service postgresql restart),首次请求/ users /我获取sqlalchemy.exc.OperationalError:

OperationalError: (psycopg2.OperationalError) terminating connection due to administrator command
SSL connection has been closed unexpectedly
 [SQL: ....

有没有办法在视图内部更新连接,或者以另一种方式设置flask-sqlalchemy以自动续订连接?

UPDATE.

我最终使用了清晰的SQLAlchemy,为每个视图声明了引擎,元数据和db_session,我非常需要它.

它不是问题的解决方案,只是一个’黑客’.

所以问题是开放的.我相信,为此找到解决方案会很好:)

解决方法

SQLAlchemy documentation解释了默认行为是乐观地处理断开连接.您是否尝试过其他请求 – 连接应该重新建立?我刚用Flask / Postgres / Windows项目对它进行了测试,它确实有效.

在使用ORM会话的典型Web应用程序中,上述条件对应于单个请求失败并出现500错误,然后Web应用程序正常继续超出该错误.因此,该方法是“乐观的”,因为不会预期频繁的数据库重启.

如果要在连接尝试之前检查连接状态,则需要编写以悲观方式处理断开连接的代码.以下示例代码在文档中提供:

from sqlalchemy import exc
from sqlalchemy import event
from sqlalchemy.pool import Pool

@event.listens_for(Pool,"checkout")
def ping_connection(dbapi_connection,connection_record,connection_proxy):
    cursor = dbapi_connection.cursor()
    try:
        cursor.execute("SELECT 1")
    except:
        # optional - dispose the whole pool
        # instead of invalidating one at a time
        # connection_proxy._pool.dispose()

        # raise DisconnectionError - pool will try
        # connecting again up to three times before raising.
        raise exc.DisconnectionError()
    cursor.close()

以下是PyCharm调试器中捕获的事件的一些屏幕截图:

Windows 7(Postgres 9.4,Flask 0.10.1,SQLAlchemy 1.0.11,Flask-SQLAlchemy 2.1和psycopg 2.6.1)

在第一个数据库请求

enter image description here


db重启后

enter image description here

Ubuntu 14.04(Postgres 9.4,SQLAlchemy 1.0.8,Flask-SQLAlchemy 2.0和psycopg 2.5.5)

在第一个数据库请求

enter image description here


db restart

enter image description here

之后

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读