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


    准备:

    安装插件

    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))
    )
  • 相关阅读:
    Linux系统设置中文
    跟着小白学Linux基础命令系列
    Linux小白基础练习题
    htop命令超级好玩用法
    sed命令用法
    Linux三剑客grep命令的使用技巧
    Linux忘记密码如何修改密码
    决心书
    Linux无法上网,ping不通百度的解决方法
    AE 创建shp图层
  • 原文地址:https://www.cnblogs.com/mofujin/p/13877639.html
Copyright © 2020-2023  润新知