【问题标题】:Flask-Sqlalchemy setup engine configurationFlask-Sqlalchemy 设置引擎配置
【发布时间】:2015-10-12 19:53:28
【问题描述】:

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() 不将这些作为参数。

【问题讨论】:

  • 那么...到底是什么问题?
  • 更新问题。希望现在更有意义。

标签: python flask flask-sqlalchemy


【解决方案1】:

这是一个未解决的问题: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)

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      我像上面一样设置了{'pool_pre_ping':True}!TypeError:无效参数'pool_pre_ping'发送到create_engine(),使用配置MySQLDialect_pymysql/QueuePool/Engine。

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

      【讨论】:

        【解决方案4】:

        您可以为覆盖 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)
        

        【讨论】:

          猜你喜欢
          • 2013-01-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-06-21
          • 2022-12-17
          • 1970-01-01
          • 2013-12-16
          • 2018-12-16
          相关资源
          最近更新 更多