1.2 连接至数据库
import pymssql
conn = pymssql.connect(server="xxx.xxx.xxx.xxx",user="xxx",password="xxx",database="xxx")
这里,server为数据库服务器名称或IP,user为用户名,password为密码,database为数据库名称。
2 pandas读写数据库 在python连接好数据库后,pandas可以利用read_sql()方法将数据读入DataFrame。这里可以看一下代码。
import pandas as pd
#这里即遵循sql语句规则
sql = "select * from 要查询的表格"
df0 = pd.read_sql(sql,conn)
df=pd.DataFrame(df0)
pandas的表展现在flask html中
from flask import Flask, request, render_template, session, redirect
import numpy as np
import pandas as pd
app = Flask(__name__)
df = pd.DataFrame({'A': [0, 1, 2, 3, 4],
'B': [5, 6, 7, 8, 9],
'C': ['a', 'b', 'c--', 'd', 'e']})
@app.route('/', methods=("POST", "GET"))
def html_table():
return render_template('simple.html', tables=[df.to_html(classes='data', header="true")])
if __name__ == '__main__':
app.run(host='0.0.0.0')
页面里简单加一个for就可以了
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% for table in tables %}
{{ table|safe }}
{% endfor %}
</body>
</html>
现在加入数据库:
import pymssql
@app.route('/db', methods=("POST", "GET"))
def html_table():
conn = pymssql.connect(server="10.179.236.72", user="BOSTON\qa.testauto", password="test@456",
database="TestAutomation")
sql = """ select top 20 environment,member_id,username, JSON_VALUE(detail,'$.level_code') as level,JSON_VALUE(detail,'$.partner') as partner,tags, created_by,created_on from ec_test_accounts
where environment='UAT'
and JSON_VALUE(detail,'$.partner')='Cehk'
and JSON_VALUE(detail,'$.level_code')='0A'
order by created_on desc
"""
df0 = pd.read_sql(sql, conn)
df = pd.DataFrame(df0)
return render_template('simple.html', tables=[df.to_html(classes='data', header="true")])
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=6000)
展现结果如下:
pandas 如何直接转化成html. pandas中有方法to_html 如下的例子是将excel的数据,转化成html
#!/usr/bin/env Python
# coding=utf-8
import pandas as pd
import codecs
xd = pd.ExcelFile('/Users/wangxingfan/Desktop/1.xlsx')
df = xd.parse()
with codecs.open('/Users/wangxingfan/Desktop/1.html','w','utf-8') as html_file:
html_file.write(df.to_html(header = True,index = False))
或者可以改写一下html.
import pandas as pd
import numpy as np
pd.set_option('display.width', 1000)
pd.set_option('colheader_justify', 'center')
np.random.seed(6182018)
demo_df = pd.DataFrame({'date': np.random.choice(pd.date_range('2018-01-01', '2018-06-18', freq='D'), 50),
},
columns=['date', 'analysis_tool', 'num1', 'database', 'num2', 'os', 'num3', 'bool']
)
pd.set_option('colheader_justify', 'center') # FOR TABLE <th>
html_string = '''
<html>
<head><title>HTML Pandas Dataframe with CSS</title></head>
<link rel="stylesheet" type="text/css" href="df_style.css"/>
<body>
{table}
</body>
</html>.
'''
# OUTPUT AN HTML FILE
with open('myhtml.html', 'w') as f:
f.write(html_string.format(table=demo_df.to_html(classes='mystyle')))
这样就很方便的操作html了。