Skip to content

sqlalchmy动态获取model

126 字小于 1 分钟

2024-12-01

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

# 映射
from sqlalchemy.orm import mapper
from sqlalchemy import Table,MetaData
metadata = MetaData()

def getModel(name, engine):
    """根据name创建并return一个新的model类
    name:数据库表名
    engine:create_engine返回的对象,指定要操作的数据库连接,from sqlalchemy import create_engine
    """
    Base.metadata.reflect(engine)
    table = Base.metadata.tables[name]
    t = type(name, (object,), dict())
    mapper(t, table)
    Base.metadata.clear()
    return t

engine = create_engine('mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8'.format(mysql_user,
                                                                                    mysql_password,
                                                                                    '127.0.0.1',
                                                                                    server.local_bind_port,
                                                                                    mysql_db))
user = getModel("user",engine) # 动态生成