在操作数据库的业务里,我们系统采用了orm框架 ,避免了过多的写sql,利用实体对数据库进行操作
需求: 账户系统里的account表是进行了分表,分表规则为accountid进行20取模,测试环境分为多套环境
a,b,c环境,需要在对数据库操作时区分环境
1、使用sqlalchemy
base = declarative_base()
def get_model(name,env):
if. env =='a':
engine = create_engine('mysql+pymysql.....这里是a环境的配置')
elif env =='b':
.......
base.metadata.reflect(engine)
table = base.metadata.table[name]
mapper(t, table)
Base.metadata.clear()
return t
当然这里的参数name是需要额外做处理的,因为存在分表的规则,所以需要在先得到具体的表名再找到对应的model
2、使用flask_sqlalchemy
通过元类编程找出对应的model
class Account(object):
__mapper = {}
@staticmethod
def model( account_id, env = 'c'):
if env == 'c':
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:root@xxxx'
else :
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:root@xxx'
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
db =SQLAlchemy(app)
table_index = account_id%20
class_name='account_%d' % table_index
ModelClass = Account.__mapper.get(class_name, None)
if ModelClass is None:
ModelClass = type(class_name, (db.Model,),
{
'__module__':__name__,
'__name__':class_name,
'__tablename__':'account_%d' % table_index,
'account_id':db.Column(db.Integer, primary_key=True),
'main_id':db.Column(db.Integer)
})
Account.__mapper[class_name]=ModelClass
cls = ModelClass()
cls.account_id = account_id
return cls