Exercise 2.4A - Learn and Practice Flask

Purpose: The purpose of these exercises is to teach you to use core features of the Python-Flask web server framework. This exercise has many subparts, but don't let that intimidate you. Each step makes a small tweak meant to teach the features of Flask incrementally. As we do so, we will rebuild the Flask Batpage code you downloaded in Exercise 2.2.

For an honest report of full credit, you must:

Required Reading

To introduce you to Flask, read the intro paragraphs and Table of Contents at the official documentation for Flask: https://flask.palletsprojects.com/en/stable/. Be aware of the links to Jinja and Werkzeug documentation, as Flask relies on them.

Optionally, feel free to read any parts of the Flask documentation that interest you. Prepare to refer back to it for questions or if you want Flask to do things beyond what is taught in class. Like most documentation, some parts will make sense immediately, and some require learning to understand fully.

Look briefly at the official github repo for Flask, maintained by Pallets, an open source community organization, at https://github.com/pallets/flask. Look over README.md.

Step 1. Return a String with Plain Text Content

Flask takes over the routing function of the Server. Instead of delivering files like a general purpose webserver, Flask delivers a string, whatever you your listener function returns. Flask operates by pattern-matching routes and returning a string to the browser. Set up a flask project with nothing but the app.py described below. Follow the instructions beneath the code and beneath the demo.

app.py

When you run this code, look at the Network tab to see the requested URL and response.

Note that there is no reference to app.py, which acts as server.

Note that there is no need for an "index.html" or comparable file, because Flask acts as server.

Change the URL

Step 2. Return a String with HTML Content

Now, create a subdirectory called "static" in your project root and place the batsignal.jpg file (from the previous exercise) into it. The "static" directory is a special subdirectory in Flask (though you can change its name with Flask settings). Flask serves its content the way a simple general webserver would.

Now, change app.py to return a string with HTML instead of plain text, as shown below, and follow the instructions below.

app.py

After running this code, look at the Network tab.

Look at URLs. Compare the original request and the image request URLs. Ponder how the Browser came up with the URLs. Remember that the Browser has no idea what kind of server it is contacting and treats every request as though it is contacting a classic general-purpose web server.

Look at the Responses. Observe the difference between the Response tab (raw), the Preview tab (rendered), and the Browser (fully rendered). Note how the Preview tab does not show the image, because it is not fetched until after the HTML is read.

Change the Routes:To help you understand routing, change the route in app.py from "/" to something else. Enter correct and incorrect URLs into the URL bar.

Step 3. Make Multiple Routes

Add "/about" and "/contact" routes to app.py, as follows:
app.py

Test Your Routes. Go to the "/about" and "/contact" routes in addition to the "/" route. Go to an incorrect route on purpose and observe the error. Observe what happens on the Network tab, Similar to previous steps.

Mess with the Code. Prove to yourself that you can change the listener function names by changing them.

Step 4. Return a Redirect Header Instead of a String

Import the redirect function and make the "/" route redirect to the "/home", as shown below. The following example does this with a relative path. Implement it, then follow the instructions below.

app.py

Network Tab with Preserve Log. Use the Network tab to examine carefully what is happening when the "/" route is redirected to "/home". Clicking the "preserve log" box on will help you see what is happening. The Server first responds to the "/" URL by giving the Browser an HTTP 302 redirect header. The Server then relies on the Browser to follow the redirect instruction and make a new request.

Change Relative to Root-Relative Path. To further build your understanding, change the redirect line as shown below, then follow the instructions below.

app.py

Change the redirect line as follows:

return redirect("/home")

Run on Both Dev Server and CGI and Compare. The root-relative path should work on the Flask dev server or on localhost CGI at document root, but should not work on localhost CGI when in a subdirectory. To understand why, look carefully at how the Browser follows the 302 redirect instruction.

Change back, Deploy to Webhost, and Compare. Our webhost behaves slightly differently than our XAMPP CGI setup depending on whether your URL has a trailing slash. To demonstrate this, change the redirect line back to the relative path as shown below, then deploy to a subdirectory on the webhost.

app.py

Change the redirect line back to:

return redirect("home")

Compare with and without a trailing slash. Try the URL with and without a trailing slash. The version with the trailing slash should succeed. The version with no trailing slash should fail, because the Browser treats the subdirectory as a file instead of a directory and follows the redirect differently. Our XAMPP CGI setup controls for this.

