flask反向生成模版(models)

2021-12-06  本文已影响0人  叶叶阿姨

代码实现 还可指定生产文件名以及路径

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

import os

HOST = 'localhost'  # 数据库地址
DATABASE = 'inspection1234'  # 数据库名
USERNAME = 'root'  # 数据库用户
PASSWORD = '123456'  # 数据库用户密码
DB_URI = "postgresql://{username}:{password}@{host}/{db}".format(username=USERNAME, password=PASSWORD, host=HOST, db=DATABASE)



def gen_models():
    db_url = DB_URI
    #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, 'models1.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()
上一篇下一篇

猜你喜欢

热点阅读