Flask SQLite
Python拥有对SQlite的内置支持。 SQlite3模块随附Python发行版。 有关在Python中使用SQLite数据库的详细教程,请参阅此链接。 在本节中,我们将看到Flask应用程序如何与SQLite进行交互。
创建一个SQLite数据库‘database.db’并在其中创建一个student
表。
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文件。
@app.route('/enternew')
def new_student():
return render_template('student.html')
‘student.html’的HTML脚本如下 -
<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’。
@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}}
。
<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
模板。
@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表格中呈现数据。
<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’作为应用程序的入口点。
@app.route('/')
def home():
return render_template('home.html')
这里是Flask-SQLite应用程序的完整代码。
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/
在浏览器中显示一个这样的简单菜单 -
点击“添加学生信息” 链接打开添加学生信息表单。
填写表单并提交。底层函数将该记录插入到学生表中。
返回主页并点击“显示列表”链接,将显示显示样本数据的表格。
点击查看所有 Flask教程 文章: https://www.codercto.com/courses/l/47.html
AI Algorithms, Data Structures, and Idioms in Prolog, Lisp, and
George F. Luger、William A Stubblefield / Addison Wesley / 2008-09-04 / USD 22.20
This book is designed for three primary purposes. The first is as a programming language component of a general class in Artificial Intelligence. From this viewpoint, the authors see as essential that......一起来看看 《AI Algorithms, Data Structures, and Idioms in Prolog, Lisp, and 》 这本书的介绍吧!