sqlalchemy對(duì)數(shù)據(jù)庫(kù)表的模型提供了很多易用的方法欺嗤。為了使用這些內(nèi)容午笛,需要將數(shù)據(jù)庫(kù)表按照sqlalchemy識(shí)別的格式創(chuàng)建成Model渣刷,但是一般我們都是在已經(jīng)創(chuàng)建好的數(shù)據(jù)庫(kù)環(huán)境中開發(fā)python代碼,對(duì)于已經(jīng)存在的數(shù)據(jù)庫(kù)表谦趣,可以通過以下方式來生成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
然后,在命令行執(zhí)行
sqlacodegen --outfile /PycharmProjects/項(xiàng)目地址/models.py mysql://數(shù)據(jù)庫(kù)用戶名:數(shù)據(jù)庫(kù)用戶密碼@數(shù)據(jù)庫(kù)地址:數(shù)據(jù)庫(kù)地址/庫(kù)名
詳細(xì)的參數(shù)信息可以查看幫助
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 也有專用的轉(zhuǎn)換工具---
flask-sqlacodegen?
地址:https://pypi.python.org/pypi/flask-sqlacodegen/
一峭梳、安裝過程
如果沒有安裝安裝pymysql舰绘、flask、flask-sqlalchemy請(qǐng)先安裝葱椭。過程如下:
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
三、詳細(xì)參數(shù)可以查看幫助
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)