MikaJuhani
MikaJuhani

Reputation: 11

Is there some way to handle a disconnect in DB uri?

I am wondering is there some way to set pool_pre_ping in the Database URI so that I should not touch the actual code and use some SELECT[1] type of conn checks?

In the config, next following variable is read:

SQLALCHEMY_DATABASE_URI = f'postgresql+psycopg2://{user}:{pw}@db:5432/{db}'

I would like to add pool_pre_ping setting like:

SQLALCHEMY_DATABASE_URI = f'postgresql+psycopg2://{user}:{pw}@db:5432/{db} [SOMETHING pool_pre_ping=True]'

A problem behind the need for setting pool_pre_ping is that client side occasionally shuts down a db connection and an application can not offer response. Before fixing the original reason for this problem I should prevent disconnections.. on way or another. I am working with Docker containers.

I am very thanksful if you could offer me some tips. Thanks :-)

Upvotes: 1

Views: 452

Answers (2)

MikaJuhani
MikaJuhani

Reputation: 11

Thanks a lot! Now it works :-)

I did following:

(I did not set up "pool_pre_ping" in URI but added some lines in the code)

from flask_sqlalchemy import SQLAlchemy as _NSQLAlc ...

class SQLAlchemy(_NSQLAlc): def apply_pool_defaults(self, app, options): super(SQLAlchemy, self).apply_pool_defaults(app, options) options["pool_pre_ping"] = True

db = SQLAlchemy()

Upvotes: 0

SuperShoot
SuperShoot

Reputation: 10861

This was recently made much easier to achieve in Flask-SQLAlchemy v2.4.

The SQLALCHEMY_ENGINE_OPTIONS configuration key has been added specifically to make the configuration of create_engine through your flask app less rigid (docs). So in your case adding app.config["SQLALCHEMY_ENGINE_OPTIONS"] = {"pool_pre_ping": True} will achieve what you want.

Alternatively (again 2.4+), you can pass the dict of keyword arguments to the engine_options parameter of the SQLAlchemy() constructor (docs), e.g., SQLAlchemy(app, engine_options={"pool_pre_ping": True}) is equivalent to above, except that these values will merge with and take precedence over any engine settings also defined in SQLALCHEMY_ENGINE_OPTIONS.

Upvotes: 2

Related Questions