Control on webhost by absolutizing the path. In order to control this issue and keep the code the same on Flask dev server, CGI, and webhost, absolutize the path by using Flask's url_for function, as shown below.

app.py

Change the import line as follows:

from flask import Flask, redirect, url_for

Change the redirect line as follows:

return redirect(url_for("home"))

Take the time you need to examine and understand the steps above. URL and path issues are at the heart of web programming. You may fully expect to run into them over and over, both in this class and every time you set up a webserver. The best way to get a strong understanding is to experience and debug these issues over and over.

Step 5. Accept Variable URLs

Since Flask does not tie URLs to file paths like a general web server, you can add variables into your URLs, freeing you up to make your web application more flexible. Putting variables in URLs allows you to create dynamic URLs. Add the following route to app.py, then follow the instructions below.
app.py

Add this route:

Test Routes. Now, test dynamic URLs by entering names:
• Go to
• Go to

Step 6. Variable URLs with Data Types

You can also constrain the data type of variable URLs. Add the following route to the Flask application above:

app.py

Add this route:

Test Routes. Now, test dynamic URLs by entering numbers:
• Go to
• Go to

Break It. Now, try a non-integer. For example:
• Go to

The server should give a 404 "not found" error, because app.route sets up pattern matching for URLs and your non-integer URL fails to match the pattern.

Step 7. Variable URLs that Capture Subdirectories

In the "/hello" and "/defeat" routes above, try to include a subdirectory, like "/hello/Boris/Yeltsin" or "/defeat/5/10". You will discover it does not work, because these paths are considered subdirectories and do not match. You can capture entire variable subdirectories using the path data type. Add the following route to the Flask application above, then follow the instructions below.

app.py

Add this route:

Test Routes. Now, test dynamic URLs as follows:
• Go to
• Go to

Clean up. After your are finished testing the routes, clean up for the next step by deleting or commenting out the "/hello", "/defeat", and "/travel/to" routes. We won't need them after ther point..

Step 8. Return File Contents as a String

To deliver HTML from files instead of strings, we read files into a string and then return that string. This is usually done with Flask's render_template function (see next step), but it can be done with any file handling function. To prove this, download nav.html and footer.html from Exercise 1.4, and put these files in the same directory where app.py is. Changes the links in nav.html as shown below so that it uses flask routes compatible with your app.py. Then change app.py to read nav.html and footer.html into strings as shown below, and in each route listener, add the contents of these strings as shown below.

templates/nav.html

Change only the following portion:

to the following:

and change app.py as follows:

app.py

Note that the CSS is missing from our batpage. We will add it in Step 15.

Look at URLs. Look carefully at the URLs and responses in the Network tab each time you click on a page. Notice that the Browser requests the page but there is no trace of nav.html or footer.html. The Browser is completely unaware of how the server is generating the HTML or what files are on the server.

Step 9. Use render_template instead of file.read

The render_template function also reads files into strings. We use it because it has flexibility that we will explore in the next steps. Add render_template to the import as shown below. Move your nav.html and footer.html files from the directory where app.py is to a new subdirectory called "templates". The render_template function requires files to be in that directory (although there is a way to change that setting). One odd little restriction is that render_template needs to run inside a route listener, so in the example below, we awkwardly repeat render_template a few times (to be fixed soon). The point of this awkwardness is to drive it home that render_template just reads files into a string.

app.py
Demo
The code should give the same output as before.
Test the "/", "/about", and "/contact" routes.

Mess with the templates directory. Just to prove to yourself how routing works, copy your nav file back to the project root directory where app.py is. Change the content so the two nav files have different content to prove to yourself that the content is not loaded.

Look at URLs. Look carefully at the URLs and responses in the Network tab each time you click on a page. Notice that there is still no trace of nav.html or footer.html.

Step 10. Use Server-Side Includes with Jinja

It is considered best form to render a single template at a time (to keep your Flask server simple), and to put all HTML content inside templates when possible (for separation of concerns).

To make this happen, we will use the flexibility features of the render_template function, which allows you to mark up files in a format called Jinja. Use Jinja's {% include %} block as shown below to include nav.html and footer.html in templates for each page, then simplify app.py as shown below to include only the templates in question.

templates/home.html
templates/about.html
templates/contact.html
app.py
Demo
The code should give the same output as before.
Test the "/", "/about", and "/contact" routes.

