How to Store Username and Password in Flask
This article covers storing usernames and passwords in a Flask web app using MySQL. After logging in, users see a welcome message with their username.
Installation
To make our project we first create a virtual environment, to learn how to create and activate a virtual environment, refer to - Python virtual environment.
After creating and activating virtual environment install Flask and Flask-MySQLdb using the following command-
pip install Flask Flask-MySQLdb
Template Folder
Create a "Templates" folder and in the templates folder we create three files in it-
register.html
This HTML file contains a straightforward registration form that asks for three inputs: username, email address and password.
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>User Registration Form</title>
</head>
<style>
.hi{
color: green;
}
.ok{
display: block;
margin-left: 80px;
margin-top: -15px;
border: 1px solid black;
}
.gfg{
margin-left: 30px;
font-weight: bold;
}
.gf{
margin-left: 10px;
font-weight: bold;
}
.btn{
margin-top: 20px;
width: 80px;
height: 25px;
background-color: orangered;
color: white;
}
.y{
color: gray;
}
</style>
<body>
<div class="container">
<h2 class="hi" > GFG User Registration </h2>
<h4 class="y" >Note : fill following details !</h4>
<form action="{{ url_for('register') }}" method="post">
{% if message is defined and message %}
<div class="alert alert-warning"> <strong> {{ message }} ???? </strong></div>
{% endif %}
<br>
<div class="form-group">
<label class="gfg">Name:</label>
<input class="ok" type="text" class="form-control" id="name" name="name" placeholder="Enter name" name="name">
</div>
<div class="form-group">
<label class="gfg">Email:</label>
<input class="ok" type="email" class="form-control" id="email" name="email" placeholder="Enter email" name="email">
</div>
<div class="form-group">
<label class="gf">Password:</label>
<input class="ok" type="password" class="form-control" id="password" name="password" placeholder="Enter password" name="pswd">
</div>
<button class="btn" type="submit" class="btn btn-primary">Register</button>
<p class="bottom">Already have an account? <a class="bottom" href="{{url_for('login')}}"> Login here</a></p>
</form>
</div>
</body>
</html>
Output:

login.html
In login.html, we have two input fields for username and password. If the correct credentials are entered, the user is redirected to the profile page after successful login.
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>User Login Form</title>
</head>
<style>
.gfg{
display: block;
margin-left: 70px;
margin-top: -15px;
}
.ok{
margin-left: 20px;
font-weight: bold;
}
.btn{
margin-top: 20px;
width: 80px;
height: 25px;
background-color: gray;
color: white;
}
.user{
color: green;
}
</style>
<body>
<div class="container">
<h2 class="user"> GFG User Login</h2>
<form action="{{ url_for('login') }}" method="post">
{% if message is defined and message %}
<div class="alert alert-warning"> <strong> {{ message }} ????</strong></div>
{% endif %}
<br>
<div class="form-group">
<label class="ok">Email:</label>
<input class="gfg" type="email" class="form-control" id="email" name="email" placeholder="Enter email" name="email">
</div>
<div class="form-group">
<label class="pop"> <strong> Password:</strong></label>
<input class="gfg" type="password" class="form-control" id="password" name="password" placeholder="Enter password" name="pswd">
</div>
<button class="btn" type="submit" class="btn btn-primary">Login</button>
<p class="bottom">Don't have an account? <a class="bottom" href="{{url_for('register')}}"> Register here</a></p>
</form>
</div>
</body>
</html>
Output:

user.html
This pages displays a welcome message after a successful login.
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>User Account</title>
</head>
<style>
.gfg{
font-size: 25px;
color: red;
font-style: italic;
}
</style>
<body>
<div class="container">
<div class="row">
<h2>User Profile</h2>
</div>
<br>
<div class="row">
Logged in : <strong class="gfg"> {{ session['name'] }} </strong>| <a href="{{ url_for('logout') }}"> Logout</a>
</div>
<br><br>
<div class="row">
<h2>Welcome to the User profile page...</h2>
</div>
</div>
</body>
</html>
Output:

Setting up Flask app
To create flask app with required routes for login and registration and setting up database has already been discussed in detail in- Login and Registration in Flask. Below is the code for the complete flask app.
from flask import *
from flask_mysqldb import MySQL
import MySQLdb.cursors
import re
# initialize first flask
app = Flask(__name__)
app.secret_key = 'GeeksForGeeks'
# Set MySQL data
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = '________' # Use you mysql password
app.config['MYSQL_DB'] = 'user_table'
mysql = MySQL(app)
def create_table():
cursor = mysql.connection.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS user (
userid INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL
)
""")
mysql.connection.commit()
cursor.close()
# Call the function when the app starts
with app.app_context():
create_table()
@app.route('/')
@app.route('/login', methods=['GET', 'POST'])
def login():
message = ''
if request.method == 'POST' and 'email' in request.form and 'password' in request.form:
email = request.form['email']
password = request.form['password']
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute(
'SELECT * FROM user WHERE email = % s AND password = % s',
(email, password, ))
user = cursor.fetchone()
if user:
session['loggedin'] = True
session['userid'] = user['userid']
session['name'] = user['name']
session['email'] = user['email']
message = 'Logged in successfully !'
return render_template('user.html',
message=message)
else:
message = 'Please enter correct email / password !'
return render_template('login.html',
message=message)
# Make function for logout session
@app.route('/logout')
def logout():
session.pop('loggedin', None)
session.pop('userid', None)
session.pop('email', None)
return redirect(url_for('login'))
@app.route('/register', methods=['GET', 'POST'])
def register():
message = ''
if request.method == 'POST' and 'name' in request.form and 'password' in request.form and 'email' in request.form:
userName = request.form['name']
password = request.form['password']
email = request.form['email']
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute('SELECT * FROM user WHERE email = % s', (email, ))
account = cursor.fetchone()
if account:
message = 'Account already exists !'
elif not re.match(r'[^@]+@[^@]+\.[^@]+', email):
message = 'Invalid email address !'
elif not userName or not password or not email:
message = 'Please fill out the form !'
else:
cursor.execute(
'INSERT INTO user VALUES (NULL, % s, % s, % s)',
(userName, email, password, ))
mysql.connection.commit()
message = 'You have successfully registered !'
elif request.method == 'POST':
message = 'Please fill out the form !'
return render_template('register.html', message=message)
# run code in debug mode
if __name__ == "__main__":
app.run(debug=True)
Explanation:
- Importing Libraries: import Flask for web handling, flask_mysqldb for MySQL database connectivity, and re for input validation.
- Flask App Configuration: configures the app, including MySQL connection settings and a secret key for session handling.
- Login Route (/login): handles user authentication by checking the username and password against the database.
- Logout Route (/logout): ends the session and redirects to the login page.
- Registration Route (/register): handles new user registrations by validating input and inserting user details into the database.
- Running the App: the app runs in debug mode, enabling easy debugging during development.
Run the flask application using command- python app.p in the terminal and visit the development server URL to launch it.
Adding Users
After launching the app, register two users:
- name = GEEK , email = geek@gfg.org, password = 12345
- name = Geek , email = geeks@gfg.org, password = 12345
Now, login to my sql server in the terminal using command- mysql -u root -p and enter your MySQL password when prompted to check if these two users have been added to the table or not.
We can print our current user_table by executing the following query-
use table user
SELECT * FROM user;
Here is the snapshot of the live demonstration:
