Skip to main content

How to Setup User Login in Flask?

In this tutorial, we are going to use flask login library for our app user authentication.

So let's get started, How to use this.

  • First, create a project folder and in this folder make a virtual environment for our project.
  • Here I am using pipenv for virtual environment.
  • Now install required python packages for our project.
    • flask 
      pip install Flask
      
    • flask-login
      pip install Flask-Login
    • flask-SQLalchemy
      pip install Flask-SQLAlchemy
      

  • Now create a file models.py for database model.
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
 
db = SQLAlchemy()
 
class UserModel(UserMixin, db.Model):
    __tablename__ = 'users'
 
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(80), unique=True)
    username = db.Column(db.String(100))
    password_hash = db.Column(db.String())
 
    def set_password(self,password):
        self.password_hash = generate_password_hash(password)
     
    def check_password(self,password):
        return check_password_hash(self.password_hash,password)
  • In this, we are creating an email, username, and password field.
  • Password field is has using werkzeug security library.
  • In UserModel class, we created a set password method and check password methods.
  • Now we have to initialize flask login extension in our app.
  • So create a new file called auth.py and create these methods.
from flask_login import LoginManager
from models import UserModel
login = LoginManager() @login.user_loader def load_user(id): return UserModel.query.get(int(id))
  • Create our main flask app file called main.py and configure the database.
from flask import Flask
  
app =Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///<db_name>.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
  
app.run(host='localhost', port=5000)
  • Adding login extension to our app.
from flask import Flask
from auth import login
 
app =Flask(__name__)
 
login.init_app(app)
 
app.run(host='localhost', port=5000)
  • Create a method for login view.
@app.route('/login', methods = ['POST', 'GET'])
def login():
    if current_user.is_authenticated:
        return redirect('/blogs')
     
    if request.method == 'POST':
        email = request.form['email']
        user = UserModel.query.filter_by(email = email).first()
        if user is not None and user.check_password(request.form['password']):
            login_user(user)
            return redirect('/blogs')
     
    return render_template('login.html')
  • Create a login.html file
<form action="" method ="POST">
    <p>email <input type ="email" name ="email" /></p>
    <p>password <input type ="password" name ="password" /></p>
    <p> submit <input type ="submit" value ="Submit" /></p>
</form>
 
<h3>Dont Have an account??</h3>
<h3><a href ="{{url_for('register') }}">Register Here</a></h3>
  • Create a register method.
@app.route('/register', methods=['POST', 'GET'])
def register():
    if current_user.is_authenticated:
        return redirect('/blogs')
     
    if request.method == 'POST':
        email = request.form['email']
        username = request.form['username']
        password = request.form['password']
 
        if UserModel.query.filter_by(email=email):
            return ('Email already Present')
             
        user = UserModel(email=email, username=username)
        user.set_password(password)
        db.session.add(user)
        db.session.commit()
        return redirect('/login')
    return render_template('register.html')
  • Create register.html file
<form action="" method ="POST">
    <p>email <input type ="email" name ="email" /></p>
    <p>Username <input type ="text" name ="username" /></p>
    <p>password <input type ="password" name ="password" /></p>
    <p> submit <input type ="submit" value ="Submit" /></p>
</form>
 
<h3>Already Have an Account?</h3><br>
<h3><a href ="{{url_for('login')}}">Login Here</a></h3>
  • Create logout method
@app.route('/logout')
def logout():
    logout_user()
    return redirect('/blogs')
  • All main.py file methods
from flask import Flask,render_template,request,redirect
from flask_login import login_required, current_user, login_user, logout_user
from models import UserModel,db,login
from auth import login
app = Flask(__name__) app.secret_key = 'xyz' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db.init_app(app) login.init_app(app) login.login_view = 'login' @app.before_first_request def create_all(): db.create_all() @app.route('/index') @login_required def index(): return render_template('index.html') @app.route('/login', methods = ['POST', 'GET']) def login(): if current_user.is_authenticated: return redirect('/index') if request.method == 'POST': email = request.form['email'] user = UserModel.query.filter_by(email = email).first() if user is not None and user.check_password(request.form['password']): login_user(user) return redirect('/index') return render_template('login.html') @app.route('/register', methods=['POST', 'GET']) def register(): if current_user.is_authenticated: return redirect('/index') if request.method == 'POST': email = request.form['email'] username = request.form['username'] password = request.form['password'] if UserModel.query.filter_by(email=email).first(): return ('Email already Present') user = UserModel(email=email, username=username) user.set_password(password) db.session.add(user) db.session.commit() return redirect('/login') return render_template('register.html') @app.route('/logout') def logout(): logout_user() return redirect('/login')
  • These are all methods to login register and logout in flask login.
  • Also, there are autentication models.
That's all thanks for reading 😁

Comments

Popular posts from this blog

How to upload files in flask API?

Hello everyone, In this tutorial. we are going to create an API that getting image files to save on the server. So our requirement is very simple. We are using flask as our framework for creating API. Then we use a simple HTML template where we create a form with a select files field. We send selected files in our API using AjaxJS to save them on the server. First, create a project directory then create a virtual environment for this project. So here I use pipenv to create an environment and you can also use virutalenv. Now install our flask library. Then create a python file. In this minimal start code for flask app. pipenv install flask Now create a method for API you can name it whatever you want. This is our API method. @app . route( '/upload' , methods = [ 'POST' ]) def uploadFile (): We are creating a simple HTML template in a flask and create a method for this to render. <!doctype html> <html lang="en" > <head> <!-- Requi...

Mastering Flask-SQLAlchemy: A Guide to Seamless Database Integration

Introduction Welcome to the world of Flask, a lightweight yet powerful web framework for Python enthusiasts. In today's post, we're diving into Flask-SQLAlchemy, an extension that makes it easier and more efficient to interact with databases using SQLAlchemy, the popular ORM (Object-Relational Mapping) tool for Python. Setting up the Stage Installation: First things first, let's set up our environment. Assuming you have Flask installed, you need to install Flask-SQLAlchemy: pip install Flask - SQLAlchemy Why Virtual Environments? It's always a good idea to work in a virtual environment to keep your project dependencies organized and isolated. SQLAlchemy Basics ORM in a Nutshell: SQLAlchemy as an ORM allows us to interact with our database using Python classes and objects, rather than writing SQL queries directly. The Benefits: This approach not only makes the code more readable but also simplifies database operations and maintenance. Configuring Flask-SQLAlchemy Ki...