Look at URLs. Look carefully at the URLs and responses in the Network tab each time you click on a page. Notice that there is still no trace of nav.html or footer.html. Although our templates are set up more like a traditional webpage.

Ponder: Two Meanings of the Word "Render". The name "render_template" can be misleading, because we also use the word "render" to describe something only the Browser does (render content to screen). The render_template function does not do anything with the screen. The server has no connection to your screen. The render_template function "renders" Jinja into HTML (string conversion, turning one format into another). So now, when we use the word "render", check whether we mean server-side rendering (string conversion) or client-side rendering (drawing).

Step 11. Pass Simple Variables with Jinja

Jinja allows you to use Python variables in your HTML templates, enclosed in double curly-braces {{ }}. Those variables must be passed as named parameters in render_template, each with a name and a value. To demonstrate this, replace the Nav items with variables a, b, and c, as shown below, and modify app.py to pass those variables as shown below.

templates/nav.html

Change only the following portion:

to the following:

and change app.py as follows:

app.py
Demo
The code should give the same output as before.
Test the "/", "/about", and "/contact" routes.

Ponder: The Order in Which This Code Runs. Take a moment to appreciate what happens in what order. When the render_template function is run, Jinja reads the template file into a string. When it encounters the included file nav.html, it recursively calls itself to render that template. It reads nav.html into a string. It then replaces {{ a }}, {{ b }}, and {{ c }} with the values you provided. It then replaces the {% include %} directive with the resulting string. It does not parse the HTML or interpret tags or process nesting of tags or any of that. All that is the Browser's job. The render_template function just does string replacements, then passes on the result.

Step 12. Pass Data Structures with Jinja

It is often desirable to pass more complex variables to a Jinja template. Python list, dict, set, tuple, and range variables can be passed in just as easily as simple variables. We will use this feature to control the nav from the server. Create a global variable called nav with a JSON-compatible object (list of dict in this case) as shown below. Pass nav to each template as shown below.

templates/nav.html (After)

Change the same portion as above to:

Change app.py as follows:

app.py
Demo
The code should give the same output as before.
Test the "/", "/about", and "/contact" routes.

Ponder: Variable scope in Jinja templates. Take a moment to ponder variable scope in Jinja templates. You may notice that even though nav.html is included using a Jinja {% include %} directive, it still sees the variables passed from render_template. In Jinja, variables passed by the render_template function are global to all templates rendered. None are local.

Step 13 Use Loops with Jinja

You may notice that the structure above would be much better in a loop. Change it to a loop as shown below. Note that Jinja encloses looped content in {% for %} and {% endfor %} blocks, and that the syntax resembles Python.

templates/nav.html

Change this portion:

to this:

Demo
The code should give the same output as before.
Test the "/", "/about", and "/contact" routes.

Step 13.5 Pass a variables to All Jinja Templates at Once

You may notice that it would be nice not to have to pass nav=nav to each template in app.py. To pass a single variable to ALL templates, add the following line just below where nav is defined:

app.jinja_env.globals["nav"] = nav

Then remove nav=nav from your render_template calls. No change is needed in your Jinja templates. They should recognize nav as a global variable.

Step 14. Use Conditionals with Jinja

Jinja also allows if statements, enclosed in {% if %} and {% endif %} blocks. Again, the syntax resembles Python. Add a conditional to the contact page as shown below.

templates/contact.html
app.py

Change the "/contact" render line to the following:

Change the result. To test the conditional, change the value of the boolean variable "batphone" in app.py to toggle the message on and off.

Step 15. Use Layouts (Inherited Templates)

Inherited layouts are more flexible than includes and are a very popular way of templating HTML. We will use an inherited layout to add the full layout to our page, including CSS.

First, download index.css from Exercise 1.4, and put it in the static directory.

Then, create a universal layout.html with replaceable blocks, enclosed in {% block <block name> %} and {% endblock %}, as shown below.

templates/layout.html

Now, modify your pages to inherit layout.html by adding {% extends "layout.html" %} and enclosing all contents inside a matching {% block %} and {% endblock %}, as shown below.

templates/home.html
templates/about.html
templates/contact.html

Flask has many other attributes and methods. Feel free to peruse Flask documentation, the internet, or ask any questions to your instructor or to AI. However, bear the rule in mind that you may only incorporate code into your project that you understand and can explain. In most cases, that will mean staying fairly close to what is taught in class.