简体   繁体   English

psycopg2.OperationalError 错误

[英]psycopg2.OperationalError errors

I have created a Python flask web app and deployed it on an Azure App service using gunicorn .我创建了一个Python的flask Web应用程序并将其部署在一个蓝色的App service使用gunicorn The web app uses flask_sqlalchemy to connect to a PostgreSQL database which is also deployed on an Azure Database for PostgreSQL server . Web 应用程序使用flask_sqlalchemy连接到 PostgreSQL 数据库,该数据库也部署在Azure Database for PostgreSQL server

I would sometimes get the error below after the web app inserts a "small" query of one row with six fields:在 Web 应用程序插入包含六个字段的一行的“小”查询后,我有时会收到以下错误:

sqlalchemy.exc.InvalidRequestError: This Session's transaction has been rolled back due to a previous exception during flush. To begin a new transaction with this Session, first issue Session.rollback(). 
Original exception was: (psycopg2.OperationalError) SSL SYSCALL error: EOF detected

[SQL: INSERT INTO <table>]
[parameters: <row's parameters>]
(Background on this error at: http://sqlalche.me/e/e3q8) (Background on this error at: http://sqlalche.me/e/7s2a)

Whilst the web app was still deployed, I restarted the database server and found the drop in connection leads to the error.虽然 Web 应用程序仍在部署,但我重新启动了数据库服务器,发现连接下降导致了错误。 If I then restart the app service, the issue gets resolved.如果我然后重新启动应用程序服务,问题就会得到解决。

When I locally deploy the web app and disconnect the database I get a slightly different error:当我在本地部署 Web 应用程序并断开数据库连接时,我收到一个略有不同的错误:

sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) server closed the connection unexpectedly
    This probably means the server terminated abnormally
    before or while processing the request.

[SQL: INSERT INTO <table>]
[parameters: <row's parameters>]
(Background on this error at: http://sqlalche.me/e/e3q8)

Following advice from SQLAlchemy , I changed the database connection to:按照SQLAlchemy 的建议,我将数据库连接更改为:

db = SQLAlchemy(engine_options={"pool_pre_ping": True})

This solved the problem for the locally deployed web app, but the same error message still appears for the Azure deployed web app.这解决了本地部署的 Web 应用程序的问题,但 Azure 部署的 Web 应用程序仍然出现相同的错误消息。

Any advice?有什么建议吗?

pip freeze:点冻结:

aniso8601==8.0.0
atomicwrites==1.3.0
attrs==19.3.0
certifi==2019.11.28
cffi==1.14.0
chardet==3.0.4
Click==7.0
colorama==0.4.3
cryptography==2.8
Flask==1.1.1
flask-restx==0.1.1
Flask-SQLAlchemy==2.4.1
idna==2.8
importlib-metadata==1.5.0
itsdangerous==1.1.0
Jinja2==2.11.1
jsonschema==3.2.0
jwt==0.6.1
MarkupSafe==1.1.1
more-itertools==8.2.0
numpy==1.18.1
packaging==20.1
pandas==1.0.1
pluggy==0.13.1
psycopg2==2.8.4
py==1.8.1
pycparser==2.19
PyJWT==1.7.1
pyparsing==2.4.6
pyrsistent==0.15.7
pytest==5.3.5
python-dateutil==2.8.1
pytz==2019.3
requests==2.22.0
scipy==1.4.1
six==1.14.0
SQLAlchemy==1.3.13
urllib3==1.25.8
wcwidth==0.1.8
Werkzeug==0.16.1
wincertstore==0.2
zipp==3.0.0

Update:更新:

We fixed it by having more defensive connections to the database;我们通过与数据库建立更多防御性连接来修复它; putting all connections in a try/catch, and if a psycopg2 exception was raised, flushing and retrying periodically.将所有连接放在 try/catch 中,如果引发了 psycopg2 异常,则定期刷新和重试。

attempts = 0
while attempts <= 5:
    attempts = attempts + 1
    logger.info("Attempt " + str(attempts))
    try:
        db.session.add(job_status)
        db.session.commit()
        return
    except (SQLAlchemyError, OperationalError) as e:
        if attempts < 5:
            logger.warning("Attempt failed. Trying rollback")
            db.session.rollback()
            time.sleep(5)
        else:
            logger.error("Maximum number of retries reached. Raising an error")
            raise e

如果事务( src )期间出现错误,您总是必须回滚对数据库的更改,并且不要忘记在所有提交(操作)后最终关闭连接。

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

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