最近工作因为要计算一些数据,为方便自己查看,就用flask写了小项目(叫项目其实都不好意思,其实就是一个小小功能),主要功能是根据一些机器sn去查询每台机器的费用情况,在这个过程中发现flask还真非常好用,很适合入门学习,今天就从头开始讲起,具体如何使用,本次我用的数据库是sqlite3,sqlite3是是pyhton标准库模块,调用起来比较方便,同时做些小型项目也足够了,如果要转到其他数据库上也很方便,废话少说,咱们还是开始咱们今天的愉快旅程:
1、创建数据库库,我自己拿到的是excle表格,作为原始数据要入到库里,因为sqlite无法直接导入excel表,所以我们要做一个小小的改动,把表格转换成csv格式,然后就可以了: 打开excel表格,点击文件—另存为—选择csv格式,点保存,这个表就是csv格式了,同时为了让sqlite支持中文,还要做一个小操作,默认你导入到sqlite3中是显示不了中文的,点击文件,然后右键–选择记事本打开,在保存处选择utf-8编码,然后我们的原始数据就算是弄好了,下一步导入到sqlite中,在导入前先要建立一个初始化脚本init_db.sql,内容如下:
1 2 3 4 5 6 7 |
drop table if exists zichan; create table zichan ( sn varchar(30) not null, money REAL not null, project varchar(30) not null, pro_id INTEGER not null ); |
建库:
1 |
sqlit3 sndb < init_db.sql |
这样就库就建好了,接下来导入数据:
1 2 3 4 5 6 7 8 |
# sqlite3 sndb SQLite version 3.6.20 Enter ".help" for instructions Enter SQL statements terminated with a ";" sqlite> .table zichan sqlite> .mode csv sqlite> .import /home/query_sn/data.csv zichan |
这样所有的数据就全部建好了,我们数据方面的工作就到此结束了,接下来进入我们代码环节。
2、第二部分,flask主角上场,在正式进入代码前,我们先对 这个小功能的目录结做一个简单介绍,如下:
├── query_sn
│ ├── static
│ │ ├──style.css
│ │
│ │
│ ├── templates
│ └── sndb
每个文件我介绍下,静态文件放在static中,模板文件放在templates中,cal.html放的是要查下的结果,show_pro.html展示的是分类结果,cal.py是主程序文件,包括数据库的链接,视图函数等,首先我们来看cal.py这个文件内容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
#coding=utf-8 import os import sys reload(sys) sys.setdefaultencoding('utf8') from sqlite3 import dbapi2 as sqlite3 from flask import Flask, g,url_for,request,render_template app = Flask(__name__) app.config.update(dict( DATABASE=os.path.join(app.root_path, 'sndb'), DEBUG=True )) app.config.from_envvar('FLASKR_SETTINGS', silent=True) def connect_db(): rv = sqlite3.connect("/home/query_sn/sndb") rv.text_factory = str rv.row_factory = sqlite3.Row return rv def get_db(): if not hasattr(g, 'sqlite_db'): g.sqlite_db = connect_db() return g.sqlite_db @app.teardown_appcontext def close_db(error): if hasattr(g, 'sqlite_db'): g.sqlite_db.close() @app.route('/',methods=['GET', 'POST']) def calmo(): total = None sn = [] db = get_db() sum_list = [] query = """select * from zichan where sn = ?""" if request.method == 'POST': data = request.form['sn'] sn = data.split() for s in sn: cur = db.execute(query, (s,)) for sn,money,project,pro_id in cur.fetchall(): sum_list.append(money) total = sum(sum_list) return render_template('cal.html', total=total) @app.route('/show',methods=['GET', 'POST']) def show_pro(): all_pro = None db = get_db() query = """select project, SUM(money) from zichan group by project""" cur = db.execute(query) allpro = cur.fetchall()[1:] return render_template('show_pro.html', allpro=allpro) if __name__ == '__main__': app.run() |
代码中数据库链接部分不细说了,从视图函数开始,calmo() 这个函数主要是从表单中获取用户输入,然后计算结果,再返回给用户,render_template是将结果渲染,
show_pro()视图函数展示所有分类结果,@app.route是装饰器, flask自带的,用户表示用户输入的url具体由那个视图函数做处理。
接下来看模板内容cal.html:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<!doctype html> <html> <head> <title>cal</title> <link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <h1>费用计算</h1> <form action="{{ url_for('calmo') }}" method=post> <dl> <dt>sn: <dd><input type=text name=sn> {# <textarea name="a" style="width:200px;height:80px;"></textarea> #} <dd><input type=submit value=submit> </dl> </form> <ul> 计算结果 <table border=1> <tr><td>{{ total }}</td></tr> </table> <p><a href=http://x.x.x.x/show>展示所有费用</a> </ul> </body> </html> |
show_pro.html内容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<!doctype html> <html> <head> <title>cal</title> <link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <h1>费用计算</h1> <form action="{{ url_for('show_pro') }}" method=post> </form> <ul> {% for project,money in allpro %} <table border=1> <tr><td>{{ project }}</td><td>{{ money }}</td></tr> </table> {% else %} <li><em>error</em> {% endfor %} </ul> <p><a href=http://x.x.x.x>返回</a> </body> </html> |
跳转和返回我用的绝对地址,大家写的时候不一定这么做,模板内容也都非常简单,什么继承、宏什么都都没用到,结合视图函数就很容易理解,基本思想是视图函数传过来的数据,由模板进行展示。
写到这基本就没有了,静态文件我就不贴了,因为我是用的其它站点的css,大家也可以上网上自己找喜欢的样式,好了,这篇就到这里了,算是学习flask的开门篇,另外自己也在学习中,非常欢迎志同道合的朋友一起研究学习,感谢观看这篇文章。