准备:

安装插件

pip install flask-sqlacodegen

1.目录介绍

Flask 根据mysql数据库表反向生成 model的py文件

 

 2.my_test.py 运行反向生成models 文件 右键run运行即可

# !/usr/bin/python
# -*- coding: utf-8 -*-
"""
Generate models from database
Created date: 2020/10/26
Author: Aangenl
"""

import os


def gen_models():
    db_url = "mysql://root:123456@localhost:3306/web_db?charset=utf8"
    #plants_path = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
    plants_path = os.getcwd()
    print(plants_path)
    model_path = os.path.join(plants_path, 'models','models.py')
    cmd = 'flask-sqlacodegen --flask {}'.format(db_url)
    try:
        output = os.popen(cmd)
        content = str(output.read())
        with open(model_path, 'w+') as f:
            f.write(content)
        print('Generated database models successfully')
    except Exception as e:
        print(e)


if __name__ == '__main__':
    gen_models()

3.生成models.py文件

# coding: utf-8
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()


class Person(db.Model):
    __tablename__ = 'persons'

    Id = db.Column(db.Integer, primary_key=True)
    Name = db.Column(db.String(255), nullable=False)
    Address = db.Column(db.String(255))
    City = db.Column(db.String(255))


class Tal(db.Model):
    __tablename__ = 'tal'

    id = db.Column(db.Integer, primary_key=True)
    val = db.Column(db.String(255))


t_users = db.Table(
    'users',
    db.Column('username', db.String(255)),
    db.Column('password', db.String(255))
)

 

相关文章:

  • 2021-05-08
  • 2021-05-21
  • 2022-02-18
  • 2022-01-25
  • 2022-12-23
  • 2022-12-23
  • 2021-11-20
猜你喜欢
  • 2022-02-13
  • 2022-01-07
  • 2022-02-08
  • 2022-12-23
  • 2021-12-30
  • 2021-06-26
  • 2022-03-05
相关资源
相似解决方案