Flask-Sqlalchemy设置引擎配置

时间:2015-10-12 19:53:29

标签: python flask flask-sqlalchemy

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

我希望使用以下参数设置客户配置引擎: http://docs.sqlalchemy.org/en/rel_0_9/core/engines.html

我使用Flask-SqlAlchemy文档中描述的方式:

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

编辑: 如何在这种配置中传递以下引擎参数:

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

方法:SQLAlchemy()不会将这些作为参数。

4 个答案:

答案 0 :(得分:6)

这是一个悬而未决的问题:https://github.com/mitsuhiko/flask-sqlalchemy/issues/166

你可以试试这个

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)

答案 1 :(得分:0)

我如上所述设置{'pool_pre_ping':True}!TypeError:使用配置'pool_pre_ping'发送到create_engine()的无效参数MySQLDialect_pymysql/QueuePool/Engine

请检查关键字参数是否适合此组件组合。

答案 2 :(得分:0)

它只是一个配置选项。这是我们的:

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

答案 3 :(得分:0)

您可以为不同的绑定定义不同的引擎选项,从而覆盖apply_driver_hacks,并为每个数据库定义选项。例如,如果要为不同的数据库定义不同的池类:

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)