当前位置:   article > 正文

Flask(十七)——SQLite_flask sqlite

flask sqlite

Python拥有对SQlite的内置支持。 SQlite3模块随附Python发行版。在本节中,我们将看到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()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

Flask应用程序有三个视图函数。

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

@app.route('/addnew')
def new_student():
    return render_template('student.html')
  • 1
  • 2
  • 3

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" /></textarea><br>
          城市<br>
          <input type = "text" name = "city" /><br>
          邮编<br>
          <input type = "text" name = "pin" /><br>
          <input type = "submit" value = "提交" /><br>
       </form>
    </body>
 </html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

可以看出,表单数据发布到绑定 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()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

该应用程序包含由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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

这个 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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

最后,URL => / 规则呈现一个 home.html 作为应用程序的入口点。

@app.route('/')
def home():
    return render_template('home.html')
  • 1
  • 2
  • 3

home.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
  <a href="/addnew">添加学生信息</a>
  <a> | </a>
  <a href="/list">学生信息列表</a>
</body>
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

这里是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('/addnew')
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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60

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

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

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

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/一键难忘520/article/detail/889506
推荐阅读
相关标签
  

闽ICP备14008679号