Flask SQLite

由 一水寒 创建,学不能停 最后一次修改 2016-12-26

Python对SQlite有内置的支持。SQlite3模块附带Python发行版。有关在Python中使用SQLite数据库的详细教程,请参考《SQLite - Python》的内容。在本节中,我们将了解Flask应用程序如何与SQLite交互。

创建一个SQLite数据库'database.db'并在其中创建学生表。

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应用程序有三个View功能。

第一个new_student()函数已绑定到URL规则('/ addnew')它呈现包含学生信息表单的HTML文件。

@app.route('/enternew')
def new_student():
   return render_template('student.html')

'student.html'的HTML脚本如下:

<html>
   <body>
      
      <form action = "{{ url_for('addrec') }}" method = "POST">
         <h3>Student Information</h3>
         Name<br>
         <input type = "text" name = "nm" /></br>
         
         Address<br>
         <textarea name = "add" ></textarea><br>
         
         City<br>
         <input type = "text" name = "city" /><br>
         
         PINCODE<br>
         <input type = "text" name = "pin" /><br>
         <input type = "submit" value = "submit" /><br>
      </form>
      
   </body>
</html>

可以看出,表单数据被发布到绑定addrec()函数的'/ addrec' URL。

这个addrec()函数通过POST方法检索表单的数据,并插入学生表中。与insert操作中的成功或错误相对应的消息将呈现为'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}},它显示Insert操作的结果。

<!doctype html>
<html>
   <body>
   
      result of addition : {{ msg }}
      <h2><a href = "\">go back to home page</a></h2>
      
   </body>
</html>

该应用程序包含由'/ list' URL表示的另一个list()函数。它将'rows'填充为包含学生表中所有记录的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表中呈现数据。

<!doctype html>
<html>
   <body>
   
      <table border = 1>
         <thead>
            <td>Name</td>
            <td>Address>/td<
            <td>city</td>
            <td>Pincode</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 = "/">Go back to home page</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
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)

if __name__ == '__main__':
   app.run(debug = True)

在开发服务器开始运行时,从Python shell运行此脚本。在浏览器中访问http://localhost:5000/,显示一个简单的菜单:

Simple Menu

点击“添加新记录”链接以打开学生信息表单。

Adding New Record

填写表单字段并提交。底层函数在学生表中插入记录。

Record Successfully Added

返回首页,然后点击'显示列表'链接。将显示一个显示样品数据的表。

Table Showing Sample Data
以上内容是否对您有帮助:
二维码
建议反馈
二维码