Skip to content

Instantly share code, notes, and snippets.

@PolBaladas
Last active August 27, 2023 05:06
Show Gist options
  • Star 34 You must be signed in to star a gist
  • Fork 25 You must be signed in to fork a gist
  • Save PolBaladas/07bfcdefb5c1c57cdeb5 to your computer and use it in GitHub Desktop.
Save PolBaladas/07bfcdefb5c1c57cdeb5 to your computer and use it in GitHub Desktop.
Creating a Login Page with Python Flask and SQLite 3 DB.

Login page using Python, Flask and sqlite3 DB

How-to guide

(Task for GCI 2015-16) Year: 2015-16 This guide will show how to create a simple login page with Flask (a python microframework) and a sqlite3 database.

1. Database Schema and Models

As we are creating a simple user login app we need to store 2 basic values in the database: the username and the password. In order to build the database we need to define a schema:

schema.sql :

drop table if exists users;
    create table users (
    id integer primary key autoincrement,
    username text not null,
    password text not null
);

This sql orders define the structure of our database. This set of orders also deletes or 'drops' previously created sql tables.

After defining the schema of the db we can now build it (on terminal): sqlite3 database.db < schema.sql

Now we can define and develop the python methods to handle this database.

models.py :

import sqlite3 as sql

def insertUser(username,password):
    con = sql.connect("database.db")
    cur = con.cursor()
    cur.execute("INSERT INTO users (username,password) VALUES (?,?)", (username,password))
    con.commit()
    con.close()

def retrieveUsers():
	con = sql.connect("database.db")
	cur = con.cursor()
	cur.execute("SELECT username, password FROM users")
	users = cur.fetchall()
	con.close()
	return users

We'll later call these methods from main.py to handle the database.

2. HTML Login Form (+css styling)

The html code used for this app can be found in index.html file (in this same git). It uses the Flask template engine to render the 'logged users' list. The html contains a simple html form with two text type inputs: username and password, and a submit type input (Login button).

3. Flask App

Flask is a python microframework intended for the developement of web applications (server side). This application works with a single flask function/route/url (views for convention) which answers to two types of HTTP methods (GET, POST). If the HTTP request is GET, the app returns the HTML form. In the case of a POST request (created after the form submission) it returns the list of logged users.

main.py :

from flask import Flask
from flask import render_template
from flask import request
import models as dbHandler

app = Flask(__name__)

@app.route('/', methods=['POST', 'GET'])
def home():
	if request.method=='POST':
   		username = request.form['username']
   		password = request.form['password']
   		dbHandler.insertUser(username, password)
   		users = dbHandler.retrieveUsers()
		return render_template('index.html', users=users)
   	else:
   		return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=False, host='0.0.0.0')

This app makes database calls in order to insert new users and to return the logged users list requested by the POST method. The Database Handler (models.py) methods are called when main.py has to acces and/or modify the database: dbHandler.insertUser(username, password) , users = dbHandler.retrieveUsers().

Note: The host parameter can be changed to 127.0.0.1 (localhost) instead of 0.0.0.0 .

4. All together: Testing and explaining data's flow

To run the Flask app (server) type into your terminal: python main.py Output :

* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)

Open your browser and visit 0.0.0.0:5000 (or 127.0.0.1:5000), the html will render and show up the login form. The terminal should prompt something like this:

* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [20/Dec/2015 15:31:53] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [20/Dec/2015 15:31:53] "GET /static/main.css HTTP/1.1" 200 -
127.0.0.1 - - [20/Dec/2015 15:31:53] "GET /favicon.ico HTTP/1.1" 404 -

If you complete and submit the form, the results will be also reflected in the terminal (pay attention at the POST method):

* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [20/Dec/2015 15:31:53] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [20/Dec/2015 15:31:53] "GET /static/main.css HTTP/1.1" 200 -
127.0.0.1 - - [20/Dec/2015 15:31:53] "GET /favicon.ico HTTP/1.1" 404 -
127.0.0.1 - - [20/Dec/2015 16:50:13] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [20/Dec/2015 16:50:14] "GET /static/main.css HTTP/1.1" 200 -
127.0.0.1 - - [20/Dec/2015 16:50:14] "GET /favicon.ico HTTP/1.1" 404 -
127.0.0.1 - - [20/Dec/2015 16:50:17] "POST / HTTP/1.1" 200 -

Now the webapp should also show the list of logged users. (It works!)

