Flask + PyMySQL : Introduction

Technical Panchayat
3 min readSep 16, 2023

--

Introduction

In the world of web development, having the right tools at your disposal can make all the difference. Flask, a lightweight Python web framework, is perfect for building web applications that are both powerful and flexible. Combine it with PyMySQL, a Python library for MySQL database connectivity, and you have a winning combination that can handle a wide range of web development tasks.

In this post, we’ll delve into Flask and PyMySQL individually to understand their strengths and how they can be used to build dynamic web applications. We’ll also set the stage for our second post, where we’ll take what we’ve learned here and apply it to create a full-fledged CRUD (Create, Read, Update, Delete) REST API.

In this section, we’ll cover the following topics:

  1. Setting up Flask and creating a basic application.
  2. Installing and configuring PyMySQL.
  3. Connecting to a MySQL database.

Flask: A Brief Introduction

Flask is often described as a “micro” web framework of python. What this means is that Flask provides the essentials for building web applications without imposing too many layers or opinions on the developer. This minimalistic approach gives you the freedom to structure your application as you see fit while still benefiting from Flask’s core features.

PyMySQL: A Brief Introduction

PyMySQL is a Python library that simplifies interaction with MySQL databases. MySQL is one of the most popular relational database management systems, and integrating it with Python through PyMySQL allows you to store, retrieve, and manipulate data seamlessly.

Getting Started: Flask and PyMySQL Integration

Project Setup and Configuration

  1. Creating Working Directory & Setting Up Virtual Environment:

For Windows Users:

mkdir flask-mysql-crud-api
cd flask-mysql-crud-api
python -m venv ./env
. ./env/Scripts/activate

For Linux/Ubuntu Users:

mkdir flask-mysql-crud-api
cd flask-mysql-crud-api
python3 -m venv ./env
. ./env/bin/activate

2. Installing Flask

pip install Flask

3. Installing PyMySQL

pip install pymysql

4. Create a MySQL database for your application

CREATE DATABASE flask_crud;

5. Create a new file (app.py), write the following code:

Step 1 : Importing required dependencies and configuring mysql connection:

from flask import Flask, request, jsonify
import pymysql

app = Flask(__name__)

app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = '[YOUR MYSQL USER]'
app.config['MYSQL_PASSWORD'] = '[YOUR MYSQL PASSWORD]'
app.config['MYSQL_DB'] = 'flask_crud'

mysql = pymysql.connect(
host = app.config['MYSQL_HOST'],
user = app.config['MYSQL_USER'],
password= app.config['MYSQL_PASSWORD'],
db = app.config['MYSQL_DB']
)

Step 2 : Automatically Creating a Table When the Server Starts Using Python

def create_table():
try:
print('Creating Table Started =====')
cur = mysql.cursor()
cur.execute(
'''
CREATE TABLE IF NOT EXISTS items (
id INT AUTO_INCREMENT PRIMARY KEY ,
name VARCHAR(255) NOT NULL,
description TEXT
)
'''
)
mysql.commit()
cur.close()
print('Items Table Created =====')
except Exception as e:
print("Error while creating table",e)


@app.route('/')
def hello():
return 'Your Flask Server Running'

if __name__ == '__main__':
create_table()
app.run(debug=True)

Step 3: Run your application

Windows:

python app.py

Linux/Ubuntu:

python3 app.py

6. Test Your Server on http://127.0.0.1:5000/:

Items Table is created on the MySQL Server

Conclusion:

In the next post, “Flask + PyMySQL: CRUD Operations,” we’ll take what we’ve learned here and apply it to create a complete CRUD REST API. We’ll integrate Flask and PyMySQL to build an API that can Create, Read, Update, and Delete data in a MySQL database. If you’re excited about building a fully functional web application, stay tuned for the next installment!

--

--