← Web apps with Flask

A page from Python

Make a website whose pages come from Python: each address is a route, and a function gives back its page.

Every website you use has code behind it that decides what page to send back. With Flask, a few lines of Python do it.

In HTML & CSS you wrote pages by hand. A web app makes its pages with code, so they can change: show the latest sign-ups, answer a form, look things up. Flask is a small Python library for this. Each address in the site (/, /about) is a route, and each route has a function that gives back the page as HTML.

The first lines (from flask import Flask and app = Flask(__name__)) set up the app: copy them as they are. In this playground, app.run() shows your site in the App tab, with an address bar. On a computer it would be a real web server at http://127.0.0.1:5000.

PredictRead the code and say what it will do before you run anything. A wrong guess is fine: it shows you what to look for.

Predict

club.py
from flask import Flask

app = Flask(__name__)


@app.route("/")
def home():
    return "<h1>Chess club</h1><p>Lunchtime, Room 12</p>"


@app.route("/about")
def about():
    return "<h1>About</h1><p>Everyone is welcome.</p>"


app.run()

The line above each function, starting with @, is a decorator: it joins a function to an address. Which function answers /about?

Someone visits /about. What does the site send back?

RunRun it and compare the result with your prediction.

Run

Run it, then use the links on the page, and type addresses in the bar above it: /about, then /missing. Change the home page's text and run again.

club.py
from flask import Flask

app = Flask(__name__)


@app.route("/")
def home():
    page = "<h1>Chess club</h1>"
    page = page + "<p>Lunchtime on Tuesdays, Room 12.</p>"
    page = page + "<p><a href='/about'>About the club</a></p>"
    return page


@app.route("/about")
def about():
    return "<h1>About</h1><p>Everyone is welcome, from beginners to champions.</p><p><a href='/'>Home</a></p>"


app.run()
Try it yourselfYour edits are saved in this browser.

InvestigateTrace how each line of code connects to what you see.

Investigate

club.py
from flask import Flask

app = Flask(__name__)


@app.route("/")
def home():
    page = "<h1>Chess club</h1>"
    page = page + "<p>Lunchtime on Tuesdays, Room 12.</p>"
    page = page + "<p><a href='/about'>About the club</a></p>"
    return page


@app.route("/about")
def about():
    return "<h1>About</h1><p>Everyone is welcome, from beginners to champions.</p><p><a href='/'>Home</a></p>"


app.run()

What every site does.

Text, joined together.

A page that cannot be reached.

What does a visitor see at /missing?

home() builds page with page = page + ... three times. What is the page?

Clicking "About the club" shows Not Found, though about() is written. Click the line where the problem is.

ModifyChange the code on purpose and check the result.

Modify

Add a /results page with a small table of players and their wins (as on the club page in HTML & CSS), and a link to it from the home page.

Need a hint?

Copy the about route: @app.route("/results"), def results():, and return a heading and a table.

Another hint

Add a link to it on the home page: <a href='/results'>Results</a>.

Count the visits to the home page and show the number on it. Visit it a few times, then press Run again: what happens to the count?

Need a hint?

visits = 0 before the routes. In home(): global visits, then visits = visits + 1.

Another hint

Add the number to the page with str(visits).

Try it yourselfYour edits are saved in this browser.

Add a /results page with a table of players and wins, and link to it from the home page.

    Run your program. This ticks when your code does all of the above.

    Count how many times the home page has been visited, and show the count on it.

      Run your program. This ticks when your code does all of the above.

      MakeBuild something new using what you have learned. Expect a few tries; that is normal.

      Your own site

      Make a small site for a club, a team or a hobby: a home page and at least two more pages, each linking back home.

      Try it yourselfYour edits are saved in this browser.

      Make a site with a home page and at least two more pages, linked to each other.

        Run your program. This ticks when your code does all of the above.

        Info

        Where this leads

        Every web app has this shape: addresses, and code that answers them. Next: build pages from data instead of writing every one by hand.

        The visit counter went back to 0 when you pressed Run. Why?

        For teachers

        Students meet Flask, where each address is a route joined to a function that returns the page as HTML, then add a results page, a visit counter and a small site of their own. About 50 minutes.

        Open the teacher guide: answers, solutions, slides and a worksheet.

        Students will be able to

        Before class

        Read the unit primer first. This course runs in the Python playground (real Python in the browser, Pyodide), where app.run() shows the site in an App tab with an address bar; links and forms in the page go back to the app. On a computer, pip install flask and python app.py serve the same file at http://127.0.0.1:5000. Before teaching it, open the site's Check your school page once on a student device at school. A route (@app.route("/about"), a decorator: the line with @ above a function) joins an address to a function; the function returns the page as HTML text. An address with no route gives the standard 404 Not Found. HTML inside Python strings uses single quotes for attributes (href='/about') so they do not end the string. The visit counter uses global (from the turtle course) and resets on every Run: variables last only while the program runs, which sets up saving in Lesson 4.

        Running the lesson

        1. Predict: draw a table on the board: address on the left, function on the right.
        2. Run: have students type /missing and read the 404 page.
        3. Investigate: ask what the browser receives: just text, which happens to be HTML.
        4. Modify: visit the counter page five times, then press Run, and ask why it reset.
        5. Make: sketch the site's pages and links on paper first.

        The hard part (on purpose)

        Understanding that the browser asks and the function answers. Ask students to say which function runs for each address before they click.

        When students get stuck

        Stretch and support

        Stretch: Add a page at /time that shows a different message in the morning and the afternoon (import datetime; datetime.datetime.now().hour).

        Support: Give students the results route with its table, and ask them only to add the link from the home page.

        Where it leads

        Next lesson builds pages from a list of data with a template. Later lessons take form answers, save them to a file and send data as JSON.

        What each step is for

        Now you can
        Next lesson2. Pages from dataKeep the club's players in a list, and let a template build the pages from it: one table for all, and a page for each player.