Resource mentioned in this lesson: Flask Tutorials
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: Routes and Controllers
00:00 It’s finally time to open your editor and start coding. Before you can start, you’ll need to install the Flask library. Luckily, Real Python already has tutorials that will walk you through the installation process.
00:12
They can be found at this link: realpython.com/tutorials/flask/
00:19
With Flask installed, we can create a file called app.py and import Flask with from flask import Flask with a capital F, and then create an app with app = Flask with a capital F, __name__.
00:40
Here, the __name__ variable contains information about the directory the app is in, so that Flask can find the other files involved in your project.
00:47
Now you’re ready to make your first controller. In your project, all your controllers will be functions. You should start with a controller called home.
00:57
For now, you can return a test response just to check everything is working. You might be wondering how Flask knows when to run the home controller.
01:06 You can link it to a specific URL so it runs whenever a user visits that URL. This is done using a route. You can route it to the home or index URL by adding a route with the forward slash URL.
01:20
Now the route is wired up to a controller, you can test if your website works by opening a terminal and, in the same directory as your code, run the command flask run.
01:32 Flask will start a development server and give you a URL where you can preview your site.
01:38
Visiting that URL should show you the Hello World! message from your home controller. Well done! Your actual controller will do two things: fetch a list of movies from the model and display them with a view.
01:52
You can replace the previous return statement with the following lines. First, a function to get the movies from the database and second, use the render_template() function from Flask to render the index.html template.
02:07
You’ll need to import the render_template() function from Flask and the get_movies_from_database() function from the model.
02:15
Well done! You’ve written your first controller. It’s worth noting that the get_movies_from_database() function doesn’t exist yet, nor does the index.html template, but don’t worry, you’ll write those in the next lesson, exploring models and views.
Become a Member to join the conversation.