Ankit
Ankit

Reputation: 4720

Flask-Sqlalchemy setup engine configuration

SqlAlchemy extension: https://pythonhosted.org/Flask-SQLAlchemy/index.html

and i want to setup the engine with customer configuration using the parameters here: http://docs.sqlalchemy.org/en/rel_0_9/core/engines.html

I'm using the way described on Flask-SqlAlchemy documentation:

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)


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

    def __init__(self, username, email):
        self.username = username
        self.email = email

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

EDIT: How can I pass the following engine parameters in this kind of configuration:

isolation_level = 'AUTOCOMMIT', encoding='latin1', echo=True

method: SQLAlchemy() doesn't take these as arguments.

Upvotes: 7

Views: 8267

Answers (4)

Zeinab Sobhani
Zeinab Sobhani

Reputation: 381

you can define different engine options for different binds overwriting the apply_driver_hacks and define the options for each of your databases. Forexample, if you want to define different pool classes for different databases:

app.config['SQLALCHEMY_DATABASE_URI'] = "monetdb://..//.."
app.config['SQLALCHEMY_BINDS '] = {
    'pg':       'postgres+psycopg2://..//..'
}
app.config['POOL_CLASS'] = {'monetdb' : StaticPool , "postgres+psycopg2" : QueuePool}


class MySQLAlchemy(SQLAlchemy):
    def apply_driver_hacks(self, app, info, options):
        super().apply_driver_hacks(app, info, options)
        try:
            options['poolclass'] = app.config['POOL_CLASS'][info.drivername]
        except KeyError: #if the pool class is not defined it will be ignored, means that it will use the default option
            pass

db = MySQLAlchemy(app)

Upvotes: 1

Eds_k
Eds_k

Reputation: 1134

it’s just a config option. Here’s ours:

SQLALCHEMY_ENGINE_OPTIONS = {
    "pool_pre_ping": True,
    "pool_recycle": 300,
}

Upvotes: 6

D.joe
D.joe

Reputation: 29

I set {'pool_pre_ping':True} like above!TypeError: Invalid argument(s) 'pool_pre_ping' sent to create_engine(), using configuration MySQLDialect_pymysql/QueuePool/Engine.

Please check that the keyword arguments are appropriate for this combination of components.

Upvotes: 2

r-m-n
r-m-n

Reputation: 15120

it's an open issue: https://github.com/mitsuhiko/flask-sqlalchemy/issues/166

you can try this

class SQLiteAlchemy(SQLAlchemy):
    def apply_driver_hacks(self, app, info, options):
        options.update({
            'isolation_level': 'AUTOCOMMIT', 
            'encoding': 'latin1', 
            'echo': True
        })
        super(SQLiteAlchemy, self).apply_driver_hacks(app, info, options)

db = SQLiteAlchemy(app)

Upvotes: 11

Related Questions