KcH
KcH

Reputation: 3502

Flask-SQLAlchemy: How to pass parameters to create_engine() such as pool_size?

A noob's confused question:

How and where to set pool_size?

I found setting the pool size in docs as:

engine = create_engine('postgresql://me@localhost/mydb',
                       pool_size=20, max_overflow=0)

, but is there a way to set pool_size for below snippet too,if yes pleased to know how?

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:root@localhost/testdb'
db = SQLAlchemy(app)


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)

    def __repr__(self):
        return '<User %r>' % self.username
    ......
    ......

error is as follows:

sqlalchemy.exc.TimeoutError: QueuePool limit of size 10 overflow 10 reached, connection timed out, timeout 30 

Upvotes: 1

Views: 5564

Answers (1)

SuperShoot
SuperShoot

Reputation: 10861

If you are using >= version 2.4, the SQLALCHEMY_ENGINE_OPTIONS key exists specifically for specifying keyword arguments that will be passed to create_engine (docs). So in your case adding app.config["SQLALCHEMY_ENGINE_OPTIONS"] = {"pool_size": 20} to your app configuration should do the trick.

Alternatively, 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_size": 20}) is equivalent to above, except that these values will merge with and take precedence over any engine settings also defined in SQLALCHEMY_ENGINE_OPTIONS.

Finally, there are a suite of SQLALCHEMY_ prefixed configuration keys that are depreciated, but will work until 3.0. In this case app.config["SQLALCHEMY_POOL_SIZE"] = 20. Unless you are using a version earlier than 2.4, it would be better to use one of the former options.

Upvotes: 6

Related Questions