English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Flask SQLite

Python has built-in support for SQLite. SQlite3The module is included with the Python distribution. In this section, we will see how the Flask application interacts with SQLite.

Create a SQLite database 'database.db'and creates a student table within it.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: de.oldtoolbag.com
# Date : 2020-08-08
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()

The Flask application has three view functions.

The first new_student() function is bound to the URL rule ('/addnew()). It presents the HTML file containing the student information form.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: de.oldtoolbag.com
# Date : 2020-08-08
@app.route('/enternew')
 def new_student():
     return render_template('student.html')

The HTML script for 'student.html' is as follows -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: de.oldtoolbag.com
# Date : 2020-08-08
<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>Student Information</h3>
          Name<br>
          <input type = "text" name = "nm" /></br>
          Adresse<br>
          <textarea name = "add" /><br>
          Stadt<br>
          <input type = "text" name = "city" /><br>
          Postleitzahl<br>
          <input type = "text" name = "pin" /><br>
          <input type = "submit" value = "提交" /><br>
       </form>
    </body>
 </html>

Es ist erkennbar, dass die Formulardaten an die mit der Funktion addrec() verknüpfte URL => ‘/addrec’ .

Diese Funktion addrec() liest die Daten des Formulars über die POST-Methode aus und fügt sie in die Studententabelle ein. Die mit dem Erfolg oder dem Fehler der Einfügereaktion korrespondierenden Nachrichten werden als 'result.html' dargestellt.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: de.oldtoolbag.com
# Date : 2020-08-08
@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 Der HTML-Skript enthält die Escape-Anweisungen {{msg}}, um das Ergebnis der Einfügereaktion anzuzeigen.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: de.oldtoolbag.com
# Date : 2020-08-08
<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>Flask示例</title>
 </head>
    <body>
       Bearbeitungsergebnis : {{ msg }}
       <h2><a href = "/">返回主页</a></h2>
    </body>
 </html>

Diese Anwendung enthält eine URL => ‘/list’ bedeutet eine andere list() -Funktion. Sie füllt "Zeile" mit einem MultiDict-Objekt, das alle Einträge der Studententabelle enthält. Dieses Objekt wird an das Template list.html übergeben.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: de.oldtoolbag.com
# Date : 2020-08-08
@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)

Diese Datei list.html ist ein Template, das die Zeilenkolektion durchsucht und die Daten in einem HTML-Tabelle darstellt.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: de.oldtoolbag.com
# Date : 2020-08-08
<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’作为应用程序的入口点。

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: de.oldtoolbag.com
# Date : 2020-08-08
@app.route('/)
 def home():
     return render_template('home.html')

这里是Flask-SQLite应用程序的完整代码。

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: de.oldtoolbag.com
# Date : 2020-08-08
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 ("Datenbank erfolgreich geöffnet")
     conn.execute('CREATE TABLE students (name TEXT, addr TEXT, city TEXT, pin TEXT)')
     print ("Tabelle erfolgreich erstellt")
     conn.close()
     return None
 if __name__ == '__main__':
     app.run(debug = True)

Führen Sie diesen Skript im Python-Shell aus und führen Sie den Entwickler-Server aus, wenn dieser gestartet wird. Besuchen Sie: http:// localhost:5000/ Zeigen Sie ein solches einfaches Menü im Browser an -

Klicken „Schülerinformationen hinzufügen“ Öffnen Sie das Formular zur Eingabe von Schülerinformationen.

Füllen Sie das Formular aus und senden Sie es ein. Die untergeordnete Funktion fügt das Protokoll in die Tabelle der Schüler ein.

Klicken Sie auf die Hauptseite und klicken Sie auf den Link "Liste anzeigen", um die Tabelle mit den Beispieldaten anzuzeigen.