how to fix “OperationalError: (psycopg2.OperationalError) server closed the connection unexpectedly”

后端 未结 3 912
你的背包
你的背包 2020-12-15 09:41

Services

My service based on flask + postgresql + gunicorn + supervisor + nginx

When deploying by docker, after running the service, then accessing the api

3条回答
  •  难免孤独
    2020-12-15 10:19

    Building on the Solution in the answer and the info from @MaxBlax360's answer. I think the proper way to set these config values in Flask-SQLAlchemy is by setting app.config['SQLALCHEMY_ENGINE_OPTIONS']:

    from flask import Flask
    from flask_sqlalchemy import SQLAlchemy
    
    app = Flask(__name__)
    # pool_pre_ping should help handle DB connection drops
    app.config['SQLALCHEMY_ENGINE_OPTIONS'] = {"pool_pre_ping": True}  
    app.config['SQLALCHEMY_DATABASE_URI'] = \
        f'postgresql+psycopg2://{POSTGRES_USER}:{dbpass}@{POSTGRES_HOST}:{POSTGRES_PORT}/{POSTGRES_DBNAME}'
    db = SQLAlchemy(app)
    

    See also Flask-SQLAlchemy docs on Configuration Keys

提交回复
热议问题