1. from sqlalchemy import create_engine
  2. from sqlalchemy.orm import sessionmaker
  3. from sqlalchemy.ext.declarative import declarative_base
  4. Base = declarative_base()
  5. # 映射
  6. from sqlalchemy.orm import mapper
  7. from sqlalchemy import Table,MetaData
  8. metadata = MetaData()
  9. def getModel(name, engine):
  10. """根据name创建并return一个新的model类
  11. name:数据库表名
  12. engine:create_engine返回的对象,指定要操作的数据库连接,from sqlalchemy import create_engine
  13. """
  14. Base.metadata.reflect(engine)
  15. table = Base.metadata.tables[name]
  16. t = type(name, (object,), dict())
  17. mapper(t, table)
  18. Base.metadata.clear()
  19. return t
  20. engine = create_engine('mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8'.format(mysql_user,
  21. mysql_password,
  22. '127.0.0.1',
  23. server.local_bind_port,
  24. mysql_db))
  25. user = getModel("user",engine) # 动态生成

欢迎关注我的微信公众号互相交流

qrcode_for_gh_b8fe229d156f_258 (1).jpg