Flask - SQLite

Flask - SQLite 首页 / Flask入门教程 / Flask - SQLite

Python对 SQlite 具有内置支持。 SQlite3模块随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' URL,该URL绑定了 addrec()函数。

此 addrec()函数通过 POST 方法检索表单的数据,并将其插入Students表中,与插入操作成功或错误相对应的消息将呈现到" 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()函数,该函数由‘/list' URL表示。它将"row" 填充为包含学生表中所有记录的 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 应用程序的完整代码。

链接:https://www.learnfk.comhttps://www.learnfk.com/flask/flask-sqlite.html

来源:LearnFk无涯教程网

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

点击"Add New Record" 链接以打开学生信息表单。

Adding New Record

填写表格字段并提交。基础函数将记录插入students表中。

Record Successfully Added

返回首页,然后点击"Show List" 链接。将显示显示样本数据的表格。

Table Showing Sample Data

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

技术管理实战36讲 -〔刘建国〕

即时消息技术剖析与实战 -〔袁武林〕

说透中台 -〔王健〕

DDD实战课 -〔欧创新〕

Tony Bai · Go语言第一课 -〔Tony Bai〕

去无方向的信 -〔小麥〕

徐昊 · TDD项目实战70讲 -〔徐昊〕

现代React Web开发实战 -〔宋一玮〕

B端体验设计入门课 -〔林远宏(汤圆)〕

好记忆不如烂笔头。留下您的足迹吧 :)