Flask Tutorial part 1 — Error Handling, Logging, User Authentication

This is tutorial on setting up a User Login system using Python Flask web framework and SQLite and also shows how to setup Logging and Error handling.

I have a public Github repo that shows the web project in its full form and you can see the full structure of the application that you can reference for rest of the project

https://github.com/perfecto25/FlaskFlavors

This tutorial will go over the following steps

  1. create a basic Flask app that returns an ice cream flavor
  2. add Logging to the application
  3. add Error Handling to the application
  4. add User Login to the application

Part 1: basic Flask application “FlaskFlavors”

pip install flask flask-login flask-wtf flask-sqlalchemy sqlalchemy

create a basic Flask app with the following structure. This app will return a basic HTML page over port 5700

basic app structure

add the following content,

app.py
config.py
app/__init__.py
app/templates/index.html
app/views/__init__.py
app/views/main.py

Now run the app

python app.py

App will run on port 5700

Part 2: Add Logging to the application

create a new file app/functions.py

Now add the init_log function to app/__init__.py

app/__init__.py

Now your Log is ready to be added anywhere in the application, for example, lets log whenever someone goes to your “/” route. Make sure to import “log” from app

app/views/main.py

Restart your App and hit the site again over port 5700, now check the log located in APP_HOME/log

cat /home/flavorapp/log/flavor.log
2018–07–11 18:41:16,143 [INFO] someone is accessing index.html!!!

Part 3: Error and Exception handling

We will add 3 new routes, a 404 “Page not found” handler, a 500 “Error” handler and a general Exception handler

Open up app/views/main.py and add these new routes

app/views/main.py

in case of a 404, 500 or Exception, the application will show the “error.html” page with a message

app/templates/error.html

Try to go to a non-existent route, for example hostname:5700/blah

app returns a custom Error page with the message

Try to add an exception Route to main.py

app/views/main.py

Now try hitting the /exception route

Whenever your application encounters an unexpected exception, it will direct the user to a Exception page with an error message. Your log will also show the unexpected exception message,

Part 4: User Login

pip install flask-login

In this example, Im using a simple SQLite DB to store 2 user accounts

I will use 2 python scripts

  1. create_db.py — this script creates a SQLite DB with Columns for Username, Email and Password
  2. create_user.py — this script injects Users into the DB, the users are temporarily stored in a JSON file called users.secure.json

Once the DB is created and populated, we will add Route protection, so if someone goes to yoursite.com/secure they will be forced to login first

To make this work, lets create the DB and populate it.

create a new folder called auth

app/auth

create a new JSON file in app/auth this will be used to inject Users into the DB

cat app/auth/users.secure.json

app/auth/users.secure.json

Addcreate_db.py

app/auth/create_db.py

add create_users.py

app/auth/create_users.py

Run cd app/auth && python create_db.py to create a new DB, you will see a new file generated in app/auth called users.db

new SQLite DB is created

your entire application structure should now look like this, notice the newly created “users.db” file

Now lets inject the users into the DB

cd app/auth && python create_users.py

users are injected into the DB. Notice that the passwords are not stored as text, but are hashed and salted for added security

remove your JSON file now that your DB is ready

rm app/auth/users.secure.json

update your app’s config file to point to the new DB,

config.py

Here you are adding your application base directory (where you are running the app from), adding Database URI and also some SQLAlchemy settings

Open up your app’s __init__.py file and add the Login block,

app/__init__.py

Now we need to create a Model of users by which Flask can check whether the user’s creds are legit or not,

create a new file app/models.py

app/models.py

Update your Main view to reference the User model,

app/views/main.py

Now lets create a Login page where the user will be routed to in case they try to access a protected area, the first step is to create a Flask Form using Flask-WTF extension. This form will have Username + Password fields.

create a new file called forms.py in app directory,

app/forms.py

Now update your Main view to import this form,

app/views/main.py

Now lets create some Routes to send the user to a login form when they try to access protected areas,

open up app/views/main.py

add flask_login requirements to the Main view, these will be used to restrict protected routes

app/views/main.py

and also add the Login and Logout routes,

app/views/main.py

The /login and /logout Routes will check the user input against the DB and route user to appropriate screen

Now we have to create the actual HTML Login form,

app/templates/login.html

Flask uses Flask-WTF extension to generate a new HTML Form during run-time

Now lets add a protected Route to test the login system,

Open up app/views/main.py and create a new “secure” Route to test for login

app/views/main.py

Restart your Flask app and try accessing the secure route, hostname:5700/secure

Flask will route you to the Login form,

Try logging in now with the user email and password from your JSON file,

You should now be redirected to the Index route, meaning that you’re logged in successfully,

You can also add a welcome message to the index.html to display User name

app/templates/index.html

Logout of your user session by going to hostname:5700/logout

Login again by going to hostname:5700/secure

Enter your login creds and you should see your username details in the welcome message,

Hope you enjoyed the tutorial.

Dont forget, the Github repo for all this is here,

https://github.com/perfecto25/FlaskFlavors