使用flask-sqlacodegen
先通過(guò)在數(shù)據(jù)庫(kù)創(chuàng)建數(shù)據(jù)表格信息,
再將在數(shù)據(jù)庫(kù)表里的數(shù)據(jù)同步到模型庫(kù)的方法。
第一步復(fù)制該代碼到數(shù)據(jù)庫(kù)管理器運(yùn)行,右鍵對(duì)應(yīng)數(shù)據(jù)庫(kù)選擇命令列界面,即可在數(shù)據(jù)庫(kù)中創(chuàng)建表
CREATE TABLE `app_access_log` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`uid` bigint(20) NOT NULL DEFAULT '0' COMMENT 'uid',
`referer_url` varchar(255) NOT NULL DEFAULT '' COMMENT '當(dāng)前訪問(wèn)的refer',
`target_url` varchar(255) NOT NULL DEFAULT '' COMMENT '訪問(wèn)的url',
`query_params` text NOT NULL COMMENT 'get和post參數(shù)',
`ua` varchar(255) NOT NULL DEFAULT '' COMMENT '訪問(wèn)ua',
`ip` varchar(32) NOT NULL DEFAULT '' COMMENT '訪問(wèn)ip',
`note` varchar(1000) NOT NULL DEFAULT '' COMMENT 'json格式備注字段',
`created_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `idx_uid` (`uid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用戶訪問(wèn)記錄表';
DROP TABLE IF EXISTS `app_error_log`;
CREATE TABLE `app_error_log` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`referer_url` varchar(255) NOT NULL DEFAULT '' COMMENT '當(dāng)前訪問(wèn)的refer',
`target_url` varchar(255) NOT NULL DEFAULT '' COMMENT '訪問(wèn)的url',
`query_params` text NOT NULL COMMENT 'get和post參數(shù)',
`content` longtext NOT NULL COMMENT '日志內(nèi)容',
`created_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '插入時(shí)間',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='app錯(cuò)誤日表';
第二步使用以下代碼即可在flask項(xiàng)目中生成相應(yīng)的py文件模型代碼。
flask-sqlacodegen 'mysql://root:root@127.0.0.1/food_db' --tables app_access_log --outfile "common/models/log/AppAccessLog.py" --flask
flask-sqlacodegen 'mysql://root:root@127.0.0.1/food_db' --tables app_error_log --outfile "common/models/log/AppErrorLog.py" --flask
# coding: utf-8
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class AppErrorLog(db.Model):
__tablename__ = 'app_error_log'
id = db.Column(db.Integer, primary_key=True)
referer_url = db.Column(db.String(255), nullable=False, server_default=db.FetchedValue(), info='當(dāng)前訪問(wèn)的refer')
target_url = db.Column(db.String(255), nullable=False, server_default=db.FetchedValue(), info='訪問(wèn)的url')
query_params = db.Column(db.Text, nullable=False, info='get和post參數(shù)')
content = db.Column(db.String, nullable=False, info='日志內(nèi)容')
created_time = db.Column(db.DateTime, nullable=False, server_default=db.FetchedValue(), info='插入時(shí)間')
第三步,對(duì)py模型庫(kù)根據(jù)項(xiàng)目需要進(jìn)行相應(yīng)的配置更改
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-770522.html
如圖所示即將db從application.py中導(dǎo)入而不是在模型庫(kù)中創(chuàng)建db。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-770522.html
到了這里,關(guān)于模型庫(kù)創(chuàng)建-使用flask-sqlacodegen的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!