How to set connection timeout in SQLAlchemy
The right way is this one (connect_timeout
instead of connection_timeout
):
create_engine(db_url, connect_args={'connect_timeout': 10})
...and it works with both Postgres and MySQL
docs sqlalchemy connect-args
ps: (the timeout is defined in seconds)
For whoever is using Flask-SQLAlchemy instead of plain SQLAlchemy, you can choose between two ways for passing values to SQLAlchemy's create_engine
:
- Use
SQLALCHEMY_ENGINE_OPTIONS
configuration key (Flask-SQLAlchemy>=2.4 required)
SQLALCHEMY_ENGINE_OPTIONS = {
'connect_args': {
'connect_timeout': 5
}
}
- Or, in alternative, use
engine_option
when instantiatingflask_sqlalchemy.SQLAlchemy
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
db = SQLAlchemy(
engine_options={ 'connect_args': { 'connect_timeout': 5 }}
)
db.init_app(app)
EDIT: The examples are using the connect_timeout
argument that works (at least) for MySQL and PostgreSQL (value represent seconds), other DBMS may require different argument name to be passed to affect the connection timeout. I suggest to check your DBMS manual to check for such option.