Python用sqlacodegen将存在的数据库表转化成model.py

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 资源大全中文版 我想很多程序员应该记得 GitHub 上有一个 Awesome - XXX 系列...
    小迈克阅读 3,063评论 1 3
  • # Awesome Python [![Awesome](https://cdn.rawgit.com/sindr...
    emily_007阅读 2,228评论 0 3
  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 9,516评论 0 13
  • 1.A simple master-to-slave replication is currently being...
    Kevin关大大阅读 6,014评论 0 3
  • 虽然每天早起,这么早出门还是不常有的。六点四十,娘俩收拾停当走出楼门。天上看不见一颗星星,夜色比晚上更浓,黎明前的...
    王小唐阅读 442评论 4 6