准备:
安装插件
pip install flask-sqlacodegen
1.目录介绍
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)) )