Hello World, Welcome to my website. Today I am going to discuss how to login logout in the flask. This is a very simple tutorial. I have divided this tutorial into the following parts.
- Install Flask
- Create view templates to showing the login form
- Create login and logout functionality with session
- Run the application
Install Flask
Please read my previous tutorial to install flask and create a hello world app with flask.
Create view templates to showing the login form
In this step, we will create the following view templates.
login_home.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>How to login logout with flask</title> </head> <body> <h1>Login Logout with flask</h1> {% if login %} You are logged in as <strong>{{ session['username'] }}</strong> <br /> <a href={{ url_for('logout') }}>logout</a> {%else%} Please login here {{ session['username'] }} <br /> <a href={{ url_for('login') }}>login</a> {%endif %} </body> </html>
In this template, we will show login status and if user logout or login then redirect to this page.
login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>How to login logout with flask</title> </head> <body> <h1>Login Logout with flask</h1> <form method="POST"> Username <input type="text" name="username" /> <input type="submit" /> </form> </body> </html>
In this template, we will create a login form.
All the view templates will be placed in templates directory.
Create login and logout functionality with session
In this step, we will perform login, logout and redirect functionality. Create login.py and add the following code in it.
from flask import Flask,session,render_template,request,redirect,url_for app=Flask(__name__) app.secret_key='asdsdfsdfs13sdf_df%&' @app.route('/login',methods=['GET','POST']) def login(): if request.method=='POST': session['username']=request.form['username'] return redirect(url_for('index')) return render_template('login.html') @app.route('/logout') def logout(): session.pop('username',None) return redirect(url_for('index')) @app.route('/') def index(): login=False if 'username' in session: login=True return render_template('login_home.html',login=login) if __name__=='__main__': app.run(debug=True)
Run the application
- Open the command prompt.
- Run the following command and open the given url in browser.
python login.py
When you open this url in the browser, you will see the following screens.
I hope you are enjoying my tutorial. Please give your feedback in comment section. Thank you 🙂 🙂