Flask is a lightweight and flexible web framework for Python that is commonly used for building web applications. It provides tools and libraries for quickly developing web applications and APIs in Python.
MySQL is a popular open-source relational database management system (RDBMS) commonly used for web applications. It allows storing, organizing, and managing data using structured query language (SQL).
Step 1: Install MySQL
Next, you need to install the MySQL database server and client on your system. For different operating systems, the process may vary. Refer to the MySQL official documentation for the specific installation instructions based on your OS. Also, create a new MySQL user and database for your Django project.
Step 2: Creating a Virtual Environment
This command creates a new directory called myenv
in your current directory, which contains the virtual environment.
python -m venv myenv
To activate the virtual environment, run the following command:
source myenv/bin/activate
Step 3: Installing Required Libraries
To install Flask using pip, you can run the following command in your terminal or command prompt:
pip install flask
To install Flask-MySQLdb, you can use the following command:
pip install flask-mysqldb
To install the mysql-connector-python package, you can use the following pip command:
pip install mysql-connector-python
Step 4: Creating Table in MySQL
To run the MySQL command with the user root and provide the password interactively, you can use the following command:
mysql -u root -p
To create a new database named flaskandmysql
using the MySQL command-line interface, you can use the following SQL command:
CREATE DATABASE flaskandmysql;
To select the flaskandmysql
database in the MySQL command-line interface, you can use the following SQL command:
USE flaskandmysql;
To create a new table named users
in the flaskandmysql
database with two columns name
and email
, you can use the following SQL command:
CREATE TABLE users(name varchar(20), email varchar(40));
Step 5: Importing the Required Libraries
Create a new Python file, such as app.py
, and import the necessary modules: Flask, render_template, request, redirect, and MySQL.
from flask import Flask, render_template, request, redirect
import mysql.connector
Step 6: Writing the Flask Application
his code initializes a Flask web application. It checks if the script is being run directly and not imported as a module, then it starts the Flask app in debug mode, allowing for real-time debugging of errors. The __name__ == '__main__'
condition ensures that the app starts only when the script is executed directly, not when imported elsewhere.
app = Flask(__name__)
if __name__ == '__main__':
app.run(debug=True)
Step 7: Defining Routes and Views
“def index():” function is for inserting new entries in our “users” table
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
# Fetch form data
userDetails = request.form
name = userDetails['name']
email = userDetails['email']
connection = mysql.connector.connect(
host="localhost",
user="root",
password="chichi2963", #enter your password
database="helloworld" #enter your database name
)
cur = connection.cursor()
cur.execute("INSERT INTO users(name, email) VALUES(%s, %s)",(name, email))
connection.commit()
cur.close()
return redirect('/users')
return render_template('index.html')
“def users():” function is to display the “users” table
@app.route('/users')
def users():
connection = mysql.connector.connect(
host="localhost",
user="root",
password="chichi2963", # enter your password
database="helloworld" # enter your database name
)
cur = connection.cursor()
cur.execute("SELECT * FROM users")
userDetails = cur.fetchall()
return render_template('users.html',userDetails=userDetails)
Step 8: Creating Templates
We need to create HTML templates for our application. Create a folder named templates
in your project directory and create two HTML files: index.html
and users.html
. Here’s a simple example of what these files might contain:
“index.html” is to create a form to receive user details :
<form method="POST" action="" style="display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 20px; border: 1px solid #ddd; border-radius: 5px; box-shadow: 0px 0px 10px rgba(0,0,0,0.1);">
<label for="name" style="font-size: 18px; font-weight: bold; margin-bottom: 5px;">NAME</label>
<input type="text" id="name" name="name" style="padding: 10px; border: 1px solid #ddd; border-radius: 5px; font-size: 16px; width: 300px; margin-bottom: 20px;">
<label for="email" style="font-size: 18px; font-weight: bold; margin-bottom: 5px;">EMAIL</label>
<input type="email" id="email" name="email" style="padding: 10px; border: 1px solid #ddd; border-radius: 5px; font-size: 16px; width: 300px; margin-bottom: 20px;">
<button type="submit" style="padding: 10px 20px; background-color: #007bff; color: #fff; border: none; border-radius: 5px; font-size: 16px; cursor: pointer;">Submit</button>
</form>
“users.html” is to display user details in MySQL table :
<style>
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid black;
padding: 15px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
</style>
<table>
<thead>
<tr>
<th>USER NAME</th>
<th>EMAIL ID</th>
</tr>
</thead>
<tbody>
{% for user in userDetails %}
<tr>
<td>{{user[0]}}</td>
<td>{{user[1]}}</td>
</tr>
{% endfor %}
</tbody>
</table>
Step 9: Running the Application
Finally, let’s run our Flask application:
python app.py
Access the application in your web browser by navigating to http://localhost:5000
Conclusion
In this tutorial, we’ve learned how to build a simple user registration web application using Flask and MySQL. By following these steps, you can create your own web applications with user registration functionality and extend them with additional features as needed. Flask’s simplicity and MySQL’s reliability make them a powerful combination for web development projects.