zoukankan      html  css  js  c++  java
  • 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))
    )
  • 相关阅读:
    Win7+Ubuntu11.10(EasyBCD硬盘安装)
    hdu 3661 Assignments
    hdu 1128 Self Numbers
    CF 152 B. Chilly Willy
    hdu 1754 I Hate It
    A survey of wireless network simulation and/or emulation software for use in higher education
    How to Fix Packet Loss: Causes, Simple Solutions & Top Tools
    getchar函数
    C++“左值”和“右值”
    stdio.h中的stdio
  • 原文地址:https://www.cnblogs.com/mofujin/p/13877639.html
Copyright © 2011-2022 走看看