美文网首页
Python用sqlacodegen将存在的数据库表转化成mod

Python用sqlacodegen将存在的数据库表转化成mod

作者: 佑___ | 来源:发表于2019-05-23 15:17 被阅读0次

sqlalchemy对数据库表的模型提供了很多易用的方法。为了使用这些内容,需要将数据库表按照sqlalchemy识别的格式创建成Model,但是一般我们都是在已经创建好的数据库环境中开发python代码,对于已经存在的数据库表,可以通过以下方式来生成models.py

注:sqlacodegen :地址:https://pypi.python.org/pypi/sqlacodegen/

   他是sqlautocode 的替换版本,sqlautocode 的地址https://pypi.python.org/pypi/sqlautocode

  sqlautocode的最高版本是0.7,

  sqlacodegen 支持SQLAlchemy 0.6.x - 1.0.x

一、安装

可以用pip安装

pip install sqlacodegen

或者用easy_install 安装

easy_install sqlacodegen

然后,在命令行执行

sqlacodegen --outfile /PycharmProjects/项目地址/models.py mysql://数据库用户名:数据库用户密码@数据库地址:数据库地址/库名

详细的参数信息可以查看帮助

sqlacodegen--help

显示如下

-h, --help show this help message and exit

--version print the version number and exit

--schema SCHEMA load tables from an alternate schema

--tables TABLES tables to process (comma-separated, default: all)

--noviews ignore views

--noindexes ignore indexes

--noconstraints ignore constraints

--nojoined don't autodetect joined table inheritance

--noinflect don't try to convert tables names to singular form

--noclasses don't generate classes, only tables

--outfile OUTFILE file to write output to (default: stdout)

----------------------------------------------------------------------------------

在Flask中使用SQLAlchemy 也有专用的转换工具---

flask-sqlacodegen 

地址:https://pypi.python.org/pypi/flask-sqlacodegen/

一、安装过程

如果没有安装安装pymysql、flask、flask-sqlalchemy请先安装。过程如下:

pip install pymysql

pip install flask

pip install flask-sqlalchemy

***安装flask-sqlacodegen

二、使用

pip install flask-sqlacodegen

flask-sqlacodegen --outfile models.py --flask mysql+pymysql://username:passwd@IP/db_name

三、详细参数可以查看帮助

optional arguments:

-h, --help show this help message and exit

--version print the version number and exit

--schema SCHEMA load tables from an alternate schema

--tables TABLES tables to process (comma-separated, default: all)

--noviews ignore views

--noindexes ignore indexes

--noconstraints ignore constraints

--nojoined don't autodetect joined table inheritance

--noinflect don't try to convert tables names to singular form

--noclasses don't generate classes, only tables

--outfile OUTFILE file to write output to (default: stdout)

--nobackrefs don't include backrefs

--flask use Flask-SQLAlchemy columns

--ignore-cols IGNORE_COLS

Don't check foreign key constraints on specified

columns (comma-separated)

相关文章

网友评论

      本文标题:Python用sqlacodegen将存在的数据库表转化成mod

      本文链接:https://www.haomeiwen.com/subject/rjxbzqtx.html