Saya ada aplikasi web (PHP, CI, MySQL) yang mau saya ganti jadi full stack (back end Python, REST API, dengan front end tetap menggunakan script PHP yang sama dengan asalnya. Hanya saja, yang sebelumnya koneksi ke MySQL diubah jadi REST API. Keseluruhan aplikasi ini dibagi menjadi 8 bagian, jadi masing-masing orang akan mengerjakan 12,5% dari keseluruhan aplikasi. Target pekerjaan per bagian (per-orang) adalah 2 minggu. Bonus tambahan bila bisa lebih cepat.
Jadi yang dikerjakan nanti adalah membuat backend (REST API) dan menyesuaikan front end supaya komunikasi data menggunakan API yang dikerjakan.
Keseluruhan project dibagi menjadi 8 bagian, dikerjakan secara terpisah oleh 8 freelancer. Jadi masing-masing pekerja hanya mengerjakan 12,5% dari keseluruhan sistem yang ada.
Sebagai gambaran, potongan pekerjaan anda ada pada video yang kami share. Mungkin akan ada sedikit perbedaan dari video tersebut, tapi tidak akan esensial dan signifikan. (Bagi yang belum mendapatkan akses ke video, berikan akun google anda, untuk saya berikan link dan akses video yang kami letakkan di google drive)
Pekerjaan utamanya adalah mengubah web application yang sudah ada, menjadi full stack system.
Aplikasi yang dikerjakan adalah aplikasi penugasan (task) berupa entri data, persetujuan, pelaporan, dan notifikasi pada beberapa proses/langkah.
Sasaran akhir dari proyek ini adalah memungkinkan penambahan front end berupa mobile app, yang dimungkinkan oleh adanya REST API.
Bagian utama yang dibuat adalah back end, sehingga menggunakan sistem REST API dengan Python FLASK
Bagian front end, yang diubah adalah akses data diubah menjadi akses ke REST API.
API yang dibuat harus mewakili fungsi-fungsi pengolahan data pada aplikasi yang sudah ada. Tidak sebatas CRUD saja. Jadi sasarannya adalah, meminimalkan proses pengolahan data yang dilakukan di front end, dan memindahkannya semaksimal mungkin ke back end.
Akan ada aturan mengenai penulisan code, seperti penamaan variabel, sub routine, indentasi, dll.
Membuat dokumentasi API yang sudah dibuat.
Hasil kerja dikirim melalui GitHub
Hasil kerja dikirim (di-commit) sesering mungkin, setiap hari supaya bisa cepat direview sehingga bila diperlukan perbaikan bisa segera dikomunikasikan. Paling lambat, pengiriman selama 3 hari.
Waktu penyelesaian adalah 2 minggu, bila dirasa perlu dan disepakati maka bisa diberikan toleransi waktu penyelesaian.
Bila ada pekerjaan yang kurang memuaskan, baik itu tidak sesuai spesifikasi, tidak sesuai kesepakatan, tidak selesai, atau hal lain, maka pembayaran akan diberikan secara proporsional sesuai pekerjaan yang dihitung memuaskan.
In this tutorial, we'll be creating a complete login and registration system with Python Flask and MySQL.
Python is currently taking the web development scene by storm, growing consistently every year. It has a low learning curve and therefore much easier to adapt to compared to other known languages (Node.js, PHP, etc.). In addition, Python is relatively new, so it would be advantageous to start learning immediately.
The includes additional features and a download link to the source code.
Contents
1. Getting Started
There are a few steps we need to take before we create our python login and registration system. We need to download and set-up Python and install the packages that our app will depend on.
1.1. What You Will Learn in this Tutorial
Form Design — Design a login and registration form with HTML5 and CSS3.
Templates — Create Flask templates with HTML and Python.
Basic Validation — Validating form data that is sent to the server (username, password, and email).
Session Management — Initialize sessions and store retrieved database results.
MySQL Queries — Select and insert records from/in our database table.
Routes — Routing will enable us to associate the URLs with the functions that we will create.
1.2. Requirements
Download and install Python, for this tutorial I'll be using Python 3.7.2. Make sure to check the Add Python to PATH option on the installation setup screen.
Download and install MySQL Community Server and MySQL Workbench. You can skip this step if you already have a MySQL server installed.
Open command line and Install Python Flask with the command: pip install flask
Install Flask-MySQLdb with the command: pip install flask-mysqldb
1.3. File Structure & Setup
We need to create our project directory and files. You can create the directory anywhere on your computer, as long as Python can access it. Create the directories and files below.
main.py — This will be our main project file, all our Python code will be in this file (Routes, MySQL connection, validation, etc).
index.html — The login form template created with HTML5 and CSS3.
register.html — The registration form template created with HTML5 and CSS3.
home.html — The home template which is restricted to logged-in users.
profile.html — The profile template which is restricted to logged-in users. The user's details will be populated on this page.
layout.html — The layout template for the home and profile templates.
style.css — The CSS3 stylesheet for our login and registration system.
The below instruction will start your web server (Windows):
Make sure your MySQL server is up and running. It should have automatically started if you installed it via the installer. In addition, ensure MySQL is running on port 3306 otherwise you'll encounter connection errors.
Open Command Prompt and navigate to your project directory. You can do this with the command cd c:\your_project_folder_destination on Windows.
Run command: set FLASK_APP=main.py
Run command: set FLASK_DEBUG=1
Run command: flask run
Debug mode will enable us to edit our files without constantly restarting the web server.
2. Creating the Database and setting-up Tables
MySQL Workbench is a GUI for managing our databases. Follow the below instructions on how to get started.
Open MySQL Workbench
Enter your MySQL details
Click Test Connection. If successful, you can click OK
Open your connection
Execute the following SQL statement:
SQL
CREATE DATABASE IF NOT EXISTS `pythonlogin` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
USE `pythonlogin`;
CREATE TABLE IF NOT EXISTS `accounts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL,
`password` varchar(255) NOT NULL,
`email` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO `accounts` (`id`, `username`, `password`, `email`) VALUES (1, 'test', 'test', '[email protected]');
The above SQL statement will create our database pythonlogin with the table accounts, along with a test account that we can use for testing purposes.
The above stylesheet will structure our pages and provide an innovative experience for our users. Feel free to customize the stylesheet (change text color, font sizes, content width, etc).
4. Creating the Login System
We can finally start coding with Python! What we'll do in this section is create the login template, connect to our MySQL database, implement login authentication, and define session variables.
The first thing we need to do is import the packages we're going to use, edit the main.py file, and add the following:
Python
from flask import Flask, render_template, request, redirect, url_for, session
from flask_mysqldb import MySQL
import MySQLdb.cursors
import re
Now that we have imported all the packages we're going to use, we need to create the MySQL and app related variables and configure the MySQL connection details.
Add after:
Python
app = Flask(__name__)
# Change this to your secret key (can be anything, it's for extra protection)
app.secret_key = 'your secret key'
# Enter your database connection details below
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'pythonlogin'
# Intialize MySQL
mysql = MySQL(app)
Ensure to configure the MySQL variables to reflect your MySQL details.
Now we can proceed to create the login page. To do that, we need to create a new route. Routes will enable us to associate our functions with a particular URL.
Add after:
Python
# http://localhost:5000/pythonlogin/ - the following will be our login page, which will use both GET and POST requests
@app.route('/pythonlogin/', methods=['GET', 'POST'])
def login():
# Output message if something goes wrong...
msg = ''
return render_template('index.html', msg='')
As you can see with the login template, we create the form along with the input fields: username and password. The form's method is set to post which determines the type of request we want to send to our server. We'll be using a POST request to send the form data.
If we navigate to http://localhost:5000/pythonlogin/ in our web browser, it will look like the following:
http://localhost:5000/pythonlogin/
If you click the Login button, nothing will happen or will return an error, that's because we haven't implemented the code that handles the POST request.
4.2 Authenticating Users with Python
Now we need to go back to our main.py file and add the authentication code to our route function that we created.
# Check if "username" and "password" POST requests exist (user submitted form)
if request.method == 'POST' and 'username' in request.form and 'password' in request.form:
# Create variables for easy access
username = request.form['username']
password = request.form['password']
With the code above, we use an if statement to check if the requested method is POST and check if the username and password variables exist in the form request. If they both exist, the username and password variables will be created, which will be associated with the form variables.
Add after:
Python
# Check if account exists using MySQL
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute('SELECT * FROM accounts WHERE username = %s AND password = %s', (username, password,))
# Fetch one record and return result
account = cursor.fetchone()
The code above will execute a SQL query that will retrieve the account details from our accounts table in our MySQL database. The username and password variables are associated with this query as that is what we will use to find the account.
Add after:
Python
# If account exists in accounts table in out database
if account:
# Create session data, we can access this data in other routes
session['loggedin'] = True
session['id'] = account['id']
session['username'] = account['username']
# Redirect to home page
return 'Logged in successfully!'
else:
# Account doesnt exist or username/password incorrect
msg = 'Incorrect username/password!'
The code above will determine if the account exists. If it does, the session variables are declared. These session variables will be remembered for the user as they will be used to determine whether the user is logged-in or not.
Session variables basically act like browser cookies. They are stored on the server as opposed to the user's browser.
If the account doesn't exist, we can simply output the error on the login form.
To make sure everything is working correctly, navigate to http://localhost:5000/pythonlogin/ and input "test" in both the username and password fields, and then click the Login button. You should receive a message that outputs "Logged in successfully!".
4.3 Creating the Logout Script
For a user to logout, all we have to do is remove the session variables that were created when the user logged-in.
The above code will remove each session variable associated with the user. Without these session variables, the user cannot be logged-in. Subsequently, the user is redirected to the login page.
We can logout by navigating to the following URL: http://localhost:5000/pythonlogin/logout
5. Creating the Registration System
We need a registration system that users can use to register on our app. What we'll do in this section is to create a new register route and create the registration template, along with the registration form, which will consist of input fields, submit button, etc.
The HTML template above we'll use to register users. It's identical to the login template but also includes the Email input field.
The form's action attribute is associated with the "register" route, as we'll use this route to handle the POST request.
5.2 Registering Users with Python
Now that we have our template created, we can proceed to create the "register" route, which will handle the POST request and insert a new account into our accounts table, but only if the submitted fields are valid.
Go back to the main.py file and add the following:
The above code will select an account with the submitted username and password fields. If the account doesn't exist, we can proceed to validate the input data. Validation will check if the submitted email is valid and check if the username contains only letters and numbers.
Subsequently, the code will insert a new account into our accounts tables.
To test that it is working correctly, navigate to http://localhost:5000/pythonlogin/register and fill out the form and click the Register button. You should receive the following response:
http://localhost:5000/pythonlogin/register
Now we can go back to our index.html file and change this line:
The above code will create the home route function. If the user is logged-in, they will have access to the home page. If not, they will be redirected to the login page.
We also need to create the layout for our logged-in pages. Edit the layout.html file and add:
HTML
from flask import Flask, render_template, request, redirect, url_for, session
from flask_mysqldb import MySQL
import MySQLdb.cursors
import re
0
Now we can easily extend the same layout for both the home and profile pages.
Currently, when a user logs in, there will be a basic output message, we can now change that to redirect the user to our new home page instead. Find the following code in the login route function:
from flask import Flask, render_template, request, redirect, url_for, session
from flask_mysqldb import MySQL
import MySQLdb.cursors
import re
1
Replace with:
Python
from flask import Flask, render_template, request, redirect, url_for, session
from flask_mysqldb import MySQL
import MySQLdb.cursors
import re
2
The user will now be redirected to the home page when they log in. If we enter the test details into the login form and click the Login button, we will see the following:
http://localhost:5000/pythonlogin/home
It's just a simple home page that will output the username. You can implement your own code later.
Next, we'll create the profile page and populate the user's details.
7. Creating the Profile Page
The profile page will populate all details associated with the account (username, password, and email).
Add the following route to the main.py file:
Python
from flask import Flask, render_template, request, redirect, url_for, session
from flask_mysqldb import MySQL
import MySQLdb.cursors
import re
3
The above code will create the profile route and retrieve all the account details from the database, but only if the user is logged-in.
Edit the profile.html file and add:
HTML
from flask import Flask, render_template, request, redirect, url_for, session
from flask_mysqldb import MySQL
import MySQLdb.cursors
import re
4
The above code will extend the layout (layout.html) file that we created previously. If you navigate to the profile page, it will look like the following:
http://localhost:5000/pythonlogin/profile
That's basically it for the home and profile pages. The includes the edit profile feature that will enable the user to change their username, password, and email.
Conclusion
Congratulations! You've successfully created your own login and registration system with Python Flask and MySQL. You're free to use the source code from this tutorial in your application(s).
If you enjoyed this tutorial, don't forget to hit the share button and drop a comment as it will help us create more future content.
If you would like to support us, consider purchasing a package below as it will greatly help us create more quality tutorials and keep our server up and running.
* Payments are processed with PayPal/Stripe. * Advanced package also includes the tutorial source and basic package.
$20.00
PayPal
Download
Stripe
Cryptocurrency
Download
For more detailed information regarding the advanced package, click here.
About Author
David Adams
Enthusiastic website developer, I've been designing and developing web applications for over 10 years, I enjoy the creativity I put into my projects and enjoy what others bring to the awesome web. My goal is to help newcomers learn the ways of the web.