Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add materials for Lego MVC resurfacing #505

Merged
merged 4 commits into from
Mar 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions mvc-legos/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Model-View-Controller (MVC) in Python Web Apps: Explained With Legos

This folder contains a minimal Flask example app that supports the explanation of the MVC pattern in [Model-View-Controller (MVC) Explained – With Legos](https://realpython.com/the-model-view-controller-mvc-paradigm-summarized-with-legos/).

To run the app, you'll need to first install [Flask](https://flask.palletsprojects.com/), preferably into a [virtual environment](https://realpython.com/python-virtual-environments-a-primer/):

```sh
(venv) $ python -m pip install Flask
```

To create and see the SQLite database file, you can then run `create_db.py`:

```sh
(venv) $ python create_db.py
```

Finally, you can start the Flask app by executing `app.py`:

```sh
(venv) $ python app.py
```

When you make a request in your browser by typing the URL of your localhost and port 8000, you'll see how Flask renders the single view that this web app defines.
28 changes: 28 additions & 0 deletions mvc-legos/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import sqlite3

from flask import Flask, g, render_template

DATABASE = "./database.db"

app = Flask(__name__)


def get_db():
db = getattr(g, "_database", None)
if db is None:
db = g._database = sqlite3.connect(DATABASE)
return db


@app.route("/")
def home():
"""Searches the database for entries, then displays them."""
db = get_db()
cur = db.execute("SELECT * FROM entries ORDER BY id DESC;")
entries = cur.fetchall()
print(entries)
return render_template("index.html", entries=entries)


if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000, debug=True)
30 changes: 30 additions & 0 deletions mvc-legos/create_db.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
"""Creates and seeds a SQLite example database."""
import sqlite3

DATABASE = "./database.db"

with sqlite3.connect(DATABASE) as db:
try:
# Create a table in the database
cursor = db.cursor()
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS entries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
text TEXT
);
"""
)

# Insert a new entry to the database
cursor.execute(
"""
INSERT INTO entries (title, text) VALUES (?, ?)
""",
("spaceship", "My MVP MVC Lego spaceship 🚀"),
)

db.commit()
except sqlite3.Error as e:
print(f"An error occurred: {e}")
Binary file added mvc-legos/database.db
Binary file not shown.
7 changes: 7 additions & 0 deletions mvc-legos/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
blinker==1.7.0
click==8.1.7
flask==3.0.2
itsdangerous==2.1.2
jinja2==3.1.3
markupsafe==2.1.5
werkzeug==3.0.1
21 changes: 21 additions & 0 deletions mvc-legos/templates/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Lego Builds</title>
</head>
<body>
<h1>My Favorite Lego Builds</h1>
<p>Here's a list of all my favorite Lego builds:</p>
<ul>
{% for entry in entries %}
<li>
<strong>{{ entry[1] }}:</strong> <!-- title -->
{{ entry[2] }} <!-- text -->
</li>
{% else %}
<li>No entries yet. Add some!</li>
{% endfor %}
</ul>
</body>
</html>
Loading