Flask 简明教程

Flask – SQLite

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

Python has an in-built support for SQlite. SQlite3 module is shipped with Python distribution. For a detailed tutorial on using SQLite database in Python, please refer to this link. In this section we shall see how a Flask application interacts with SQLite.

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

Create an SQLite database ‘database.db’ and create a students’ table in it.

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 函数。

Our Flask application has three View functions.

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

First new_student() function is bound to the URL rule (‘/addnew’). It renders an HTML file containing student information form.

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

‘student.html’ 的HTML脚本如下 −

The HTML script for ‘student.html’ is as follows −

<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。

As it can be seen, form data is posted to the ‘/addrec’ URL which binds the addrec() function.

addrec() 函数通过 POST 方法检索表单数据并插入 students 表中。插入操作成功或失败的对应消息呈现在 ‘result.html’ 上。

This addrec() function retrieves the form’s data by POST method and inserts in students table. Message corresponding to success or error in insert operation is rendered to ‘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 操作的结果。

The HTML script of result.html contains an escaping statement {{msg}} that displays the result of Insert operation.

<!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 对象,其中包含 students 表中的所有记录。该对象传递给 list.html 模板。

The application contains another list() function represented by ‘/list’ URL. It populates ‘rows’ as a MultiDict object containing all records in the students table. This object is passed to the list.html template.

@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 表中呈现数据。

This list.html is a template, which iterates over the row set and renders the data in an HTML table.

<!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’ ,作为应用程序的入口点。

Finally, the ‘/’ URL rule renders a ‘home.html’ which acts as the entry point of the application.

@app.route('/')
def home():
   return render_template('home.html')

以下为 Flask-SQLite 应用程序的完整代码。

Here is the complete code of Flask-SQLite application.

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/ ,它会显示类似这样的简单菜单 -

Run this script from Python shell and as the development server starts running. Visit http://localhost:5000/ in browser which displays a simple menu like this −

simple menu

点击 ‘Add New Record’ 链接以打开 Student Information 表单。

Click ‘Add New Record’ link to open the Student Information Form.

adding new record

填写表单字段并提交。底层函数会将记录插入 students 表。

Fill the form fields and submit it. The underlying function inserts the record in the students table.

record successfully added

返回主页并点击 ‘Show List’ 链接。程序会显示包含示例数据的表格。

Go back to the home page and click ‘Show List’ link. The table showing the sample data will be displayed.

table showing sample data