Connecting sqlite to Flask Web App

From TRCCompSci - AQA Computer Science
Jump to: navigation, search

sqlite will create a file local to the web app and will allow you to run a pretty full SQL relational database. There are some features not supported by sqlite but you are unlikely to need any of them. The wiki already covers using sqlite in the following pages:

Adding to Flask Web App

You will need to import sqlite into your or file:

import sqlite3
from sqlite3 import Error

I would recommend you create a class for the database functions you will need:

class Database:
    dbname = "test.db"

    def connect(self, db_file):
            conn = sqlite3.connect(db_file)
            return conn
        except Error as e:
            return none

    def execute(self, sql):
            c = self.connection.cursor()
            return True
        except Error as e:
            return False

    def select(self, sql):
            cur = self.connection.cursor()
            return cur.fetchall()
        except Error as e:
            return False
    def __init__(self):
        self.connection = self.connect(self.dbname)

This code will create a database connection whenever an object of the class is created. It also contains a method to run the execute style commands (ie create, insert, update, delete) and a method to run the retrieve style commands (ie select). This method will allow you to change the connection methods at a later date without needing to change any of the web app code.

You could extend this by creating individual methods for 'CheckLogin', or 'GetProduct' or 'GetQuiz', alternatively the sql could be within your routes. This will keep all of the database code in one place.

This example shows how you can make a route to execute the command. This creates an object of the database class, and then runs the execute method to run the sql:

def createuserdb():
    db = Database()
    sql = """CREATE TABLE IF NOT EXISTS users(
                UserID text PRIMARY KEY,
                UserPass text NOT NULL,
                UserEmail text NOT NULL
    check = db.execute(sql)