fbpx

Login and Registration with Python, Flask & MySQL

[ad_1]

In our earlier Python tutorial, we’ve defined the way to develop Climate App in Python utilizing Flask. On this tutorial, we’ll clarify the way to implement Person Login and Registration with Python, Flask and MySQL.

Person login and registration is a crucial performance of person module in any net software. The person’s are allowed create their account and login to entry person part.

On this tutorial, we’ll implement performance for person login, logout and registration. We’ll use Flask framework with Python to create net software with login and registration Kind and implement functonality utilizing MySQL database.

So let’s proceed with implementing Login and Registration with Python, Flask and MySQL.

Modules Required

We’ll use folloing modules to implemen login and registration performance.

  • Flask: Flask is a light-weight WSGI net software framework used to create net functions utilizing Python. It may be put in utilizing the under command:
pip set up Flask
  • Flask-MySQLdb: Flask-MySQLdb gives MySQL connection for Flask software. As we’ll develop performance utilizing MySQL database, so we have to set up this module to attach with database. It may be put in utilizing the under command:
pip set up flask-mysqldb

Create MySQL Database

We have to create MySQL database after which person desk to retailer person data.

We’ll create person desk utilizing under question.

CREATE TABLE `person` (
  `userid` int(11) NOT NULL,
  `title` varchar(100) NOT NULL,
  `e-mail` varchar(100) NOT NULL,
  `password` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

ALTER TABLE `person`
  ADD PRIMARY KEY (`userid`);

We additionally insert some person document to for checking login performance.

INSERT INTO `person` (`userid`, `title`, `e-mail`, `password`) VALUES
(1, 'Jhon smith', 'smith@webdamn.com', '123'),
(2, 'Adam William', 'adam@webdamn.com', '123');

Implement Person Login and Registration

We’ll create challenge listing login-register-app and set up all required modules.

Then we’ll create app.py Python file and import required modules reminiscent of Falsk, flask-mysqldb and helper features.

We may even create listing templates in proect folder to maintain template recordsdata.’

Then we’ll create perform login() in app.py to implement person login performance.

@app.route('/login', strategies =['GET', 'POST'])
def login():
    mesage=""
    if request.technique == 'POST' and 'e-mail' in request.kind and 'password' in request.kind:
        e-mail = request.kind['email']
        password = request.kind['password']
        cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        cursor.execute('SELECT * FROM person WHERE e-mail = % s AND password = % s', (e-mail, password, ))
        person = cursor.fetchone()
        if person:
            session['loggedin'] = True
            session['userid'] = person['userid']
            session['name'] = person['name']
            session['email'] = person['email']
            mesage="Logged in efficiently !"
            return render_template('person.html', mesage = mesage)
        else:
            mesage="Please enter right e-mail / password !"
    return render_template('login.html', mesage = mesage)

We’ll create login.html template file in templates listing and create login kind.

Right here is full .login.html file.

<html>
<head>
<meta charset="utf-8">
<meta title="viewport" content material="width=device-width, initial-scale=1">
<title>Person Login Kind</title>
<hyperlink rel="stylesheet" href="https://cdn.jsdelivr.web/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
</head>
<physique>	
<div class="container">
	<h2>Person Login</h2>
	<kind motion="{{ url_for('login') }}" technique="submit">
	    % if mesage is outlined and mesage %
			<div class="alert alert-warning">{{ mesage }}</div>
		{% endif %}
		<div class="form-group">
			<label for="e-mail">E-mail:</label>
			<enter sort="e-mail" class="form-control" id="e-mail" title="e-mail" placeholder="Enter e-mail" title="e-mail">
		</div>
		<div class="form-group">
			<label for="pwd">Password:</label>
			<enter sort="password" class="form-control" id="password" title="password" placeholder="Enter password" title="pswd">
		</div>    
		<button sort="submit" class="btn btn-primary">Login</button>
		<p class="backside">Dont't have an account?  <a category="backside" href="{{url_for('register')}}"> Register right here</a></p>
	</kind>
</div>
</physique>
</html>

When person login efficiently, it’s going to redirect to person.html to show loggedin web page. Right here is full person.html file.

<html>
<head>
<meta charset="utf-8">
<meta title="viewport" content material="width=device-width, initial-scale=1">
<title>Person Account</title>
<hyperlink rel="stylesheet" href="https://cdn.jsdelivr.web/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">              
</head>
<physique>
<div class="container">
	<div class="row">	
		<h1>Person Profile</h1>
	</div>
	<br>
	<div class="row">	
		Logged in : <sturdy>{session.title} | <a href="{{ url_for('logout') }}"> Logout</a>
	</div>
	<br><br>
	<div class="row">
	    
		<h2>Welcome to the person profile web page...</h2> 
	</div>		
</div>
</physique>
</html>

We’ll create perform logout() in app.py to implement logout performance.

@app.route('/logout')
def logout():
    session.pop('loggedin', None)
    session.pop('userid', None)
    session.pop('e-mail', None)
    return redirect(url_for('login'))

We’ll create perform register() in app.py and implement registration performance.

@app.route('/register', strategies =['GET', 'POST'])
def register():
    mesage=""
    if request.technique == 'POST' and 'title' in request.kind and 'password' in request.kind and 'e-mail' in request.kind :
        userName = request.kind['name']
        password = request.kind['password']
        e-mail = request.kind['email']
        cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        cursor.execute('SELECT * FROM person WHERE e-mail = % s', (e-mail, ))
        account = cursor.fetchone()
        if account:
            mesage="Account already exists !"
        elif not re.match(r'[^@]+@[^@]+\.[^@]+', e-mail):
            mesage="Invalid e-mail tackle !"
        elif not userName or not password or not e-mail:
            mesage="Please fill out the shape !"
        else:
            cursor.execute('INSERT INTO person VALUES (NULL, % s, % s, % s)', (userName, e-mail, password, ))
            mysql.connection.commit()
            mesage="You could have efficiently registered !"
    elif request.technique == 'POST':
        mesage="Please fill out the shape !"
    return render_template('register.html', mesage = mesage)

We’ll create register.html template file in templates listing and create registration kind.

Right here is full register.html file.

<html>
<head>
<meta charset="utf-8">
<meta title="viewport" content material="width=device-width, initial-scale=1">
<title>Person Registeration Kind</title>
<hyperlink rel="stylesheet" href="https://cdn.jsdelivr.web/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">              
</head>
<physique>
<div class="container">
	<h2>Person Registration</h2>
	<kind motion="{{ url_for('register') }}" technique="submit">
        % if mesage is outlined and mesage %
			<div class="alert alert-warning">{{ mesage }}</div>
		{% endif %}
		<div class="form-group">
			<label for="title">Identify:</label>
			<enter sort="textual content" class="form-control" id="title" title="title" placeholder="Enter title" title="title">
		</div>
		<div class="form-group">
			<label for="e-mail">E-mail:</label>
			<enter sort="e-mail" class="form-control" id="e-mail" title="e-mail" placeholder="Enter e-mail" title="e-mail">
		</div>
		<div class="form-group">
			<label for="pwd">Password:</label>
			<enter sort="password" class="form-control" id="password" title="password" placeholder="Enter password" title="pswd">
		</div>    
		<button sort="submit" class="btn btn-primary">Register</button>
		<p class="backside">Have already got an account?  <a category="backside" href="{{url_for('login')}}"> Login right here</a></p>
	</kind>
</div>        
</physique>
</html>

Right here is full code from app.py to implement login, logout and registration performance.

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 = 'xyzsdfg'
  
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'user-system'
  
mysql = MySQL(app)
  
@app.route('/')
@app.route('/login', strategies =['GET', 'POST'])
def login():
    mesage=""
    if request.technique == 'POST' and 'e-mail' in request.kind and 'password' in request.kind:
        e-mail = request.kind['email']
        password = request.kind['password']
        cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        cursor.execute('SELECT * FROM person WHERE e-mail = % s AND password = % s', (e-mail, password, ))
        person = cursor.fetchone()
        if person:
            session['loggedin'] = True
            session['userid'] = person['userid']
            session['name'] = person['name']
            session['email'] = person['email']
            mesage="Logged in efficiently !"
            return render_template('person.html', mesage = mesage)
        else:
            mesage="Please enter right e-mail / password !"
    return render_template('login.html', mesage = mesage)
  
@app.route('/logout')
def logout():
    session.pop('loggedin', None)
    session.pop('userid', None)
    session.pop('e-mail', None)
    return redirect(url_for('login'))
  
@app.route('/register', strategies =['GET', 'POST'])
def register():
    mesage=""
    if request.technique == 'POST' and 'title' in request.kind and 'password' in request.kind and 'e-mail' in request.kind :
        userName = request.kind['name']
        password = request.kind['password']
        e-mail = request.kind['email']
        cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        cursor.execute('SELECT * FROM person WHERE e-mail = % s', (e-mail, ))
        account = cursor.fetchone()
        if account:
            mesage="Account already exists !"
        elif not re.match(r'[^@]+@[^@]+\.[^@]+', e-mail):
            mesage="Invalid e-mail tackle !"
        elif not userName or not password or not e-mail:
            mesage="Please fill out the shape !"
        else:
            cursor.execute('INSERT INTO person VALUES (NULL, % s, % s, % s)', (userName, e-mail, password, ))
            mysql.connection.commit()
            mesage="You could have efficiently registered !"
    elif request.technique == 'POST':
        mesage="Please fill out the shape !"
    return render_template('register.html', mesage = mesage)
    
if __name__ == "__main__":
    app.run()

[ad_2]

Source_link

Leave a Comment