Flask – SQLite

  • 简述

    Python 内置支持SQlite. SQlite3 模块随 Python 发行版一起提供。关于在 Python 中使用 SQLite 数据库的详细教程,请参考此链接。在本节中,我们将看到 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')
    
    HTML 脚本‘student.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’绑定的 URLaddrec()功能。
    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()
    
    的 HTML 脚本result.html包含转义语句{{msg}}显示结果Insert手术。
    
    <!doctype html>
    <html>
       <body>
          result of addition : {{ msg }}
          <h2><a href = "\">go back to home page</a></h2>
       </body>
    </html>
    
    该应用程序包含另一个list()所代表的功能‘/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/在显示这样一个简单菜单的浏览器中 -
    简单菜单
    点击‘Add New Record’打开链接Student Information形式。
    添加新记录
    填写表格字段并提交。底层函数将记录插入学生表中。
    记录添加成功
    返回首页并点击‘Show List’关联。将显示显示示例数据的表格。
    显示样本数据的表格