Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

OS 6.1 (2 of 10): Dynamic pages, forms and cookies

The whole lesson, free. Read it and have a go at the activities. To work the tasks and labs in the real lesson, press Start lab, with no account needed.

55 minutes

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

Why does the page know your name?

You open a shop site. It says "Welcome back, Aisha". Your friend opens the same site. It says "Welcome back, Sam".

It is the same address. But the page is different. Somebody wrote code that builds each page when you ask for it.

How does the site remember you? That is today's puzzle.

Key words

WordWhat it meansExample
Dynamic pageA page that the server builds each time, from data.Welcome back, Aisha
Static pageA page that is the same file for everybody.
FormBoxes on a page where the user types data to send.
Query stringData added to the end of an address, after a question mark.?name=Sam&age=15
StatelessDoes not remember anything from one request to the next.
StatefulRemembers what happened before.
SessionThe server's memory of one user, kept between requests.
CookieA small piece of text the browser keeps and sends back each time.
Front endThe part of a program that the user sees, in the browser.
Back endThe part of a program that runs on the server.
HTTPThe rules a browser and a server use to talk to each other.
EscapeChange special signs so the browser shows them as text.
ValidationChecking that data is sensible before you use it.
HttpOnlyA cookie setting that hides the cookie from JavaScript.

The cells students fill in are left blank in this preview.

Static and dynamic pages

A static page is a file. Everybody gets the same one.

A dynamic page is built when somebody asks. The server looks up data, such as your name or your basket, and puts it into the HTML.

Build HTML from a list

Code: python
from html import escape

items = ["Tea", "Milk", "Biscuits"]

rows = ""
for item in items:
    rows = rows + "<li>" + escape(item) + "</li>"

print("<ul>" + rows + "</ul>")

# Add an item that has a < sign in it. See what escape() does.

Make a free account to save your work and track your progress.

Always escape user text

Warning

Many people think text a user types is safe to put straight into a page. It is not safe if it holds <script>, because that code then runs in other people's browsers. Use escape() on all text from users. It turns < into &lt;, so it shows as text and does not run.

Check: pages and escaping

Have a go

Check: pages and escaping

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Forms send data

A form sends what the user typed to the server. The data arrives as text, like name=Sam&age=15.

The back end must split the text into parts and then validate it. Never trust a form. A user can send anything, even if your page has checks.

Split form data into parts

Code: python
from urllib.parse import parse_qs

body = "name=Sam&age=15"
data = parse_qs(body)
print(data)
print(data["name"][0])

# Each value is a list. Change age to abc. Can you check it is a number?
print(data["age"][0].isdigit())

Make a free account to save your work and track your progress.

The web forgets

The web is stateless. Each request is new. The server does not know that you were here a second ago.

To remember you, the server gives your browser a cookie. The browser sends it back with every request. The server reads it and finds your session, its memory of you.

How a cookie works

sequenceDiagram
  participant B as Browser
  participant S as Server
  B->>S: Request: log in as Aisha
  S-->>B: Page, and Set-Cookie: session=abc123
  B->>S: Next request, with Cookie: session=abc123
  S-->>B: Welcome back, Aisha

Stateless and stateful

StatelessStateful
Remembers you?NoYes
ExampleHTTP, and a page of public newsA shopping basket
Where memory livesNowhereIn a session on the server, found by a cookie
Easy to add more servers?Yes: any server can answerHarder: the memory must be shared

The cells students fill in are left blank in this preview.

Match the word

Have a go

Loading…

Your answers are marked here and are not kept. A college account keeps every student’s marks.

Write a small web back end

Write the four parts of a small web back end. build_page makes safe HTML. handle_form checks form data. parse_cookie reads a Cookie header. make_cookie builds one. Read the comments. Press Run Tests.

Code: python
from html import escape
from urllib.parse import parse_qs
from http.cookies import SimpleCookie


def build_page(title, items):
    # Give back text like: <h1>Shop</h1><ul><li>Tea</li><li>Milk</li></ul>
    # Use escape() on the title and on every item, so a user cannot add a tag.
    return None


def handle_form(body):
    # body is form data as text, like: name=Sam&age=15
    # Good data: give back {"ok": True, "name": "Sam", "age": 15}  (age is a whole number)
    # Name missing or only spaces: {"ok": False, "error": "Name is missing."}
    # Age not a whole number (a minus sign counts as not one here): {"ok": False, "error": "Age must be a whole number."}
    # Age under 1 or over 120:     {"ok": False, "error": "Age must be between 1 and 120."}
    # Check the name first, then the age.
    return None


def parse_cookie(header):
    # header is like: theme=dark; user=sam
    # Give back a dictionary: {"theme": "dark", "user": "sam"}
    return None


def make_cookie(name, value):
    # Give back text like: user=sam; HttpOnly; Path=/
    return None

Make a free account to save your work, or press Start lab to work through the whole lesson.

Key words crossword

Have a go

Loading…

Your answers are marked here and are not kept. A college account keeps every student’s marks.

Exit quiz

Have a go

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teach this lesson with your class

On a college account your students work the tasks and the labs as well, and every mark is kept for you.