Create a simple login

Okay, so now we need to create a simple login system for our high powered blog. Create a file called login.html under templates.

The page has a very basic form with a username and password. I’m adding some template code to print an error if some enters the wrong password.

Now go to The first thing you need to do is import a few functions, and set the secret key:

We are going to be storing user sessions in cookies, and these need to be encrypted. Don’t choose ‘Chocolate chip cookies’ like I’ve done! This must be a completely random string. Now add the login function (you can create this new route anywhere before the command):

New things: We are doing a methods = [‘GET’, ‘POST’], because this form will have a both HTML GET and POST.

We are using session to store the logged_in state.

We read the username and password from the form, and compare to fixed values. The function will check if the username and password are fish and chips (the national food for the elite in the UK). If they are, it will set logged_in in the current session to true.

The only other thing is error. If the username or password is wrong, this is sent to the login.html file.  If you look at that file, you will see a

{% if error %}

statement, that will print the error on the screen.

The secret page

Create secret.html:

Finally, add the logout and secret function:


Go to and test out your code.

There is a problem with this code: We can go to directly, as nothing checks if we are logged in or not. We will fix this in the next chapter.

The source files are here,Flask

Leave a Reply