Join us and get access to thousands of tutorials and a community of expert Pythonistas.
This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.
Implementing the Architecture: Models and Views
00:00 You know a model is a representation of your data, and a view is how you present the data to a user, but how do you actually write those in Python? To begin, you’ll create a model.
00:11
I’ve provided an example database you can use for this application. It contains one table called movies with three columns: id, title, and year.
00:21
Download the tutorial.db file and save it to the same directory as your code. In a new file called model.py, you should create the get_movies_from_database() function you referenced in the last lesson.
00:35
To interact with the database, you’ll import the sqlite3 library.
00:41
Inside your function, you should connect to the database, execute a query to select the id, title, and year for every movie in the database, and return them.
00:50
It’s also helpful to set the database’s row factory, which will let you reference the movie’s attributes like title and year by name.
01:01
The last thing you’ll need to do to get the app to work is write a view. In this case, your home controller is rendering a template, which is a page of HTML, and passing it your list of movies.
01:13
To write this template, you should create a folder called templates, and inside create a file called index.html. As this isn’t a course on HTML and CSS, I’ve started you off with some boilerplate structure and styling, but you’ll need to finish it off.
01:30
Scroll down until you find the <table> element, and specifically the <tbody> element. Here, you want to add a new table row for every movie.
01:39
You can write a for loop inside a template using this special syntax, wrapping a Python command in a curly brace and percentage symbol. You must also end your for loop explicitly, something you don’t normally do in Python.
01:54
Inside the for loop, you’ll create a table row element with three pieces of table data, the movie ID,
02:11 Now you can see why row factory was useful.
02:15
Returning to the terminal and running your application again, you can see the website in full swing. Your URL has been routed to your home controller, which is fetching the movie data from your model and rendering it with a view, which in this case is just populating the HTML template.
02:31 You now understand a core principle behind a lot of web development. If you want to know what else you might add to this site or how to learn more, check out the next and final video in this course.
Become a Member to join the conversation.