<html lang="en">
<head>
<link href="static/main.css" rel="stylesheet" type="text/css" media="all">
</head>
<body>
<h1 style="text-align:center;">GCI <a href="https://codein.withgoogle.com/dashboard/task-instances/6211328603586560/?sp-page=1">TASK</a></h1>
<div class="box">
<h1>Log In</h1>
<form action="/" method="post">
<input type="text" name="username" id="username" placeholder="Username" required/>
<br>
<input type="password" name="password" id="password" placeholder="Password" required/>
<br>
<input type="submit" class="button" value="Log In"/>
</form>
</div>
<div class="footer">
<h4>Made by <a href="http://www.github.com/PolBaladas">Pol Baladas</a></h4>
<h5 style="text-align:center;">Check <a href="https://github.com/PolBaladas/GCI-LoginApp">this Project</a> on Github</h5>
</div>
{%if users%}
<div class="users" style="margin-left:20%">
<h2>Registered Users List</h2>
<table style="width:100%;">
{%for user in users%}
<tr>
<td>{{user[0]}}</td>
</tr>
{%endfor%}
</table>
</div>
{%endif%}
</body>
</html>
body,
input,
textarea,
select {
font-family: 'Open Sans', sans-serif;
font-size: 12px;
color: #4c4c4c;
}
h1 {
font-size: 32px;
font-weight: 300;
color: #4c4c4c;
text-align: center;
padding-top: 10px;
margin-top: 20px;
margin-bottom: 10px;
}
.box h2{
text-align: center;
margin-top: 30px;
}
.box {
margin: 20px auto;
width: 310px;
height: 260px;
-webkit-border-radius: 8px/7px;
-moz-border-radius: 8px/7px;
border-radius: 8px/7px;
background-color: white;
-webkit-box-shadow: 1px 2px 5px grey;
-moz-box-shadow: 1px 2px 5px grey;
box-shadow: 1px 2px 5px grey;
border: solid 1px grey;
}
.footer h4{
text-align: right;
margin-right: 30%;
margin-top: 30px;
}
input{
margin-top: 15px;
margin-left: 25%;
margin-right:25%;
}
@cnpante
Copy link

cnpante commented Nov 23, 2016

what could be a function that could delete a user? thanks

@Tommy-B-Git
Copy link

Getting a...
Bad Request
The browser (or proxy) sent a request that this server could not understand.

When I try to run this

@kanishkamakhija
Copy link

i got internal server error while running this code

@trohit
Copy link

trohit commented Aug 29, 2017

Works. You need to create a 'templates' directory and put main.html inside it. main.css goes under a directory called 'static'.
in sqlite, you need to create a new user using:
sqlite> .open database.db
sqlite> create table users ( id integer PRIMARY KEY, username TEXT NOT NULL, password TEXT NOT NULL);
sqlite> select * from users;
1|guest|guest

@seansio1995
Copy link

great tutorial

@datainvestor
Copy link

I tried to run this code exactly as it is but it shows me that the site cant be reached. It executes and console states:
Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)

But thats all.
Anyone has idea how to solve this?

@Abdulkereem
Copy link

this the error that i receive any solution to this please sqlite3.OperationalError

OperationalError: no such table: users

@Anchal-kansal
Copy link

no errors, but not able to print output on the webpage, possible reasons could be?

@vijay-subramani
Copy link

I got this error.
No module named models.

@vijay-subramani
Copy link

How can I recover it?

@SANDHIYA-AMMU
Copy link

how can i see the list of users?

@AtyamAnudeep
Copy link

no errors, thankyou ..!

@mkarrlp
Copy link

mkarrlp commented Apr 10, 2019

Thanks for this, it was helpful.

SANDHIYA-AMMU, part of the tutorial explains how you can do this. IF you follow it you will end up with a page that lists your users out. If you play with it more you can show more or less information with "{{user[0]}}" the number inside there relates to the column of the table. If you have 3 columns you could show the 3rd by putting a 2 in there. Not part of your question but just an FYI.

@nivethaprakash
Copy link

I am new to programming.how should I run the code?can someone please help me?

@nivethaprakash
Copy link

@mkarrlp hi,i am new to programming.could you please help me to run this code in a step by step manner?
thanks:)

@lukehinds
Copy link

would not recommend anyone use this beyond simple learning. If you intend to run this code anywhere near the internet, then introduce password hashing using something like bcrypt, so your users passwords are protected.

@001Shubham001
Copy link

socket.gaierror: [Errno 11001] getaddrinfo failed.

now what to do?

@Some1and2-XC
Copy link

Please no one actually use this in production. When storing user data you must NEVER store user passwords as plain text (as this method does). Using PBKDF2 practices should make your application more secure but please research ethical storing methods for passwords before trying to set up a login page for a wbapp.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment