How to use Flask-Login with SQLite3

Jude_Raj
Analytics Vidhya
Published in
4 min readDec 3, 2020
Python, Flask & SQLite3

Hi Everyone!!!

I have seen many tutorials on how to use Flask-Login with SQLAlchemy. On the other way, We can also use Flask-Login with SQLite3 Database.

where SQLite3 is 3x Faster than SQLAlchemy.

In this, I will be showing how to use SQLite3 Database with Flask-Login and This is one part of my project that I have done to show you.

Important Mention I use Raspberry Pi 3 for this project.

First, we install all the necessary software to get going,

  1. Create a Python Virtual Environment.
sudo apt-get install python-virtualenv #Install Python virtual-envcd /var/ # Navigate to var directorymkdir www # Create directory named "www"cd wwwmkdir flaskcd flaskvirtualenv flask-sqlite3 #Create the virtual-env "flask-sqlite3" . flask-sqlite3/bin/activate # To activate virtual-envdeactivate # To deactivate virtual-env

2. Install Flask, Flask-Login & wtforms.

. flask-sqlite3/bin/activatepip install flask # Install Flaskpip install flask-login # Install flask-loginpip install flask-wtf # Install flask-wtfpip install WTForms # Install WTForms

3. Install SQLite3.

apt-get install sqlite3 # Install sqlite3sqlite3 login.db # Create a new sqlite database named "login"

“I have used Nginx as my webserver and Uwsgi as my Application Gateway”

Setup SQLite3

sqlite3 login.db

Now we will create a table named “login” to store all the login data in the database.

create table login(
user_id NUMBER PRIMARY KEY AUTOINCREMENT,
email text not null,
password text not null);

By, using Autoincrement the developer doesn't have to keep track of IDs while inserting details. It will automatically assign user_ids to each registered user.

“Use a registration form to insert login data into login.db”

I’m assuming that you have inserted some data into login data

insert into login values('xyz@gmail.com','XYZ123abc')

flask_login.py

nano flask.py # Create a new python file named "flask"                              .  .  . from flask import Flask
from flask import render_template, url_for, flash, request, redirect, Response
import sqlite3
from flask_login import LoginManager, UserMixin, login_required, login_user, logout_user, current_user
from forms import LoginForm
app = Flask(__name__)
app.debug=True
login_manager = LoginManager(app)
login_manager.login_view = "login"
class User(UserMixin):
def __init__(self, id, email, password):
self.id = unicode(id)
self.email = email
self.password = password
self.authenticated = False
def is_active(self):
return self.is_active()
def is_anonymous(self):
return False
def is_authenticated(self):
return self.authenticated
def is_active(self):
return True
def get_id(self):
return self.id
@login_manager.user_loader
def load_user(user_id):
conn = sqlite3.connect('/var/www/flask/login.db')
curs = conn.cursor()
curs.execute("SELECT * from login where id = (?)",[user_id])
lu = curs.fetchone()
if lu is None:
return None
else:
return User(int(lu[0]), lu[1], lu[2])
@app.route("/login", methods=['GET','POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('profile'))
form = LoginForm()
if form.validate_on_submit():
conn = sqlite3.connect('/var/www/flask/login.db')
curs = conn.cursor()
curs.execute("SELECT * FROM login where email = (?)", [form.email.data])
user = list(curs.fetchone())
Us = load_user(user[0])
if form.email.data == Us.email and form.password.data == Us.password:
login_user(Us, remember=form.remember.data)
Umail = list({form.email.data})[0].split('@')[0]
flash('Logged in successfully '+Umail)
redirect(url_for('profile'))
else:
flash('Login Unsuccessfull.')
return render_template('login.html',title='Login', form=form)
if __name__ == "__main__":
app.run(host='0.0.0.0',port=8080,threaded=True)

forms.py

from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, BooleanField
from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError
import sqlite3
class LoginForm(FlaskForm):
email = StringField('Email',validators=[DataRequired(),Email()])
password = PasswordField('Password',validators=[DataRequired()])
remember = BooleanField('Remember Me')
submit = SubmitField('Login')
def validate_email(self, email):
conn = sqlite3.connect('/var/www/flask/login.db')
curs = conn.cursor()
curs.execute("SELECT email FROM login where email = (?)",[email.data])
valemail = curs.fetchone()
if valemail is None:
raise ValidationError('This Email ID is not registered. Please register before login')

Now we design the template using HTML & CSS for the login page.

mkdir templates # create a templates directory.cd templates

html_template.html

<!DOCTYPE html>
<html lang="en">
<head>
<!-- Basic Page Needs
-->
<meta charset="utf-8">
{% if title %}
<title>{{ title }}</title>
{% endif %}
<!-- Mobile Specific Metas
-->
<meta name="viewport" content="width=device-width, initial-scale=1 shrink-to-fit=no">
<!-- FONT
-->
<link href="//fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="../static/css/normalize.css">
<link rel="stylesheet" href="../static/css/skeleton.css">
<link rel="icon" type="image/png" href="../static/logo.png"></head>
<body>
<!-- Primary Page Layout
-->
<div style="margin-top:5%; margin-left:5%">
<div style="width:100%;">
<div style="width: 80%; height: 100px; float: left;">
{% with messages = get_flashed_messages(with_categories=True)%}
{% if messages %}
{% for category, message in messages %}
<div class="alert alert-{{ category }}">
<h5>{{ message }}<h5>
</div>
{% endfor %}
{% endif %}
{% endwith %}
{% block info %}
{% endblock %}
</div>
</div>
</div>
<!-- End Document
-->
</body>
</html>

I have used skeleton.css for the design

Refer to http://getskeleton.com/ “or” https://github.com/dhg/Skeleton

login.html

{% extends "html_template.html" %}
{% block info %}
<form method='POST' action="">
{{ form.hidden_tag() }}
<fieldset class="form-group">
<h1>Log In</h1>
<div class="form-group">
{{ form.email.label(class="form-control-label")}}
{% if form.email.errors %}
{{ form.email(class="form-control form-control-lg is-invalid") }}
<div class="invalid-feedback">
{% for error in form.email.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ form.email(class="form-control form-control-lg")}}
{% endif %}
</div>
<div class="form-group">
{{ form.password.label(class="form-control-label")}}
{% if form.password.errors %}
{{ form.password(class="form-control form-control-lg is-invalid") }}
<div class="invalid-feedback">
{% for error in form.password.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ form.password(class="form-control form-control-lg")}}
{% endif %}
</div>
<div class="form-group">
{{ form.remember(class="form-check-input") }}
{{ form.remember.label(class="form-check-label") }}
</div>
</fieldset>
<div class="form-group">
{{ form.submit(class="btn btn-outline-info")}}
</div>
<a href="javascript:void(0)" onclick="location.href='/reset'">Forgot Password?</a>
</form>
<h6>Create an Account <a href="javascript:void(0)" onclick="location.href='/register'">Sign Up Now</a></h6>
{% endblock info %}

Now, Run the web app by,

python flask_login.py

Thank You to everyone who find it useful

--

--

Analytics Vidhya
Analytics Vidhya

Published in Analytics Vidhya

Analytics Vidhya is a community of Generative AI and Data Science professionals. We are building the next-gen data science ecosystem https://www.analyticsvidhya.com