Add User and Display Current Username in Flask
0 919
Introduction
Adding user authentication and displaying the current username in a Flask application is essential for personalized user experiences. This guide demonstrates how to implement user registration, login functionality, and display the logged-in user's name using Flask and MySQL.
Setting Up the Flask Application
Begin by installing the necessary packages:
pip install flask flask-mysqldb
Then, configure your Flask application and MySQL connection:
from flask import Flask, render_template, request, redirect, url_for, session
from flask_mysqldb import MySQL
import MySQLdb.cursors
import re
app = Flask(__name__)
app.secret_key = 'GeeksForGeeks'
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'your_mysql_password'
app.config['MYSQL_DB'] = 'user_table'
mysql = MySQL(app)
Creating the User Table
Define a function to create the user table in the MySQL database:
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()
with app.app_context():
create_table()
User Registration Route
Implement the registration route to handle user sign-up:
@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)
User Login Route
Implement the login route to authenticate users:
@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 = 'Incorrect email or password!'
return render_template('login.html', message=message)
Displaying the Current Username
Create a route to display the logged-in user's name:
@app.route('/user')
def user():
if 'loggedin' in session:
return f'Logged in as {session["name"]}'
return redirect(url_for('login'))
Logout Route
Implement the logout route to end the user's session:
@app.route('/logout')
def logout():
session.pop('loggedin', None)
session.pop('userid', None)
session.pop('email', None)
return redirect(url_for('login'))
Conclusion
By following these steps, you can add user authentication to your Flask application and display the current username. This setup provides a foundation for building more complex user management systems.
If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!
Share:


Comments
Waiting for your comments