Flask 教程

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/ 在浏览器中显示一个这样的简单菜单 -

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

填写表单并提交。底层函数将该记录插入到学生表中。

返回主页并点击“显示列表”链接,将显示显示样本数据的表格。