我发现了一个很好的解决方案,它受SQLAlchemy文档中提到的Factory模式和
声明性Mixins的启发。
对于复杂的多级继承方案,需要使用另一种方法
@declared_attr.cascading。
from sqlalchemy import create_enginefrom sqlalchemy.orm import sessionmakerfrom sqlalchemy import Column, Integer, Stringfrom sqlalchemy import metaDatafrom sqlalchemy.ext.declarative import declarative_basefrom flask_sqlalchemy import SQLAlchemySQLALCHEMY_DATAbase_URI = 'sqlite:///' + '/tmp/test_app.db'engine = create_engine(SQLALCHEMY_DATAbase_URI, echo=True)# for vanillabase = declarative_base()# for Flask (import from app once initialized)db = SQLAlchemy()class MachineMixin: __tablename__ = 'machine' id = Column(Integer, primary_key=True) name = Column(String(100)) status = Column(Integer)class ModelFactory: @staticmethod def create(which_model, which_parent): if which_parent == 'flask_sqlalchemy': parent = db.Model elif which_parent == 'pure_sqlalchemy': parent = base # now use type() to interit, fill __dict__ and assign a name obj = type(which_model.__name__ + '_' + which_parent, (which_model, parent), {}) return objtest_scenario = 'pure_sqlalchemy' # 'flask_sqlalchemy'Machine = ModelFactory.create(MachineMixin, test_scenario)if test_scenario == 'flask_sqlalchemy': db.metadata.drop_all(bind=engine) db.metadata.create_all(bind=engine)elif test_scenario == 'pure_sqlalchemy': base.metadata.drop_all(bind=engine) base.metadata.create_all(bind=engine)Session = sessionmaker(bind=engine)session = Session()session.add(Machine(name='Bob', status=1))session.commit()
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)