Flask Dashboard Argon - adding SQLite database

Hello Coder,

This is part of the tutorial Flask Argon Dashboard - from Zero to Full-Stack. Thank you for reading!

At this point, our dashboard requires a database, used for two things:

  • authentication - new users can register and later on, pass the login
  • to save / read information, displayed later on by dashboard charts

We can  add a database in Flask, in two ways: import the SQL package directly and perform requests, and the second option is to add an ORM, like SQLAlchemy. Concerning the database, we can choose from a variety of engines: SQLite, MySql, PostreSQL.  Adding SQLAlchemy into the picture, the whole task become much easier because this library represents an abstract layer between our application and the underline SQL engine.

SQLAlchemy introduction

SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL. Flask-SQLAlchemy is an extension for Flask, coded on top of SQLAlchemy. Flask-SQLAlchemy aims  to simplify using SQLAlchemy with Flask.

From the short list with database engines, we will pick SQLite because is much easier to work with, and doesn't require any additional installation like servers and drivers.  Let's start coding.

Steps to follow:  

  • Add new files: models.py, views.py, configuration.py
  • Install Flask-SQLAlchemy
  • Update run.py to create the database, when application starts

Define models

from app import db

class User(db.Model):

    id          = db.Column(db.Integer,     primary_key=True)
    user        = db.Column(db.String(64),  unique = True)
    email       = db.Column(db.String(120), unique = True)
    password    = db.Column(db.String(500))

    def __init__(self, user, password, email):
        self.user       = user
        self.password   = password
        self.email      = email

Added configuration

class Config():

	SQLALCHEMY_DATABASE_URI = 'sqlite:///database.db')

Create views file

Creating views.py is optional, but recommended if we want to have a well structured app with a modular design.

from flask import render_template

from app  import app

def index():
    return render_template(  'layouts/default.html',
                             content=render_template( 'pages/index.html') )

Update __init.py - to bundle the new app assets
from flask            import Flask
from flask_sqlalchemy import SQLAlchemy

# Grabs the folder where the script runs.
basedir = os.path.abspath(os.path.dirname(__file__))

app = Flask(__name__)


db = SQLAlchemy(app) 

from app import views, models

Update run.py - to create the database at startup
from app import app
from app import db

if __name__ == "__main__":

    db.create_all() # create tables
	app.run() # rock the world

Future Steps

Argon Dashboard Resources

Thank you for reading!
Show Comments

Get the latest posts delivered right to your inbox.