[GTPS][Web] MVC pattern in GTPS
Structuring a Flask Project with the MVC Pattern — A Practical Example
When building web applications in Flask, it’s easy to start mixing route logic, database access, and business rules in a single file. As the project grows, this quickly becomes hard to manage. That’s why applying the Model-View-Controller (MVC) pattern is a smart choice—even for small projects.
In this post, I’ll go through how my current project is structured using the MVC pattern, and why the flow I’m using (View → Controller → Model) is the intended and correct design.
MVC pattern
Model-View-Controller is a design pattern that separates an application into three interconnected layers:
-
Model: Responsible for managing data and interacting with the database.
-
View: Handles presentation logic, such as rendering templates or preparing HTTP responses.
-
Controller: Contains the main logic. It takes input from the View, processes it (possibly using the Model), and returns a result.
Project Structure Example
/project-root /server /controllers game_manager.py # Controller /models mysqldb.py # Model /views blog.py # View (Blueprint)
The actual flow in GTPS
In a case where the user clicks a button to search for a game.
Here’s how the flow looks in code:
View (blog.py)
@blog.route('/search')def search(): search_keyword = request.args.get('search_keyword') result = game_manager.search_game_by_title(search_keyword) return render_template('search_results.html', result=result)-
It handles the HTTP request and passes the keyword to the Controller (
game_manager).
Controller (game_manager.py)
from server.models import mysqldb
def search_game_by_title(title: str): game_data = mysqldb.get_game_by_title(title) # You can add more processing here if needed return game_data-
It receives input from the View, calls the Model, and processes the result.
Model (mysqldb.py)
def get_game_by_title(title: str):cursor = connection.cursor()query = "SELECT * FROM game_table WHERE title = %s"cursor.execute(query, (title,))return cursor.fetchall()
-
It communicates with the database and returns raw data.
Why This Is the Correct MVC Flow
The chain:
View (blog.py)
→ Controller (game_manager.py)
→ Model (mysqldb.py)
…is exactly how MVC is designed to work.
-
The View doesn't talk to the Model directly.
-
The Controller serves as the bridge between the View and the Model.
-
The Model is responsible only for handling and returning data.
Comments
Post a Comment