Person Administration System with Python, Flask and MySQL

[ad_1]

In our earlier Python tutorial, we’ve defined how one can develop Climate App in Python utilizing Flask. On this tutorial, we are going to clarify how one can develop Person Administration System with Python, Flask and MySQL.

Person part is a crucial a part of any net utility through which customers are created, up to date, deleted, considered and many others. We are able to simply develop person managment system in Python utilizing Flask and MySQL packages.

So let’s proceed to develop Person Administration System with Python, Flask and MySQL.

Software Setup

We are going to create utility listing user-management-system-python utilizing under command.

$ mkdir user-management-system-python

then moved inside challenge direcotry

$ cd user-management-system-python

Modules Required

We are going to use folloing modules on this utility from Python.

  • Flask: It’s a micro framework from Python to create net utility. So we are going to set up this module to create net functions. We are going to set up it utilizing the under command:
pip set up Flask
  • flask_mysqldb: That is Python bundle that can be utilized to connect with MySQL database. We are going to set up it utilizing the under command:
pip set up flask_mysqldb

Create MySQL Database and Desk

We are going to create MySQL database user-system and create deskperson to retailer customers particulars.

CREATE TABLE `person` (
  `userid` int(11) NOT NULL,
  `identify` varchar(100) NOT NULL,
  `e-mail` varchar(100) NOT NULL,
  `password` varchar(255) NOT NULL,
  `function` enum('admin','person') NOT NULL,
  `nation` varchar(350) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

ALTER TABLE `person`
  ADD PRIMARY KEY (`userid`);
  
ALTER TABLE `person`
  MODIFY `userid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;

Create Software File

We are going to create utility file app.py into challenge root listing.

Then we are going to import put in module Flask and flask_mysqldb with it’s helpers.

we are going to create Flask app and assign app.config vaues for MySQL database connection to entry database.

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('/')


if __name__ == "__main__":
    app.run()

Implement Person Login Part

We are going to create template file templates/login.html and create FORM with enter and submit button.

<type motion="{{ url_for('login') }}" technique="put up">
	
		<div class="alert alert-warning">{{ mesage }}</div>
	{% endif %}
	<div class="form-group">
		<label for="e-mail">Electronic mail:</label>
		<enter kind="e-mail" class="form-control" id="e-mail" identify="e-mail" placeholder="Enter e-mail" identify="e-mail">
	</div>
	<div class="form-group">
		<label for="pwd">Password:</label>
		<enter kind="password" class="form-control" id="password" identify="password" placeholder="Enter password" identify="pswd">
	</div>    
	<button kind="submit" class="btn btn-primary">Login</button>		
</type>

Then we are going to create perform login() in app.py file and name perform render_template() to render login.html file to load person login web page. We are going to implement login performance by executing SQL question to carry out person login.

@app.route('/login', strategies =['GET', 'POST'])
def login():
    mesage=""
    if request.technique == 'POST' and 'e-mail' in request.type and 'password' in request.type:
        e-mail = request.type['email']
        password = request.type['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:            
            if person['role'] == 'admin':
                session['loggedin'] = True
                session['userid'] = person['userid']
                session['name'] = person['name']
                session['email'] = person['email']
                mesage="Logged in efficiently !"
                return redirect(url_for('customers'))
            else:
               mesage="Solely admin can login" 
        else:
            mesage="Please enter right e-mail / password !"
    return render_template('login.html', mesage = mesage)
  
@app.route('/logout')

Implement Add New Person

We are going to create template file templates/register.html and create person FORM with enter and submit button.

<type motion="{{ url_for('register') }}" technique="put up">
	
		<div class="alert alert-warning">{{ mesage }}</div>
	{% endif %}
	<div class="form-group">
		<label for="identify">Title:</label>
		<enter kind="textual content" class="form-control" id="identify" identify="identify" placeholder="Enter identify">
	</div>
	<div class="form-group">
		<label for="e-mail">Electronic mail:</label>
		<enter kind="e-mail" class="form-control" id="e-mail" identify="e-mail" placeholder="Enter e-mail">
	</div>
	<div class="form-group">
		<label for="pwd">Password:</label>
		<enter kind="password" class="form-control" id="password" identify="password" placeholder="Enter password">
	</div>  
	<div class="form-group">
		<label for="function">Position:</label>
		<choose class="form-control" id="function" identify="function">
			<possibility worth="admin">Admin</possibility>
			<possibility worth="person">Person</possibility>			
		</choose>
	</div>
	<div class="form-group">
		<label for="nation">Nation:</label>
		<enter kind="textual content" class="form-control" id="nation" identify="nation">
	</div>
	<button kind="submit" class="btn btn-primary">Register</button>		
</type>

We are going to implement new person add utilizing type submit put up values. We are going to insert customers particulars into person desk.

@app.route('/register', strategies =['GET', 'POST'])
def register():
    mesage=""
    if request.technique == 'POST' and 'identify' in request.type and 'password' in request.type and 'e-mail' in request.type :
        userName = request.type['name']
        password = request.type['password']
        e-mail = request.type['email']
        function = request.type['role']
        nation = request.type['country']
        cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        cursor.execute('SELECT * FROM person WHERE e-mail = % s', (e-mail, ))
        account = cursor.fetchone()
        if account:
            mesage="Person already exists !"
        elif not re.match(r'[^@]+@[^@]+\.[^@]+', e-mail):
            mesage="Invalid e-mail deal with !"
        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, % s, % s)', (userName, e-mail, password, function, nation))
            mysql.connection.commit()
            mesage="New person created!"
    elif request.technique == 'POST':
        mesage="Please fill out the shape !"
    return render_template('register.html', mesage = mesage)

Implement Person Itemizing

We are going to create templates/customers.html template file and create HTML to show person record. Then implement to loop via person information and show record with particulars.

<desk class="desk table-striped">
    <thead>
      <tr>
        <th>Title</th>
        <th>Electronic mail</th>
        <th>Position</th>
		<th>Nation</th>
		<th></th>
		<th></th>
		<th></th>
		<th></th>
      </tr>
    </thead>
    <tbody>
	  
      <tr>
        <td>{}</td>
        <td>person.e-mail</td>
        <td>person.function</td>
		<td>person.nation</td>
		<td><a href="https://webdamn.com/user-management-system-with-python-flask-and-mysql/{url_for("view', userid=person.userid)}" class="btn btn-success">View</a></td>
		<td><a href="https://webdamn.com/user-management-system-with-python-flask-and-mysql/{}" class="btn btn-primary">Edit</a></td>
		<td><a href="https://webdamn.com/user-management-system-with-python-flask-and-mysql/{url_for("password_change', userid=person.userid)}" class="btn btn-warning">Change Password</a></td>
		<td><a href="https://webdamn.com/user-management-system-with-python-flask-and-mysql/{url_for("delete', userid=person.userid)}" class="btn btn-danger">Delete</a></td>
      </tr> 
	{% endfor %}	  
    </tbody>
</desk>	

We are going to create perform customers() in app.py and implement performance to get all customers information from database desk and go to template customers.html to show record.

@app.route("/customers", strategies =['GET', 'POST'])
def customers():
    if 'loggedin' in session:
        cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        cursor.execute('SELECT * FROM person')
        customers = cursor.fetchall()    
        return render_template("customers.html", customers = customers)
    return redirect(url_for('login'))
    

Implement Person Edit Part

We are going to create template file templates/edit.html and create person edit type.

<type motion="{{ url_for('edit') }}" technique="put up">
	
		<div class="alert alert-warning">{{ mesage }}</div>
	{% endif %}
	<div class="form-group">
		<label for="identify">Title:</label>
		<enter kind="textual content" class="form-control" id="identify" identify="identify" worth="{}">
	</div>
	<div class="form-group">
		<label for="function">Position:</label>
		<choose class="form-control" id="function" identify="function">
			<possibility worth="admin" chosen{% endif %}>Admin</possibility>
			<possibility worth="person"  chosen{% endif %}>Person</possibility>			
		</choose>
	</div>
	<div class="form-group">
		<label for="nation">Nation:</label>
		<enter kind="textual content" class="form-control" id="nation" identify="nation" worth="{ editUser.nation }">
	</div>
		
	<enter kind="hidden" id="userid" identify="userid" worth="{{ editUser.userid }}">
	<button kind="submit" class="btn btn-primary">Save</button>		
</type>

We are going to create edit() perform in app.py and implement person edit performance and render edit.html template.

@app.route("/edit", strategies =['GET', 'POST'])
def edit():
    msg = ''    
    if 'loggedin' in session:
        editUserId = request.args.get('userid')
        cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        cursor.execute('SELECT * FROM person WHERE userid = % s', (editUserId, ))
        editUser = cursor.fetchone()
        if request.technique == 'POST' and 'identify' in request.type and 'userid' in request.type and 'function' in request.type and 'nation' in request.type :
            userName = request.type['name']   
            function = request.type['role']
            nation = request.type['country']            
            userId = request.type['userid']
            if not re.match(r'[A-Za-z0-9]+', userName):
                msg = 'identify should comprise solely characters and numbers !'
            else:
                cursor.execute('UPDATE person SET  identify =% s, function =% s, nation =% s WHERE userid =% s', (userName, function, nation, (userId, ), ))
                mysql.connection.commit()
                msg = 'Person up to date !'
                return redirect(url_for('customers'))
        elif request.technique == 'POST':
            msg = 'Please fill out the shape !'        
        return render_template("edit.html", msg = msg, editUser = editUser)
    return redirect(url_for('login'))

Implement Person Password Change

We are going to create template file templates/password_change.html and create password change type to implement performance.

<type motion="{{ url_for('password_change') }}" technique="put up">
	
		<div class="alert alert-warning">{{ mesage }}</div>
	{% endif %}		
	<div class="form-group">
		<label for="nation">Password:</label>
		<enter kind="password" class="form-control" id="password" identify="password">
	</div>
	<div class="form-group">
		<label for="nation">Affirm Password:</label>
		<enter kind="password" class="form-control" id="confirm_pass" identify="confirm_pass">
	</div>
	<enter kind="hidden" id="userid" identify="userid" worth="{{ changePassUserId }}">
	<button kind="submit" class="btn btn-primary">Replace</button>		
</type>

We are going to create a perform password_change() in app.py and implement person password change performance.

@app.route("/password_change", strategies =['GET', 'POST'])
def password_change():
    mesage=""
    if 'loggedin' in session:
        changePassUserId = request.args.get('userid')        
        if request.technique == 'POST' and 'password' in request.type and 'confirm_pass' in request.type and 'userid' in request.type  :
            password = request.type['password']   
            confirm_pass = request.type['confirm_pass'] 
            userId = request.type['userid']
            if not password or not confirm_pass:
                mesage="Please fill out the shape !"
            elif password != confirm_pass:
                mesage="Affirm password shouldn't be equal!"
            else:
                cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
                cursor.execute('UPDATE person SET  password =% s WHERE userid =% s', (password, (userId, ), ))
                mysql.connection.commit()
                mesage="Password up to date !"            
        elif request.technique == 'POST':
            mesage="Please fill out the shape !"        
        return render_template("password_change.html", mesage = mesage, changePassUserId = changePassUserId)
    return redirect(url_for('login'))

Implement View Person Particulars

We are going to create templates/view.html file and implement to show person particulars.

<h3>Person Particulars</h3> 
<br>
<h4>{}</h4>
<p><robust>Electronic mail: </robust> person.e-mail. </p>
<p><robust>Position: </robust> person.function </p>
<p><robust>Expertise: </robust> person.nation</p>

We are going to create perform view() in app.py and implement to get person particulars from database desk and go to template view.html to show person particulars.

@app.route("/view", strategies =['GET', 'POST'])
def view():
    if 'loggedin' in session:
        viewUserId = request.args.get('userid')   
        cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        cursor.execute('SELECT * FROM person WHERE userid = % s', (viewUserId, ))
        person = cursor.fetchone()   
        return render_template("view.html", person = person)
    return redirect(url_for('login'))

You’ll be able to obtain the entire supply code of challenge from the Obtain hyperlink under.
Obtain

[ad_2]

Source_link

Leave a Comment