Reload Changes in Flask Web App Without Server Restart

Introduction

In this example I am going to show how your application can reload changes without server restart in Flask applications in development environment.

Situations may occur when you need to speed up your development works without having to worry about restarting the server for every change in the piece of code in your application. Flask development server provides such provision using which you can easily achieve the goal.

Applications that use DEBUG mode in development environment will automatically restart whenever files in the application change. This can be a useful feature as it gives a very fast feedback loop for code changes.

flask changes without server restart

Prerequisites

Python 3.9.7, Flask 2.0.2, Flask-MySQL 1.5.2, pymysql 1.0.2, MySQL 8.0.26

To install any Python based module, use command pip install , for example, pip install Flask-Caching.

Project Directory

Create a project root directory called flask-reload-changes-without-server-restart as per your chosen location.

I may not mention the project’s root directory name in the subsequent sections, but I will assume that I am creating files with respect to the project’s root directory.

MySQL Table

The following user table under roytuts database will be used for this tutorial’s example.

CREATE TABLE user (
    id INT unsigned COLLATE utf8mb4_unicode_ci AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50) COLLATE utf8mb4_unicode_ci NOT NULL,
    email VARCHAR(255) COLLATE utf8mb4_unicode_ci NOT NULL,
    phone VARCHAR(15) COLLATE utf8mb4_unicode_ci NOT NULL,
    address VARCHAR(255) COLLATE utf8mb4_unicode_ci NOT NULL,
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

I am inserting a row in the table so that I can test the application right away.

insert into user values(1, 'Soumitra', 'soumitra@roytuts.com', '43256789', 'Earth');

Configure Flask

The following configuration is written into a file app.py:

from flask import Flask

config = {
    "DEBUG": True  # run app in debug mode
}

app = Flask(__name__)

# Flask to use the above defined config
app.config.from_mapping(config)

In the above code I have imported the required module for flask instantiation.

Database Configuration

I have created the below db.py Python script to setup the MySQL database configuration for connecting to database and fetching user information from user table under roytuts database.

As I need to configure database connection with flask module and that’s why I have imported app module and setup the MySQL configuration with flask module.

Make sure to change the database configuration values according to your database setup.

from app import app
from flaskext.mysql import MySQL

mysql = MySQL()
 
# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'root'
app.config['MYSQL_DATABASE_DB'] = 'roytuts'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'

mysql.init_app(app)

Fetch Data from MySQL

Now I am going to create a main.py file that will have the required function defined for fetching data from MySQL database.

import pymysql
from app import app
from db import mysql
from flask import render_template
	
@app.route('/')
def users():
    conn = None
    cursor = None
    try:
        conn = mysql.connect()
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        cursor.execute("SELECT * FROM user")
        rows = cursor.fetchall()
        print(rows)
        return render_template('index.html', rows=rows)
    except Exception as e:
        print(e)
    finally:
        if cursor:
            cursor.close()
        if conn:
            conn.close()

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

Template or View File

Now you need a template page for displaying user records fetched from MySQL database to the end users. This is index.html page kept under directory – templates, which is the standard directory for storing template or view file in flask applications.

<!doctype html>
<title>Python Flask - Reload Changes without Server Restart</title>
<h2>Reload Changes Without Server Restart in Flask</h2>

<div>
	{% for row in rows %}
		<p>Id: {{ row['id']|safe }}</p>
		<p>Name: {{ row['name']|safe }}</p>
		<p>Email: {{ row['email']|safe }}</p>
		<p>Phone: {{ row['phone']|safe }}</p>
		<p>Address: {{ row['address']|safe }}</p>
	{% endfor %}
	<p/>
</div>

I have used |safe so that it won’t translate “dangerous” symbols into html entities (that Jinja2 does by default to escape “dangerous” ones). Use this option if you trust variable’s content because in opposite case there can be vulnerabilities for example XSS.

Deploying the Application

Now navigate to the project’s root directory using command line tool and execute the command python main.py or if your Python is on the classpath then just execute main.py, your server will be started on default port 5000.

If you want to change the port then you can change the line app.run() to app.run(port=5001), where 5001 is the new port.

Your application will be started on port 5000 and you will see that your application has been started in debug mode.

flask changes without server restart

Testing the Application When you hit the URL http://localhost:5000 in the browser to get the below page where user record is shown.

flask changes without server restart

Now let’s say I want to add a heading (<h1>User Details</h1>) to the view file, so the view file looks like below:

<!doctype html>
<title>Python Flask - Reload Changes Without Server Restart</title>
<h2>Reload Changes Without Server Restart in Flask</h2>

<div>
    <h1>User Details</h1>
	{% for row in rows %}
		<p>Id: {{ row['id']|safe }}</p>
		<p>Name: {{ row['name']|safe }}</p>
		<p>Email: {{ row['email']|safe }}</p>
		<p>Phone: {{ row['phone']|safe }}</p>
		<p>Address: {{ row['address']|safe }}</p>
	{% endfor %}
	<p/>
</div>

You don’t need to stop/start or restart the server and if you refresh the page, you will see the following changes:

flask changes without server restart

Note that changing in the view file your application won’t log anything in the console, but changing in the .py (Python) file or scripts your applications will log the changes detected.

Let’s comment the print() line in the users() function of main.py file.

import pymysql
from app import app
from db import mysql
from flask import render_template
	
@app.route('/')
def users():
    conn = None
    cursor = None
    try:
        conn = mysql.connect()
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        cursor.execute("SELECT * FROM user")
        rows = cursor.fetchall()
        #print(rows)
        return render_template('index.html', rows=rows)
    except Exception as e:
        print(e)
    finally:
        if cursor:
            cursor.close()
        if conn:
            conn.close()

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

Now if you check console then you will find the following messages have been logged:

flask changes without server restart

Hope you have understood how to reload changes without restarting server in Flask applications.

Source Code

Download

Leave a Reply

Your email address will not be published.