如何告诉SQLAlchemy我想要InnoDB用于整个数据库?

时间:2014-09-10 16:35:30

标签: mysql sqlalchemy innodb flask-sqlalchemy

我正在使用(Flask-)SQLAlchemy管理MySQL数据库,我想明确地对所有表使用mysql_engine = InnoDB。有没有办法告诉我想要的数据库连接,所以我不必为每个表重复它?提前谢谢。

1 个答案:

答案 0 :(得分:1)

您使用声明性扩展吗?如果是这样,您可以使用简单的元类(从here中窃取)设置默认__table_args__

def TableArgsMeta(table_args):

    class _TableArgsMeta(declarative.DeclarativeMeta):

        def __init__(cls, name, bases, dict_):
            if (    # Do not extend base class
                    '_decl_class_registry' not in cls.__dict__ and 
                    # Missing __tablename_ or equal to None means single table
                    # inheritance — no table for it (columns go to table of
                    # base class)
                    cls.__dict__.get('__tablename__') and
                    # Abstract class — no table for it (columns go to table[s]
                    # of subclass[es]
                    not cls.__dict__.get('__abstract__', False)):
                ta = getattr(cls, '__table_args__', {})
                if isinstance(ta, dict):
                    ta = dict(table_args, **ta)
                    cls.__table_args__ = ta
                else:
                    assert isinstance(ta, tuple)
                    if ta and isinstance(ta[-1], dict):
                        tad = dict(table_args, **ta[-1])
                        ta = ta[:-1]
                    else:
                        tad = dict(table_args)
                    cls.__table_args__ = ta + (tad,)
            super(_TableArgsMeta, cls).__init__(name, bases, dict_)

    return _TableArgsMeta

用法:

Base = declarative_base(
            name='Base',
            metaclass=TableArgsMeta({'mysql_engine': 'InnoDB'}))