Python拥有对SQlite的内置支持。 SQlite3模块随附Python发行版。在本节中,我们将看到Flask应用程序如何与SQLite进行交互。
创建一个SQLite数据库 ‘database.db’并在其中创建一个student表。
# Filename : example.py # Copyright : 2020 By Nhooo # Author by : www.528045.com # Date : 2020-08-08 import sqlite3 conn = sqlite3.connect('database.db') print "Opened database successfully"; conn.execute('CREATE TABLE students (name TEXT, addr TEXT, city TEXT, pin TEXT)') print "Table created successfully"; conn.close()
Flask应用程序有三个视图函数。
第一个new_student()函数绑定到URL规则(‘/addnew’)。 它呈现包含学生信息表单的HTML文件。
# Filename : example.py # Copyright : 2020 By Nhooo # Author by : www.528045.com # Date : 2020-08-08 @app.route('/enternew') def new_student(): return render_template('student.html')
‘student.html’的HTML脚本如下 -
# Filename : example.py # Copyright : 2020 By Nhooo # Author by : www.528045.com # Date : 2020-08-08 <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Flask示例</title> </head> <body> <form action = "{{ url_for('addrec') }}" method = "POST"> <h3>学生信息</h3> 姓名<br> <input type = "text" name = "nm" /></br> 地址<br> <textarea name = "add" /><br> 城市<br> <input type = "text" name = "city" /><br> 邮编<br> <input type = "text" name = "pin" /><br> <input type = "submit" value = "提交" /><br> </form> </body> </html>
可以看出,表单数据发布到绑定addrec()函数,对应于URL => ‘/addrec’ 。
这个addrec()函数通过POST方法检索表单的数据并插入到学生表中。 与插入操作中的成功或错误相对应的消息呈现为’result.html’。
# Filename : example.py # Copyright : 2020 By Nhooo # Author by : www.528045.com # Date : 2020-08-08 @app.route('/addrec',methods = ['POST', 'GET']) def addrec(): if request.method == 'POST': try: nm = request.form['nm'] addr = request.form['add'] city = request.form['city'] pin = request.form['pin'] with sql.connect("database.db") as con: cur = con.cursor() cur.execute("INSERT INTO students (name,addr,city,pin) VALUES (?,?,?,?)",(nm,addr,city,pin) ) con.commit() msg = "Record successfully added" except: con.rollback() msg = "error in insert operation" finally: return render_template("result.html",msg = msg) con.close()
result.html 的HTML脚本包含显示插入操作结果的转义语句{{msg}}。
# Filename : example.py # Copyright : 2020 By Nhooo # Author by : www.528045.com # Date : 2020-08-08 <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Flask示例</title> </head> <body> 操作结果 : {{ msg }} <h2><a href = "/">返回主页</a></h2> </body> </html>
该应用程序包含由URL => ‘/list’表示的另一个list()函数。 它将“行”填充为包含学生表中所有记录的MultiDict对象。 这个对象传递到 list.html 模板。
# Filename : example.py # Copyright : 2020 By Nhooo # Author by : www.528045.com # Date : 2020-08-08 @app.route('/list') def list(): con = sql.connect("database.db") con.row_factory = sql.Row cur = con.cursor() cur.execute("select * from students") rows = cur.fetchall(); return render_template("list.html",rows = rows)
这个list.html是一个模板,它遍历行集合并在HTML表格中呈现数据。
# Filename : example.py # Copyright : 2020 By Nhooo # Author by : www.528045.com # Date : 2020-08-08 <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Flask示例</title> </head> <body> <table border = 1> <thead> <td>改名</td> <td>地址</td> <td>城市</td> <td>编码</td> </thead> {% for row in rows %} <tr> <td>{{row["name"]}}</td> <td>{{row["addr"]}}</td> <td>{{row["city"]}}</td> <td>{{row['pin']}}</td> </tr> {% endfor %} </table> <a href = "/">返回主页</a> </body> </html>
最后,URL => ‘/‘规则呈现一个’home.html’作为应用程序的入口点。
# Filename : example.py # Copyright : 2020 By Nhooo # Author by : www.528045.com # Date : 2020-08-08 @app.route('/') def home(): return render_template('home.html')
这里是Flask-SQLite应用程序的完整代码。
# Filename : example.py # Copyright : 2020 By Nhooo # Author by : www.528045.com # Date : 2020-08-08 from flask import Flask, render_template, request import sqlite3 as sql import sqlite3 app = Flask(__name__) @app.route('/') def home(): return render_template('home.html') @app.route('/enternew') def new_student(): return render_template('student.html') @app.route('/addrec',methods = ['POST', 'GET']) def addrec(): if request.method == 'POST': try: nm = request.form['nm'] addr = request.form['add'] city = request.form['city'] pin = request.form['pin'] with sql.connect("database.db") as con: cur = con.cursor() cur.execute("INSERT INTO students (name,addr,city,pin) VALUES (?,?,?,?)",(nm,addr,city,pin) ) con.commit() msg = "Record successfully added" except: con.rollback() msg = "error in insert operation" finally: return render_template("result.html",msg = msg) con.close() @app.route('/list') def list(): con = sql.connect("database.db") con.row_factory = sql.Row cur = con.cursor() cur.execute("select * from students") rows = cur.fetchall(); return render_template("list.html",rows = rows) @app.route('/init') def init(): conn = sqlite3.connect('database.db') print ("Opened database successfully") conn.execute('CREATE TABLE students (name TEXT, addr TEXT, city TEXT, pin TEXT)') print ("Table created successfully") conn.close() return None if __name__ == '__main__': app.run(debug = True)
从Python shell运行此脚本,并在开发服务器开始运行时运行。 访问:http:// localhost:5000/ 在浏览器中显示一个这样的简单菜单 -
点击 “添加学生信息” 链接打开添加学生信息表单。
填写表单并提交。底层函数将该记录插入到学生表中。
返回主页并点击“显示列表”链接,将显示样本数据的表格。