Flask-sqlacodegen
数据库脚本参考
安装依赖
shell
pip install flask-sqlacodegen
运行命令
shell
flask-sqlacodegen "mysql+pymysql://用户名:密码@127.0.0.1/数据库名" --tables 表1,表2 --outfile "自定义文件名.py" --flask
使用emp 作为案例
flask-sqlacodegen "mysql+pymysql://root:root@127.0.0.1/emp" --tables emp,dept,salgrade --outfile "models.py" --flask
使用Python代码操作shell 命令
python
import os
def create_models():
db_url = "mysql+pymysql://root:root@localhost:3306/emp?charset=utf8mb4"
project_path = os.getcwd()
print(project_path)
model_path = os.path.join(project_path, 'models.py')
cmd = 'flask-sqlacodegen --flask {}'.format(db_url)
try:
output = os.popen(cmd)
resp = output.buffer.read().decode(encoding='utf-8')
content = str(resp)
output.close()
# w+ 读写权限
with open(model_path, 'w+', encoding='utf-8') as f:
f.write(content)
print('create models successfully!')
except Exception as e:
print(e)
if __name__ == '__main__':
create_models()
不使用 Flask
sqlacodegen
shell
pip install sqlacodegen
运行shell 命令
shell
# sqlacodegen --tables third_api "mysql+pymysql://username:password@host/db_name" >tmp.py
sqlacodegen --tables emp,dept "mysql+pymysql://root:root@localhost/emp" >test.py