close

How to set connection timeout in SQLAlchemy

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to set connection timeout in SQLAlchemy in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to set connection timeout in SQLAlchemy?

  1. How to set connection timeout in SQLAlchemy?

    For whoever is using Flask-SQLAlchemy instead of plain SQLAlchemy, you can choose between two ways for passing values to SQLAlchemy's create_engine:

  2. set connection timeout in SQLAlchemy

    For whoever is using Flask-SQLAlchemy instead of plain SQLAlchemy, you can choose between two ways for passing values to SQLAlchemy's create_engine:

Method 1

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

ps: (the timeout is defined in seconds)

Method 2

For whoever is using Flask-SQLAlchemy instead of plain SQLAlchemy, you can choose between two ways for passing values to SQLAlchemy’s create_engine:

  1. Use SQLALCHEMY_ENGINE_OPTIONS configuration key (Flask-SQLAlchemy>=2.4 required)
SQLALCHEMY_ENGINE_OPTIONS = {
    'connect_args': {
        'connect_timeout': 5
    }
}
  1. Or, in alternative, use engine_option when instantiating flask_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.

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read