近来有个客户需要远程数据库里面的信息,但是又不想开放主机真实ip,用户密码,数据库用户密码这些信息,就搞了一个丑陋的文件下载网站,把这些信息封装了起来
用到的包flask ,mysql-connector-python,xlwt
实现思路:
1、使用python连接数据库,读取数据
使用mysql.connector模块连接数据库
因语句固定,所以写到了脚本中,未实现用户交互输入,其实是懒
2、将数据进行处理后,写入excel表格
使用xlwt模块写入excel表格
因查出的数据格式和需要的不同,所以需要进行数据预先处理,然后再写入excel
3、通过web浏览器下载excel文件
使用flask框架实现网页登录验证,实现文件下载
通过nginx做代理,提供公网访问
经过一番折腾,终于功能实现,是否有bug,后续用用再说。有感触的几个地方有:
架构:将每个功能写入不同的模块,这样每个功能都可以单独测试,使用if __name__ == ‘__main__‘: test()写测试用例进行调试。当然也可以使用nosetests这样专门的测试模块,不过当时写的时候,还没接触nosetest。。。再加上功能也不复杂,后面也就不打算改写了
mysql数据库连接:可以使用字典存储连接信息,这样对于更换测试环境和生成环境会很方便;使用try语句连接,进行异常处理
try:conn = mysql.connector.connect(**config)except mysql.connector.Error as e:print(‘open database failed !{} ‘.format(e))cursor=conn.cursor()cursor.execute(sql_str)values=cursor.fetchall()
cursor.close()conn.close()
sql语句:使用字典存储语句,key值使用中文字符串,为后续写入excel的中文标签使用,非常方便
查询结果处理:因为查询语句的结果只有记录,没有字段头,所以把查询结果和字段列表进行了拼接,
???????sh_ysh_tou=[(‘名称‘,‘类型‘,‘审核人’,‘创建时间‘,‘任务状态‘),]jg_dict[‘已审核‘] = sh_ysh_tou + jg_dict[‘已审核‘] ???????
写入excel:实现自定义单元格格式。
def newf(data_dict):
#新建文件 ???datatable = xlwt.Workbook(encoding=‘utf-8‘, style_compression=0) ???#加边框 ?????borders = xlwt.Borders() ???borders.left = 1 ???borders.right = 1 ???borders.top = 1 ???borders.bottom = 1 ???borders.bottom_colour=0x3A ????#定义样式 ???style = xlwt.XFStyle() ???style1 = xlwt.XFStyle() ???style.borders = borders ???style1.borders = borders
#自定义日期格式 ???style1.num_format_str=‘YYYY/M/D h:mm:ss‘
???for k in data_dict:
#新建标签 ???????newsheet = datatable.add_sheet(k, cell_overwrite_ok=True) ?#新建excel文档sheet ???????x=0 ???????for l in data_dict[k]: ???????????y=0 ???????????for i in l: ???????????????if(y == 3): ???????????????????newsheet.write(x, y, i, style1) ???????????????else: ???????????????????newsheet.write(x, y, i, style) ???????????????y+=1 ???????????x+=1
#设置列宽 ???????four_col=newsheet.col(3) ???????first_col=newsheet.col(0) ???????third_col=newsheet.col(2) ???????first_col.width=256*40 ???????third_col.width=256*15 ???????four_col.width=256*20
#保存文件 ???datatable.save(‘结果‘+‘.xls‘)
web框架:用到了 Flask,request,send_from_directory
app = Flask(__name__)@app.route(‘/signin‘, methods=[‘POST‘])def signin(): ???# 需要从request对象读取表单内容: ???if request.form[‘username‘]==‘admin‘ and request.form[‘password‘]==‘password‘: ???????chaxun() ???????return send_from_directory(os.getcwd(),‘结果.xls‘,as_attachment=True)if __name__ == ‘__main__‘: ???app.run()
越用,越觉得python优雅!嘿嘿
一个丑陋的文件下载网站
原文地址:https://www.cnblogs.com/mathprice/p/9228215.html