Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • Official Blog
  • Nearby Places Finder
  • Direction Route Finder
  • Distance & Time Calculator
Menu

Python 3 Flask Project to Build User Login & Logout System Using Sessions in Browser Using HTML5 Forms

Posted on December 18, 2022

 

 

Welcome folks today in this blog post we will be building a user login & logout system using sessions in flask using html5 forms. All the full source code of the application is shown below.

 

 

Get Started

 

 

In order to get started you need to install the flask library using the pip command as shown below

 

 

pip install flask

 

 

After installing this library you need to see the directory structure of the app as shown below

 

 

 

 

 

And now you need to make an app.py file and copy paste the following code

 

 

app.py

 

 

Python
1
2
3
4
5
6
7
8
9
10
from flask import Flask,session,render_template,redirect,request,g,url_for
 
import os
 
app = Flask(__name__)
 
app.secret_key = os.urandom(24)
 
if __name__ == "__main__":
    app.run(debug=True)

 

 

As you can see in the python code we are importing the flask library and also we are importing the sessions and render_template . And also we are importing the redirect,request and url_for modules. And then we are initializing a new flask app. And we are setting the secret key of the flask app.

 

Now you need to make the templates folder inside the root directory and make an index.html file and copy paste the following code

 

 

index.html

 

 

1
2
3
4
5
6
7
<h1>Simple Login Form</h1>
 
<form method="post" action="/">
    <input type="text" name="username" required id="">
    <input type="password" name="password" required id="">
    <input type="submit" value="Register">
</form>

 

 

As you can see in the above html code we have a simple user form where we have two fields username and password and basically this form will submit to the endpoint which is the home route / and the method is post. And then we have the submit button to submit the form.

 

 

 

 

And now inside the app.py file we need to write the flask code to serve the index.html file when the user open the home route and when the users submits the form a post method will be made to the same home route as shown below

 

 

1
2
3
4
5
6
7
8
9
10
@app.route('/',methods=['GET','POST'])
def index():
    if request.method == 'POST':
        session.pop('user',None)
 
        if request.form['password'] == 'password':
            session['user'] = request.form['username']
            return redirect(url_for('protected'))
    
    return render_template('index.html')

 

 

As you can see we are getting the username and the password from the post request. And then we are setting the user session variable if the password is equal to password and then we are redirecting the user to the protected page. And now we are using the render_template() method to load the index.html file when the user is opening the / route it will be a get request that’s why we will be showing the index.html file.

 

 

Now we need to write the get request to the /protected route as shown below so that user will be redirected once they are successfully logged in

 

 

Python
1
2
3
4
5
@app.route('/protected')
def protected():
    if g.user:
        return render_template('protected.html',user=session['user'])
    return redirect(url_for('index'))

 

 

As you can see we are first of all checking if the session user variable is set or not by using the global variable property inside the if condition and inside it we are redirecting the user to the protected page. And in the template we are passing the user session variable. And if the user session variable is not set then we are redirecting the user to the login page.

 

 

Now we need to create the protected.html file inside the templates folder and copy paste the following code

 

 

templates/protected.html

 

 

1
2
<h1>Welcome {{user}} to the protected page</h1>
<button type="submit" onclick='window.location="http://localhost:5000/dropsession"'>Logout</button>

 

 

 

 

As you can see inside the protected page we are displaying the logged in user using the {{}} operator. Here inside this we are displaying the username and also we have the logout button and we have binded a onclicklistener and when the user clicks the logout button we are redirecting the user to the /dropsession route as shown below

 

 

Python
1
2
3
4
@app.route('/dropsession')
def dropsession():
    session.pop('user',None)
    return render_template('index.html')

 

 

As you can see we are defining the get route to the /dropsession and inside it we are deleting the user session variable using the pop() method and after that we are rendering the index.html template.

 

 

And now we need to write the middleware function which will execute before every request just to check if the session variable is set or not using the global variable as shown below

 

 

Python
1
2
3
4
5
6
@app.before_request
def before_request():
    g.user = None
 
    if 'user' in session:
        g.user = session['user']

 

 

As you can see we are just initializing a global variable of user which is None and after that inside the if condition we are checking if the user session is set or not. If it’s set then we are storing that session variable of user into the global user variable.

 

 

Full Source Code

 

 

Wrapping the full blog post this is the full source code of the app.py file as shown below

 

 

app.py

 

 

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
from flask import Flask,session,render_template,redirect,request,g,url_for
 
import os
 
app = Flask(__name__)
 
app.secret_key = os.urandom(24)
 
@app.route('/',methods=['GET','POST'])
def index():
    if request.method == 'POST':
        session.pop('user',None)
 
        if request.form['password'] == 'password':
            session['user'] = request.form['username']
            return redirect(url_for('protected'))
    
    return render_template('index.html')
 
@app.route('/protected')
def protected():
    if g.user:
        return render_template('protected.html',user=session['user'])
    return redirect(url_for('index'))
 
@app.before_request
def before_request():
    g.user = None
 
    if 'user' in session:
        g.user = session['user']
 
@app.route('/dropsession')
def dropsession():
    session.pop('user',None)
    return render_template('index.html')
 
if __name__ == "__main__":
    app.run(debug=True)

 

 

 

Recent Posts

  • Android Java Project to Crop,Scale & Rotate Images Selected From Gallery and Save it inside SD Card
  • Android Kotlin Project to Load Image From URL into ImageView Widget
  • Android Java Project to Make HTTP Call to JSONPlaceholder API and Display Data in RecyclerView Using GSON & Volley Library
  • Android Java Project to Download Youtube Video Thumbnail From URL & Save it inside SD Card
  • Android Java Project to Embed Google Maps & Add Markers Using Maps SDK
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • java
  • javascript
  • Koajs
  • kotlin
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • ReactNative
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme