flask sqlalchemy tutorial

Flask SQLAlchemy Tutorial: Login System with Python


Read Time4 Minutes, 41 Seconds

You are trying to build a web application using Flask, and you need to have a login system in it. You need a database to store the login credentials of the users. Here, in this article, I’m going to introduce you with the SQLAlchemy and how to use it in Flask to create a login system in this tutorial.

In this tutorial, we will use MySQL database system. Now, let us first understand what is SQLAlchemy.

Note: This tutorial does not cover the basics of Flask but introduces SQLAlchemy.

Flask SQLAlchemy Tutorial

What is SQLAlchemy?

SQLAlchemy is the database toolkit and it provides the way for Python to interact with the database. You can use any of the MongoDB, PostgreSQL, SQLite, and MySQL.

Installation

pip install Flask-SQLAlchemy

Copy this command and paste it in your terminal. Now you only have to wait for some time for installation to complete.

Let’s Code

@app.route(“/”)
def hello():
return render_template(‘home.html’)

This is what basic Flask Application should be. But we have to create a login system so we will focus on its coding.

The very first thing to do is creating the database. Use your terminal or phpMyAdmin to create the database. After you create the database, go to your text editor and start typing the below code.

flask sqlalchemy

You can directly copy from here. Just do some changes like changing username, password. As you can see in the comment the database name is ‘register’.

from flask import Flask,render_template,url_for,request,session,logging,redirect,flash
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session,sessionmaker

from passlib.hash import sha256_crypt
engine=create_engine("mysql+pymysql://shubham:[email protected]/register")
					#mysql+pymysql://username:[email protected]/databasename
db=scoped_session(sessionmaker(bind=engine))

Now create a registration page using HTML.

flask sqlalchemy

Your registration page could be like this. The code is given below.

<div class="container">
		<h1>Register</h1>
		<form action="" method="POST">
			<div class="form-group">
				<input type="text" name="name" class="form-control" placeholder="Name" required>
			</div>
			<div class="form-group">
				<input type="text" name="username" class="form-control" placeholder="Usernameame" required>
			</div>
			<div class="form-group">
				<input type="password" name="password" class="form-control" placeholder="Password" required>
			</div>
			<div class="form-group">
				<input type="password" name="confirm" class="form-control" placeholder="Confirm Password" required>
			</div>
			<button class="btn btn-primary" type="submit">Submit</button>
			
		</form>
		
	</div>

Note: You can use navbar in Bootstrap to paste your login and registration on the navigation bar.

Now, let us create a login page as well so that we can clearly focus on python code. The login page can be similar to this.

flask sqlalchemy

Or you can simply copy this code.

 {% if session["log"] %}
	You are logged in already
	
	<!-- <h1>Here goes the user login</h1> -->
{% else %}
	 <div class="container">
	 	<h1>Login</h1>
	 	<form action="" method="POST">
	 		<div class="form-group">
				<input type="text" name="name" class="form-control" placeholder="Name" required>
			</div>
			<div class="form-group">
				<input type="password" name="password" class="form-control" placeholder="Password" required>
			</div>
			<button class="btn btn-primary" type="submit">Submit</button>
	 	</form>
	 </div>
	
{% endif %}

Now comes the main part of the Flask SQLAlchemy tutorial. The Python file! This the code you are going to write. Read it, then read the explanation below.

app = Flask(__name__)

#app.static_folder = 'static'
#register form
@app.route("/register",methods=["GET","POST"])
def register():
	if request.method=="POST":
		name=request.form.get("name")
		username=request.form.get("username")
		password=request.form.get("password")
		confirm=request.form.get("confirm")
		secure_password=sha256_crypt.encrypt(str(password))

		usernamedata=db.execute("SELECT username FROM users WHERE username=:username",{"username":username}).fetchone()
		#usernamedata=str(usernamedata)
		if usernamedata==None:
			if password==confirm:
				db.execute("INSERT INTO users(name,username,password) VALUES(:name,:username,:password)",
					{"name":name,"username":username,"password":secure_password})
				db.commit()
				flash("You are registered and can now login","success")
				return redirect(url_for('login'))
			else:
				flash("password does not match","danger")
				return render_template('register.html')
		else:
			flash("user already existed, please login or contact admin","danger")
			return redirect(url_for('login'))

	return render_template('register.html')

@app.route("/login",methods=["GET","POST"])
def login():
	if request.method=="POST":
		username=request.form.get("name")
		password=request.form.get("password")

		usernamedata=db.execute("SELECT username FROM users WHERE username=:username",{"username":username}).fetchone()
		passworddata=db.execute("SELECT password FROM users WHERE username=:username",{"username":username}).fetchone()

		if usernamedata is None:
			flash("No username","danger")
			return render_template('login.html')
		else:
			for passwor_data in passworddata:
				if sha256_crypt.verify(password,passwor_data):
					session["log"]=True
					flash("You are now logged in!!","success")
					return redirect(url_for('hello')) #to be edited from here do redict to either svm or home
				else:
					flash("incorrect password","danger")
					return render_template('login.html')

	return render_template('login.html')

We have created object DB in the first coding snippet. execute() is used to execute the SQL commands.

Flash is used to display messages on the screen regarding the login details. SHA is used to encrypt the password of the users and session is created so if the user is logged in then only he/she can view certain links.

Here’s one Machine Learning application I build using algorithms, Flask and SQLAlchemy.

As you read Flask SQLAlchemy tutorial, you might wonder what if I used Django? That’s why you might like: Flask vs Django: Which Python Framework is best for Machine Learning app?


Shubham

Shubham is an ambitious coder. He mostly writes about cloud computing and upcoming technical gadgets. He has widely influenced by the technological world and love to express his judicial opinion on happening activities. And yes he's massive Liverpool Fan.

Leave a Reply

avatar
  Subscribe  
Notify of