top of page

How To Create LogIn System Using Flask



How to Create Login system using Flask


Hello Everyone !!!


In this article we are going to show you in a simple way how to create a login system using flask. We will create login templates, create databases and implement login authentication. Here we are going to be using the “Flask-login” Library.


What is flask-Login?

It provides user session management and provides login and logout remember user session over an extended period of time.


Prerequisite

There are a few steps that need to be followed before creating our python login system using flask. We need to install and set up python and its packages that our small application will depend on.


File Structure and Setup




Each file contains the following things :


  • app.py : This file is our main project file, that contains all our python code will be there

  • home.py : This is the html file Home page.

  • login.html : This is the login form template html file where we can enter login details username and password.

  • signup.html : This is the sign up form template html file, where we can create new account by entering username and password

  • profile.html : This profile template which is restricted to logged in users. The user details will be shown after login successfully.


Create Login System


To create a login system we just create a python file, which contains all our code.


The first thing we need to do is import the python packages we are going to use for our login system :


from flask import Flask, render_template, url_for,redirect
from flask_sqlalchemy import SQLAlchemy
from  flask_login import UserMixin,login_user, LoginManager, login_required, logout_user, current_user
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import InputRequired, Length, ValidationError
from flask_bcrypt import Bcrypt

Now here we create a sqlite database which is connected through using sqlalchemy. In this database stored the user's data username and password when the user will create a new account. If the user's username is shown in the database that means the account is valid. After the username is valid check if the password that users entered is correct or not. If it is correct then the users logged in their account.


After creating a database to connect with the file use app.config. Used secrete key to more secure session cookie


app = Flask(__name__)
db = SQLAlchemy(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
app.config['SECRET_KEY'] = 'secretkey'
 
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
 
@login_manager.user_loader
def load_user(user_id):
   return User.query.get(int(user_id))
 
 
bcrypt = Bcrypt(app)
 
class User(db.Model,UserMixin):
   id = db.Column(db.Integer,primary_key = True)
   username = db.Column(db.String(20),nullable=False,unique=True)
   password = db.Column(db.String(80), nullable=False)

Creating Login script

In the app.py file create a login function.


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

Flask-form
Create login and signup form. Here we are creating a class for login form and signup form.  
class SignupForm(FlaskForm):
   username = StringField(validators=[InputRequired(),Length(
       min=4, max=20)],render_kw={"placeholder":"Username"})
 
   password = PasswordField(validators=[InputRequired(),Length(
       min=4, max=20)],render_kw={"placeholder":"password"})
 
   submit = SubmitField("Signup")
 
   def validate_username(self, username):
       existing_user_username = User.query.filter_by(
           username=username.data).first()
       if existing_user_username:
           raise ValidationError(
               'This  username already exists in the database. Please Choose Different Username.')
 
class LoginForm(FlaskForm):
   username = StringField(validators=[
                          InputRequired(), Length(min=4, max=20)], render_kw={"placeholder": "Username"})
 
   password = PasswordField(validators=[
                            InputRequired(), Length(min=8, max=20)], render_kw={"placeholder": "Password"})
 
   submit = SubmitField('Login')

Adding

Adding code in def login() to check if the username and password variable exists in the database. If they both exist in the database it will redirect to the profile page.


@app.route('/login',methods = ['GET','POST'])
def login():
   form = LoginForm()
   if form.validate_on_submit():
       user = User.query.filter_by(username=form.username.data).first()
       if user:
           if bcrypt.check_password_hash(user.password, form.password.data):
               login_user(user)
               return redirect(url_for('profile'))
   return render_template('login.html',form=form)

Creating signup Scripts

Here we create a defined function for registration. Which will be taking data from users like username and password and store it into the database.


@app.route('/signup',methods = ['GET','POST'])
def signup():
   form = SignupForm()
 
   if form.validate_on_submit():
       hashed_password = bcrypt.generate_password_hash(form.password.data)
       new_user = User(username=form.username.data, password=hashed_password)
       db.session.add(new_user)
       db.session.commit()
       return redirect(url_for('login'))
 
   return render_template('signup.html',form=form)

Creating a Logout script


After login the profile we need to logout to remove the session when the user logged in. This code will remove each session. To perform this task a login is required.


@app.route('/logout', methods=['GET', 'POST'])
@login_required
def logout():
   logout_user()
   return redirect(url_for('login'))

Creating a Profile script


After the login successfully this page will be visible to the users. To open this page a login is required.


@app.route('/profile', methods=['GET', 'POST'])
@login_required
def profile():
   return render_template('profile.html')

Templates


Creating the home template


This is home page template of our login system.


<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Welcome to Codersarts!!</title>
</head>
<body>
   <h1>Welcome to Codersarts!!</h1>
   <h3>Login system Using Flask</h3>
   <a href="{{url_for('login')}}">Login Page</a>
   <a href="{{url_for('signup')}}">Signup Page</a>
   <a href="{{url_for('auth')}}">Your Account</a>
 
</body>
</html>

Output




Creating a signup templates

We required a registration system where users can create new accounts on our application. So for that we have already created a signup route here we are creating signup templates along with the registration form. Which will consist of input fields, submit buttons etc.


<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Signup</title>
</head>
<body>
<h1>Welcome To CodersArts!!</h1>
<h2>Signup Page</h2>
 
<form method="POST" action="">
   {{form.hidden_tag()}}
   {{form.username}}
   {{form.password}}
   {{form.submit}}
 
</form>
<a href="{{url_for('login')}}">You already have an account? Log In</a>
<a href="{{url_for('home')}}">Home</a>
</body>
</html>

Output




Creating a Login templates

This is the login page where the login form is available. User can enter login details in the login form


<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Login</title>
</head>
<body>
<h1>Welcome To CodersArts !!</h1>
<h2>Login Page</h2>
<form method="POST" action="">
   {{form.hidden_tag()}}
   {{form.username}}
   {{form.password}}
   {{form.submit}}
</form>
 
<a href="{{url_for('signup')}}">Don't have account? Sign Up</a>
<a href="{{url_for('home')}}">Home</a>
</body>
</html>

Output




Creating a profile templates

This is the user's account page which is the login required for this page.


<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Congratulation, You Are logged In</title>
</head>
<body>
<h1>Welcome To Codersarts!!</h1>
<h2>Congratulation</h2>
<h2>You are Logged In !!</h2>
<a href="{{url_for('logout')}}">Click Here to Logout</a>
<a href="{{url_for('home')}}">Home</a>
</body>
</html>

Output






Conclusion : We have successfully built the login system using python flask in very simple way.


Need more help in Flask Projects ?


  • Flask Assignment help

  • Flask Error Resolving Help

  • Mentorship in Flask from Experts

  • Flask Development Project

If you are looking for help in Flask project contact us contact@codersarts.com


bottom of page