flask sqlalchemy 动态创建表

创建模型

def get_model(suffix):
    class BaseModel(Base):
        __tablename__ = f'table_{suffix}'
        __table_args__ = {'extend_existing': True}

        target_name = db.Column(db.String(64), nullable=False, unique=True, comment="名称")
        target_id = db.Column(db.String(32), comment="ID")
        country = db.Column(db.String(32), comment="国家")
        time = db.Column(db.DateTime, comment='时间')
        content= db.Column(db.Text)
        the_geom = db.Column(Geometry(geometry_type='POINT', srid=4326), comment='经纬度')

    return BaseModel

初始化数据库

@manager.command
def init_db():
    import json
    # 1. 获取数据列表
    with open('data_list.json', 'r') as f:
        ship_list = json.load(f)
    # 2. 动态创建数据库表
    for datain data_list:
        data_id = data['ID']
        get_model(data_id)

    with app.app_context():
        db.create_all(app=app)

    print('create table success')

参考链接

  • https://stackoverrun.com/cn/q/5228815
  • https://www.jianshu.com/p/130bb4b36920

你可能感兴趣的:(数据库,flask,sqlalchemy)