Minimal Flask Application using MVC design pattern

Syed Arsalan Amin
7 min readDec 12, 2021

--

An easy step-by-step guide to implementing a flask app in an MVC software design pattern.

If you are new to programming you may be used to writing code in a file push the run button and boom your code is running! But that is not the case when you make an organized application with a lot of features.

A common practice is to always follow a software design pattern even if your application is small, in the future if you want to add some features then it would be easier to add if your code is in MVC because your code will be more organized, maintainable, reusable and flexible.

Why use these software design patterns?

If you do not follow these patterns probably you’ll get stuck in some kind of problem that will tease you to progress. Like myself, when I started to learn I got stuck in a cyclic dependency problem. That slowed down my development process. There are a lot of software design patterns but MVC provides the idea of "seperation of concerns." I’ll be following that here.

How this will help you?

I’ve implemented a simple flask application with MySQL database using an MVC design pattern. For using the MySQL database I’ve used the flask-sqlalchemy package which is a popular ORM(object-relational mapper), which is a way to map the database tables to python objects. That makes it easier to work with the database.

In simple words:

“MVC architecture helps us to control the complexity of application by dividing it into three components i.e. model, view and controller”

Tools and Technologies

Below are the Tools and Technologies that we’ll be using:

  • Python.
  • Flask.
  • Model View Controller (MVC).
  • Mysql.
  • Flask-sqlalchemy.

File tree structure

Let's take a look at the file structure:

📦src
┣ 📂controllers
┃ ┗ 📜machineController.py
┣ 📂models
┃ ┗ 📜machine.py
┣ 📂routes
┃ ┗ 📜blueprint.py
┣ 📂services
┃ ┗ 📜user_service.py
┣ 📜app.py
┣ 📜config.py
┗ 📜data.json

Let’s dive deep into this!

We should have knowledge about how server requests and responses work. When a user requests a page from a particular server, it will receive the request and as a result, send a response to the user. The response could be an HTML page.

One thing is important I’m explaining the MVC structure with the flask app, code logic is not important here you can implement your own custom logic!

Routes:

When a user visit URL he will be redirected to the specific page. The router is the address to which the user will be redirected. For example, if the user wants to visit the machines page then he will type http://localhost:5000/machines in the URL bar.

We are using flask-REST API. You can also use FastApi. But for this one, we are using flask. So on hitting a specific endpoint a method will be called that is linked with that endpoint in our case it’s '/machines’ because we are using url_prefix='/machines'. For more efficient use of routes, we use flask blueprints.

What is Blueprint?

In simple words, they record each operation that is performed on the application. When flask generates a URL from an endpoint it will link the view function with a blueprint.

Why use Blueprint?

  • We are using flask blueprints that a way through which we can factor an application into smaller pieces.
  • We can register a blueprint on an application at a URL prefix.
  • We can register multiple blueprints on an application.

Isn’t that amazing!

Now take a look at a high-level overview of the project below.

Overview of MVC Software Design Pattern

Model:

Models represent the data and its related logic. They are the core of the application. It will decide the data that is being transferred between the controller and other business logic. For example, in our case, the controller is responsible for creating a table(Inserttable) in the MySQL database.

In the figure above you can see the illustration that only, the model has access to the database. Models access the database directly and that data is being used by the controller and ultimately for the view to display.

Controller:

The controller is like a middle-man between view and models. They take input and talk directly to the model that will communicate with the database. Here you are only calling the business logic from the services layer.

Note: controller doesn’t communicate directly with the database there is a model between the database and controller.

In the above code index, create and insert method talk to the model. The controller tells the model what to do. The model then communicates with the database and fetches data then comes the view part.

Services layer (business logic):

You can call it an additional layer on top of the controller. It is helpful when your application grows and more features are added to it, it is a better practice to separate the business logic from the application. A service layer adds an additional layer of abstraction between the application and the business logic. It has the core business logic.

Business logic part

Here you can see that I’m reading data from the data.json and using the StateId int value’s binary I decide what to set the state column to in the MYSQL database table(inserttable). You can simply add some data in fields in the table instead of this business logic.

You can think of services as a worker. While the controller is the manager that just handles what to do, services are the workers that do the actual work and return what is required by the API user. In summary:

  • controller(manager): manages the work.
  • services(worker): do the work.

View:

Now the view is the part of the application that is responsible for displaying the data. It can be a simple return string or a fully-fledged HTML page with a beautiful design. I’m not implementing the view part in this tutorial because my major focus is the backend functioning of the app.

Config file:

This file contains the configuration for the database. For other databases, you can use different file configurations.

App file:

This is the main file of the application. It has the modules which we created and then calls that here. First, we are creating an app flask objects, configuring and initializing the database. Then you have to register the blueprint as discussed above. And finally running the application using 'flask run' the command in the terminal.

Flask app requires some environment variables to be set. These are as follows:

Running the app:

Below are the screenshots of the running app. You can see that the app is running on localhost:5000. When we hit on machines/create the table(inserttable) is created and machines/insert inserted the data in the database table.

Table and data:

Below you can see the table and data inserted into the database.

Key Takeaway:

In this tutorial, we not only went through MVC but also implemented a simple flask application with an MVC structure. You can make a flask application in a single file but for more sophisticated applications you have to make use of the MVC structure.

We learned how blueprint works, what is the file structure and how does MVC works practically. Now packaging flask and MySQL database are important. Next, I’ll be dockerizing flask and MySQL database.

MVC has three layers:

Model:

It communicates with the database.

View:

It displays the data on the screen.

Controller:

It is an interconnection between the model and the view layer.

Hurrah! 🥳 Thanks for sticking with me at the end.

Now you know how to make a flask application with an MVC structure. Go ahead implement it and make interesting applications with it. Please upvote and follow me and do share your thoughts and suggestions.

If you are interested in solving real-world problems using data science, machine learning, and advanced technology then we’ve got a lot in common. Follow me to get more of these technical posts.

Thanks for reading!

--

--