Model-View-Controller (MVC) in Python Web Apps

If web programming grabs your interest, you have probably come across the acronym MVC, which stands for Model-View-Controller. As many Pythons online frameworks and even desktop apps use it, you may be aware that it's a prevalent design pattern.

But what does it really mean? If the idea has proven difficult for you to understand, continue reading.

This article will teach you:

  • Learn the MVC pattern by using an analogy based on Legos.
  • Find out what conceptually models, views, and controllers are.
  • Connect your theoretical knowledge to specific instances of web development.
  • Examine bits of Flask code to make the point clear.

Perhaps you grew up building with Legos, or perhaps you're still a die-hard fan now. Therefore, continue reading even if you've never put two Lego pieces together because the analogy may still be a useful foundation for your knowledge.

Explaining the Model-View-Controller Pattern with Lego

Picture yourself seated on the floor of your family room at the age of 10. A large bucket filled with Lego or comparable modular construction components sits in front of you. There are many sized and shaped blocks available:

  • 🟦🟦🟦 Some are blue, tall, and long.
  • 🟥 Some are red and cube-shaped.
  • 🟨🟨 Some are yellow, big, and wide.

You could create anything with so many different Lego parts!

As your thoughts begin to race with all of the possibilities, you hear movement towards the sofa. It's your elder brother, asking for something specific. He's stating, "Hey! Construct me a spacecraft!

You say to yourself, "Well, that might be kind of cool." It's a spacecraft!

So you start working. You begin taking out the Lego pieces you believe you will require. A few large, a few little. The engines and the exterior of the spacecraft have various colours.

Now that you have arranged all of your components, it is time to put the spaceship together. And now, after several hours of laborious effort, this spaceship is in front of you:

Model-View-Controller (MVC) in Python Web Apps

You dash to locate your sibling and present the completed project to him. "Amazing job!" he exclaims. Then he adds in silence:

Could you imagine that creating a web application with the MVC design is similar to creating something with Legos?

User Sends a Request

It was your brother who put out the request for you to make something in the case of the Lego spaceship. When a user wants to visit a certain page in a web application, they do so by providing a URL.

Controller Interprets the Request

You were the controller when you assembled the Lego spaceship for your brother. The code you write is the controller in a web application.

It is the controller's responsibility to comprehend the request and act upon it. The controller is the one who collects and arranges all of the required building pieces.

Models Make the Products

The models are the many kinds of Lego blocks. You take the various forms and sizes that you'll need to assemble the spacecraft. Models assist the controller of a web application in retrieving all the data required from the database to create the goods.

Everything required to construct the finished result is in place once the controller utilises the models to acquire the relevant objects.

View Represents the Final Product

The spacecraft is the perspective in the Lego example. Your brother, the one who made the request, only gets to see the finished result.

The page that a user views in their browser is known as the view in a web application.

Summarizing Your Lego Adventure

You've constructed a spacecraft, won your brother over, and made the connection between the MVC pattern and web application development. You can refer to this brief summary anytime you need to remind yourself of the connection between this tale and web development.

When Constructing With Lego:

  • Your brother asks you to construct a spacecraft.
  • The request is delivered to you.
  • You gather and arrange every Lego piece required to build the spacecraft.
  • You construct the spacecraft out of building blocks, then show your brother the completed object.

These are standard procedures. These may be repeated to create Lego constructions in a wide variety of forms and hues.

Now that you've ingrained this delicately coloured picture into your memory, you may go back and compare it with the online application version of the procedure.

When Developing a Web App:

  • By inputting a URL, a user wants to visit a page.
  • That request is received by the controller.
  • The controller gathers all the required data using the models, arranges it, and provides it to the display.
  • The view renders the final webpage using the data it gets and shows it to the user in their browser.

Once more, your web application performs these general actions repeatedly to provide your consumers with a variety of pages and information:

Here is a further summary, presented in a table:

LegoWebsite
WishBrothers's requestURL request
ExecutionYouController
Building blocksLegoModels
Presentable productSpaceshipView

Well done! Having committed this example to memory, you have established a strong basis for comprehending the Model-View-Controller architecture. You may then go a bit farther and analyse everything from a technical standpoint, with a particular emphasis on Python web programming.

Exploring the Model-View-Controller Pattern in Python Web Development

A request to visit a certain page inside an application is made when you input a URL into your browser to access a web application. However, how does the program determine which page to render and show?

You establish what are referred to as routes while creating a web application. Routes are essentially URL patterns linked to various pages. Thus, the program attempts, in the background, to match a given URL entered by the user with one of the pre-established routes.

Controllers, models, views, and routes are the four main elements that are involved in this.

Routing Requests

Every route has a controller attached to it. More precisely, it's connected to a particular controller action, which is a function inside the controller. Thus, the program looks for a route that matches the URL you input. The controller action linked with that route is called if it is successful.

Using a simple Flask route as an example, you may begin understanding how the Model-View-Controller pattern functions in Python web development:

This is where you define the relationship between the home() view function, which is essentially a controller action, and the base route ("/"). Your web application will call home() when a user requests that base route.

Controllers and Models for Coding

Usually, there are two primary actions you do within the controller action:

  • The models are used to get all the required data out of a database.
  • A view receives that data and produces the desired page.

Typically, you append the information that you obtain from the models to a data structure, such as a dictionary or list. Sending that data structure to the view comes next.

Go ahead and add these features to your Flask example app:

Lines 6 through 8 of your modified view function are where you retrieve data from the database. This code snippet's get_db() method is a stand-in for a database connection function. The code for this function must be written such that it is compatible with the database you intend to use, such as a Python SQL package.

Note: Although the code in these examples theoretically demonstrates how a Flask app operates, in practice it doesn't operate that way on its own. You may receive a working Flask example app by downloading the materials repository, which also includes the script to create an interactive SQLite database and the required Flask boilerplate code.

You assign the list that results from line 8 to the variable entries. Line 9 then sends the list to the index.html template, where a variable named entries is used to make the data available.

Constructing the Views

Lastly, your viewpoint is represented in the index.html file. You may now access the data in the template file since you sent the data structure there using the controller action. After that, you may utilise the data structure's information to produce the HTML content of the page that the user will eventually view in their browser.

You may use the Jinja syntax in your Flask app example to loop over entries and show each one:

Your user will see all of the entries shown sequentially if you have entries in your database. In line 9, you have included an optional else clause that, in the event that there are no entries yet, produces a descriptive text message.

Summarizing the Model-View-Controller Pattern

You have now completed another cycle of the Model-View-Controller paradigm, this time utilising the Flask web framework in Python as a reference. A more thorough, technical synopsis of the MVC request procedure is provided below:

  • By inputting a URL, a user wants to visit a page.
  • The program compares the URL to a pre-planned path.
  • The controller action linked to the route is invoked by the application.
  • All of the required data is retrieved from a database using the models by the controller action, which then loads a view while sending the data structure along.
  • The program displays the requested page to the user in their browser when the view retrieves and renders the data structure.

Though the two methods aren't exactly the same, perhaps you can recognise the conceptual parallels between them when creating a Lego spaceship for your sibling.

You may download the code here to experiment with the Flask sample application and learn more about the extra code needed to make it work.

Conclusion:

Now is the moment to return from your Lego-wielding past. You travelled in search of recollections and metaphors, which you then used to further your comprehension of the Model-View-Controller (MVC) paradigm used in Python web application development.