1. 概述
通过python连接本地数据库,创建Html网页,生成数据库的表清单及每张表的结构、修改语句等。步骤如下:
1. 从git远程拉取代码 2. 读取数据库每张表结构,生成md文档 3. 为表结构md文档添加change log 4. 每张表结构md转为html 5. 构建首页导航
2. 代码实现
2.1 从git远程拉取代码
def downloadGit(download_path,clone_path,branch_name):
# 从远程仓库更新代码
if os.listdir(download_path):
print('git pull to ', download_path)
repo = Repo(download_path)
## 切换到最新分支
repo.git.checkout(branch_name)
repo.git.pull()
cur_branch = repo.git.branch()
print('current branch ', cur_branch,' 代码正在拉取中...')
# 从远程仓库下载代码
else:
print('clone from ', clone_path)
Repo.clone_from(clone_path,to_path=download_path,branch='master')
2.2 读取数据库每张表结构,生成md文档
数据库表结构查询,生成表结构md文档
1. 连接数据库
2. 读取表名
3. 遍历表,读取表结构
4. 每张表保存为md文档
import pymysql
import os
print('hello world——convertSqlToMd')
########################### 1. 连接数据库 #############################
def connectSql():
# 打开数据库连接
db = pymysql.connect(
host="host_name",
port=port_name,
user='user_name',
password='password_name',
database='database_name'
)
db = connectSql()
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# 使用 execute() 方法执行 SQL 查询
cursor.execute("SELECT VERSION()")
# 使用 fetchone() 方法获取单条数据fetchone/所有数据fetchall
data = cursor.fetchall()
print ("Database version : %s " % data)
# 关闭数据库连接
db.close()
########################### 2. 读取表名 ##################################
selTables = "select table_name from information_schema.tables where table_schema='database_name' "
cursor.execute(selTables)
tableNames = cursor.fetchall()
########################### 3. 遍历表,读取表结构 #############################
########################### 4. 每张表保存为md文档 #############################
colName= '| Field |Type | Collation | Null |Key | Default | Extra |Privileges | Comment |'
colDel = '| ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- |'
try:
for tableName in tableNames:
# 遍历每张表
tableName = tableName[0]
# 描述表结构
desTable = "show full columns from " + tableName
# 执行表结构读取
cursor.execute(desTable)
tableStruc = cursor.fetchall()
# 创建md文档,解析格式化数据
with open(os.path.join(path , '%s.md'%tableName), 'w') as f:
# 增加页面标题
print(os.path.join(path , '%s.md'%tableName))
f.writelines('## %s'%tableName + '\n')
f.writelines('------ \n')
f.writelines(colName + '\n')
f.writelines(colDel + '\n')
# 遍历该表结构每行
for i in tableStruc:
i = list(i)
removeNone = ['null' if i == None else i for i in i]
line = '|' + ' | '.join(removeNone) + ' | '
f.writelines(line + '\n')
f.close()
2.3 为表结构md文档添加change log
组件代码结构如下,遍历该文件夹下所有时间日期的文件夹中的sql文件,sql文件名与实际表名一致,方便查找该表md文档,直接写入sql语句
import datetime
import os
'''
1. 读取 DbScript组件 脚本语句
2. 添加到已有md文档中
'''
def addChangeLog(dbpath):
### md文档地址
md_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'mySqlTabsMd')
listdir = os.listdir(dbpath)
listdir.remove('deploy.yaml')
listdir.sort(reverse=True)
print('迭代文件夹:',listdir)
for timedir in listdir:
### 遍历当前日期文件夹下 每个sql文件
for foldername , subfolders , filenames in os.walk(dbpath +'\%s'%timedir):
for filename in filenames:
if filename != 'rollback.sql':
####### 读取表名 及 Sql 语句
tablename = filename.split('.')[0].split('-')[0]
filepath = os.path.join(foldername, filename)
sqlfile = open(filepath, "r",encoding='utf-8').read()
#### 将 change log 写进对应表md中
try:
md_file_path = os.path.join(md_path,tablename+'.md')
with open(md_file_path,'a') as f:
# 添加 时间
f.writelines('\n')
f.writelines(' - '+ timedir + '\n')
f.writelines("```mysql \n")
f.write(sqlfile+ '\n')
f.writelines("```")
f.close()
except :
pass
2.4 每张表结构md转为html
将每一个表结构md文档转化为html文件,方便首页导航直接跳转。其中exts为markdown类型扩展包,能够将md文档中的样式正常加载转换为Html的样式,github.css及dracula.css为样式文件,使html样式正常/代码高亮显示等..
exts = ['markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.tables', 'markdown.extensions.toc']
'''
md文档转为html格式
1. 格式化html页面
2. md————>html
3. 输出保存html
'''
import markdown
import os
print('hello world——md2html')
####### 1. 读取文件
def readFile(exts):
path = os.path.dirname(os.path.abspath(__file__))
print(path)
### 变量定义
html = '''<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimal-ui">
<title>{}</title>
<link rel="stylesheet" href="../css/github.css">
<link rel="stylesheet" href="../css/dracula.css">
</head>
<body>
<article class="markdown-body">
{}
</article>
</body>
</html>
'''
for input_file in os.listdir(path+'\mySqlTabsMd'):
table_name = input_file.split('.')[0]
output_file =os.path.join(path,'mySqlTabsHtml' , table_name +'.html')
print(input_file,output_file)
md_file_path = os.path.join(path,'mySqlTabsMd',input_file)
md_file = open(md_file_path,"r")
html_body_txt = md_file.read()
md_file.close()
md2html(table_name,html_body_txt,output_file,html,exts)
####### 2. md文档转换,html文件保存
####### 参数:标题,Htmlbody内容,输出路径,html结构参数,md扩展包
def md2html(title,html_body_txt,output_file,html,exts):
### md文件转为 html
md = markdown.Markdown(extensions = exts)
html_body = md.convert(html_body_txt)
### html文件保存
html = html.format(title, html_body)
html_file = open(output_file,"w",encoding='utf-8')
html_file.write(html)
html_file.close()
2.5 构建首页导航
读取数据库所有表名,循环换行写入index.md,调用md2html 方法,生成首页的Html文件
# 执行sql语句
db = connectSql()
cursor = db.cursor()
selTables = "select table_name from information_schema.tables where table_schema='zytbmdb' "
cursor.execute(selTables)
tableNames = cursor.fetchall()
注意, title为表名,最好md文档也保持同名
for i in tableNames:
title = i[0]
link = 'mySqlTabsHtml/%s.html'%title
content = "- [{}]({})".format(title,link)
print(content)
f.write(content+'\n')