loading...
Cover image for Flask Dashboard Argon - Learn Flask by coding

Flask Dashboard Argon - Learn Flask by coding

sm0ke profile image Sm0ke Updated on ・4 min read

Hello Coder,

In case you're a beginner and the idea of coding a dashboard might sound challenging or a little bit scary, this article should help you a little bit, because, in the end, we will have a functional Flask dashboard application to click on. Thank you for reading!


In case you want to start faster your next admin dashboard project check out this index with Open Source Admin Dashboards already coded with authentication, database, and deploy scripts - Provided by AppSeed.


(Future) App features

Final App Screen, sources, demo, product info, and documentation

Argon Dashboard - Open-Source Flask Dashboard | AppSeed

For topics like setting up the environment and integrating a design please take a look at my previous article

This article will address topics like adding a database, access the information by using an ORM and implement a minimal authentication flow (login, register). Let's code!

Adding a database

Because Flask does not support databases natively, we need to integrate Flask SqlAlchemy into our application, in order to have access to the underline database (SQLite, MySql)
This extension helps us to access the tables in an object-oriented way, and avoid completely writing RAW SQL queries.

Steps to follow:

  • install Flask SQLAlchemy extension
  • define models, add the required configuration
  • Update the app starter to create the database on-the-fly

Any python extension can be easily installed via PIP

pip install flask_sqlalchemy

Define the User model - used in the authentication process - sources

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))

Add Configuration required by SQLAlchemy - sources

class Config():
    SQLALCHEMY_TRACK_MODIFICATIONS  = False
    SQLALCHEMY_DATABASE_URI = 'sqlite:///database.db')

Bind SQLAchemy object to our app - in file init.py

from flask            import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config.from_object('app.configuration.Config')

db = SQLAlchemy  (app) # flask-sqlalchemy

Finally, update the app launcher run.sh to create the database

from app import app
from app import db

if __name__ == "__main__":
    db.create_all()
    app.run() 

Adding authentication

Implementing basic authentication into a Flask application should be an easy task if we have a basic Flask knowledge and spent a few minutes to read the documentation.

Steps to follow

  • Add Flask Login module
  • Add Login, Registration forms and pages
  • Handle the authentication routes

Install Flask login - via PIP

pip install flask-login

Install forms helpers to validate the user input

pip install flask-login
pip install wtforms

Create forms.py

from flask_wtf import FlaskForm
from wtforms.validators import Email, DataRequired

class LoginForm(FlaskForm):
    username = StringField   (u'Username', validators=[DataRequired()])
    password = PasswordField (u'Password', validators=[DataRequired()])

class RegisterForm(FlaskForm):
    username = StringField   (u'Username', validators=[DataRequired()])
    password = PasswordField (u'Password', validators=[DataRequired()])
    email    = StringField   (u'Email'   , validators=[Email()])

Create the login page

<form role="form" method="post" action="">
    {{ form.username(placeholder="Username") }}
    {{ form.password(placeholder="Password",type="password") }}
</form>

Create the registration page

<form role="form" method="post" action="">
    {{ form.username(placeholder="Username") }}
    {{ form.email(placeholder="eMail") }}
    {{ form.password(placeholder="Password") }}
</form>

Update the __init.py file - to include the LoginManager

from flask            import Flask
from flask_sqlalchemy import SQLAlchemy # <-- new line
from flask_login      import LoginManager # <-- new line

app = Flask(__name__)

app.config.from_object('app.configuration.Config')

db = SQLAlchemy  (app) #flask-sqlalchemy

lm = LoginManager(   ) # flask-loginmanager
lm.init_app(app) # init the login manager

Create new routes in the views.py for login, logout, register

# update the imports to include latest assets
from app.models import User
from app.forms  import LoginForm, RegisterForm

# logout route
@app.route('/logout.html')
def logout():
    logout_user()

...

# register user
@app.route('/register.html', methods=['GET', 'POST'])
def register():

    # declare the Registration Form
    form = RegisterForm(request.form)
... 


@app.route('/login.html', methods=['GET', 'POST'])
def login():

    # Declare the login form
    form = LoginForm(request.form)
... 


Final words

If something is not clear, feel free to request more information in the comments section. Thank you!

Resources

Posted on by:

sm0ke profile

Sm0ke

@sm0ke

#Automation, my favorite programming language

Discussion

pic
Editor guide