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: www.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: www.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: www.oldtoolbag.com
# Date : 2020-08-08
<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>Flask Example</title>/title>
 </head>
    <body>
     <form action="{{ url_for('addrec') }}" method="POST">
          <h3>Student Information</h3>
          Name
          <input type = "text" name = "nm" /></br>
          Address<br>
          <textarea name = "add" /><br>
          City<br>
          <input type = "text" name = "city" /><br>
          Postal Code<br>
          <input type = "text" name = "pin" /><br>
          <input type = "submit" value = "Submit" /><br>
       </form>
    </body>
 </html>

It can be seen that the form data is published to the URL => ‘/addrec’ .

The addrec() function retrieves the form data via the POST method and inserts it into the student table. Messages corresponding to the success or error of the insertion operation are presented as 'result.html'.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.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 The HTML script contains the escaped statement {{msg}} to display the result of the insertion operation.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>Flask Example</title>/title>
 </head>
    <body>
       Operation Result: {{ msg }}
       <h2><a href = "/">Return to homepage</a></h2>
    </body>
 </html>

This application contains a URL => '/list’ represents another list() function. It fills 'row' with a MultiDict object containing all records of the student table. This object is passed to the list.html template.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.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)

This list.html is a template that iterates over the row collection and presents the data in an HTML table.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>Flask Example</title>/title>
 </head>
    <body>
       <table border = " 1>
          thead>
             <td>Name</td>/td>
             <td>Address</td>/td>
             <td>City</td>/td>
             <td>Code</td>/td>
          </thead>
          {% for row in rows %}
             tr>
                <td>{{row["name"]}}</td>/td>
                <td>{{row["addr"]}}</td>/td>
                <td>{{row["city"]}}</td>/td>
                <td>{{row['pin']}}</td>/td> 
             </tr>
          {% endfor %}
       </table>
       <a href = "}}/">Return to homepage</a>
    </body>
 </html>

Finally, URL => ‘/‘presenting a rule’home.html’as the entry point of the application.

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

Here is Flask-Complete code for a SQLite application.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.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 ('Database opened 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)

Run this script from the Python shell and run the development server when it starts. Access: http:// localhost:5000/ Display such a simple menu in the browser -

Click Add Student Information Link opens the form to add student information.

Fill in the form and submit. The underlying function inserts the record into the student table.

Return to homepage and click the 'Show List' link to display the table of sample data.