এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।
High School Computer Science · শ্রেণি 10–12
8The Web: Clients, Servers and HTTP
Sara types the address of the town library’s site and presses Enter. Less than a second later the page is there, with its title, a logo, a search box and two small pictures. In that second her browser and a machine she has never seen exchanged about a dozen messages, each a few lines of plain text, written in an agreed format.
This chapter reads those messages. It runs a small web server on the reader’s own machine, at the address 127.0.0.1, which always means “this computer”, and sends it requests from Python, so that every line that crosses between the two can be printed.
You already know
Data crosses the internet in packets; every machine has an address, and the name system turns names into addresses. A client asks and a server answers (Book 1, grade 8). A browser shows web pages, and a link takes you to another page (Book 1, grade 5). A page is written in HTML, and its look in CSS; the padlock next to an address means the connection is encrypted (Book 1, grade 9).
8.1 The parts of an address
Definition 8.1 (URL)
A URL (uniform resource locator) is the address of a resource on the web. It is made of a scheme (http or https), a host (the name or address of the server), an optional port number, a path naming the resource on that server, an optional query string after a ?, made of name=value pairs separated by &, and an optional fragment after a #, a place inside the resource that the browser keeps for itself.
http, for https.from urllib.parse import parse_qs, urlsplit
address = ("http://library.brenmoor.example:8080"
"/books/search?title=forest&genre=nature#top")
url = urlsplit(address)
print("scheme: ", url.scheme)
print("host: ", url.hostname)
print("port: ", url.port)
print("path: ", url.path)
print("query: ", url.query, "->", parse_qs(url.query))
print("fragment:", url.fragment)
print(urlsplit("https://library.brenmoor.example/").port)
$ python parse_url.py
scheme: http
host: library.brenmoor.example
port: 8080
path: /books/search
query: title=forest&genre=nature -> {'title': ['forest'], 'genre': ['nature']}
fragment: top
None
None.The host names a machine, but one machine can run several servers at once: a web server, a mail server, a game server. The port number tells them apart.
Definition 8.2 (Port number)
A port number is a whole number from to that identifies one program waiting for connections on a machine. A connection goes to a pair (address, port). Web servers usually listen on port for http and for https.
8.2 A request and its response
Definition 8.3 (Protocol)
A protocol is a set of rules for an exchange of messages between programs: who speaks first, the format of each message, and what each answer means.
Definition 8.4 (HTTP, request, response)
HTTP (hypertext transfer protocol) is the protocol of the web. The client sends a request; the server sends back one response. Each message is text: a first line, then header lines, then an empty line, then an optional body. Every line ends with the two characters carriage return and line feed, written \r\n in Python.
Definition 8.5 (Header)
A header is a line Name: value of an HTTP message that gives information about the message: the server’s name (Host), the type of the body (Content-Type), its length in bytes (Content-Length), a cookie, and so on.
To see the messages themselves, the next listing opens a connection to the server and writes a request byte by byte, as a browser would, then prints every line of the response.
import socket
from serve import running
REQUEST = b"GET /hello HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n"
with running(42084):
with socket.create_connection(("127.0.0.1", 42084)) as s:
s.sendall(REQUEST)
reply = b""
while chunk := s.recv(4096):
reply += chunk
for line in reply.split(b"\r\n"):
if not line.startswith(b"Date:"):
print(line)
$ python raw_exchange.py
b'HTTP/1.1 200 OK'
b'Server: BrenmoorSite/1.0'
b'Content-Type: text/plain; charset=utf-8'
b'Content-Length: 20'
b''
b'Hello from Brenmoor\n'
[server] GET /hello HTTP/1.1 -> 200
The helper running, in the chapter’s folder, starts the server in a process of its own on the given port, waits until it accepts connections, and stops it at the end of the with block, printing what the server wrote meanwhile. The Date header is left out of the printout because it changes every second.
Content-Length tells the client where it ends.Here is the server. Its code is grouped in a class, a notion of grade 12; for now, read it as a set of functions that the http.server module calls: do_GET for each GET request, do_POST for each POST request, and self as the way to reach the request and to answer it.
The file starts by importing http.server and urllib.parse, and by naming the folder of the site’s files and the type of each kind of file; then comes the class.
class Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def version_string(self):
return "BrenmoorSite/1.0"
def log_request(self, code="-", size="-"):
print(f"[server] {self.requestline} -> {code}", flush=True)
def reply(self, status, body, kind="text/plain; charset=utf-8", extra=()):
data = body if isinstance(body, bytes) else body.encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", kind)
self.send_header("Content-Length", str(len(data)))
for name, value in extra:
self.send_header(name, value)
self.end_headers() # the blank line
self.wfile.write(data)
def do_GET(self):
url = urlsplit(self.path)
if url.path == "/hello":
self.reply(200, "Hello from Brenmoor\n")
elif url.path == "/old-hello":
self.reply(303, "", extra=[("Location", "/hello")])
elif url.path == "/search":
self.search(parse_qs(url.query))
elif url.path == "/count":
self.count()
elif ".." not in url.path and (FILES / url.path.lstrip("/")).is_file():
file = FILES / url.path.lstrip("/")
self.reply(200, file.read_bytes(), TYPES[file.suffix])
else:
self.reply(404, "No such page\n")
Python’s urllib.request module is a client: it writes the request, reads the response and separates its parts.
import urllib.request
from serve import running
with running(42080):
request = urllib.request.Request("http://127.0.0.1:42080/hello",
headers={"User-Agent": "brenmoor-client"})
with urllib.request.urlopen(request) as response:
print("[client] status:", response.status, response.reason)
for name, value in response.getheaders():
if name != "Date": # changes every second
print(f"[client] {name}: {value}")
print("[client] body:", response.read())
urllib. code/grade-10/08-http-clients-servers/listings/fetch_once.py$ python fetch_once.py
[client] status: 200 OK
[client] Server: BrenmoorSite/1.0
[client] Content-Type: text/plain; charset=utf-8
[client] Content-Length: 20
[client] body: b'Hello from Brenmoor\n'
[server] GET /hello HTTP/1.1 -> 200
Definition 8.6 (Status code)
The status code of a response is a three-digit number whose first digit gives its class: 1xx information, 2xx success (200 OK), 3xx redirection, the resource is elsewhere (303 See Other), 4xx an error of the client (404 Not Found), 5xx an error of the server.
import urllib.error
import urllib.request
from serve import running
with running(42081):
for path in ["/hello", "/old-hello", "/no-such-page"]:
try:
with urllib.request.urlopen("http://127.0.0.1:42081" + path) as response:
print("[client]", path, "->", response.status, "at", response.url)
except urllib.error.HTTPError as error:
print("[client]", path, "->", error.code, error.reason)
$ python status_codes.py
[client] /hello -> 200 at http://127.0.0.1:42081/hello
[client] /old-hello -> 200 at http://127.0.0.1:42081/hello
[client] /no-such-page -> 404 Not Found
[server] GET /hello HTTP/1.1 -> 200
[server] GET /old-hello HTTP/1.1 -> 303
[server] GET /hello HTTP/1.1 -> 200
[server] GET /no-such-page HTTP/1.1 -> 404
/old-hello.A browser does the same, and does more: once the page has arrived, it reads its HTML and sends one more request for each stylesheet and each image the page names.
8.3 Forms and parameters
Definition 8.7 (Form, parameter)
A form is the part of a web page where the user types or chooses values and sends them; each value is sent as a parameter, a pair name=value, to the address that the form names.
<!DOCTYPE html>
<html>
<head>
<title>Brenmoor Library</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Brenmoor Library</h1>
<img src="logo.svg" alt="the library logo">
<form action="/search" method="get">
<label>Title: <input name="title"></label>
<button>Search</button>
</form>
<p>Open every day. <img src="map.svg" alt="map"> <img src="clock.svg" alt="hours"></p>
</body>
</html>
/search?title=forest: the form’s method is get.Definition 8.8 (Methods GET and POST)
The method of a request says what the client wants. GET asks for a resource; its parameters, if any, travel in the query string of the address. POST sends data to the server, such as a form to record; its parameters travel in the body of the request.
def do_POST(self):
length = int(self.headers["Content-Length"])
body = self.rfile.read(length).decode("utf-8")
print(f"[server] body: {body}", flush=True)
if self.path == "/search":
self.search(parse_qs(body))
else:
self.reply(404, "No such page\n")
def search(self, params):
title = params.get("title", [""])[0]
self.reply(200, f"Searching for {title!r}\n")
import urllib.request
from urllib.parse import urlencode
from serve import running
params = urlencode({"title": "forest"})
with running(42082):
url = "http://127.0.0.1:42082/search"
with urllib.request.urlopen(url + "?" + params) as response: # GET
print("[client] GET :", response.read())
with urllib.request.urlopen(url, data=params.encode()) as response: # POST
print("[client] POST:", response.read())
$ python form_get_post.py
[client] GET : b"Searching for 'forest'\n"
[client] POST: b"Searching for 'forest'\n"
[server] GET /search?title=forest HTTP/1.1 -> 200
[server] body: title=forest
[server] POST /search HTTP/1.1 -> 200
Method 8.9 (Choosing between GET and POST)
- A request that only reads (a search, a page) uses GET: its address can be copied, bookmarked and sent again without harm. The rules of HTTP call GET a safe method: it must not change anything on the server.
- A request that changes something (a loan, a message, an order) uses POST, so that a crawler following links or a reloaded page does not repeat it unseen.
- Large data (a file, a long text) goes in a POST body: addresses have a limited length.
- A password never goes in an address: addresses are logged and kept in the browser’s history. It goes in a POST body, over HTTPS.
An address may only hold some ASCII characters, so the others are written by percent-encoding: each byte of their UTF-8 encoding becomes % followed by two hexadecimal digits. In a form’s query string, a space may also be written +.
from urllib.parse import quote, unquote, urlencode
print(quote("café & co"))
print(urlencode({"title": "café & co", "page": 2}))
print(unquote("caf%C3%A9%20%26%20co"))
$ python percent.py
caf%C3%A9%20%26%20co
title=caf%C3%A9+%26+co&page=2
café & co
C3 A9; the space is 20 and & is 26.8.4 Cookies and sessions
Each HTTP request stands alone: the server does not remember the previous one. To recognise a visitor, it hands the browser a small piece of text that the browser sends back.
Definition 8.10 (Cookie, session)
A cookie is a pair name=value that a server sends in a Set-Cookie header and that the browser stores and sends back, in a Cookie header, with every later request to the same server. A session is the series of requests of one visitor that a server links together, usually through a cookie holding a random session identifier, while the session’s data stays on the server.
def count(self):
cookie = self.headers.get("Cookie", "")
visits = int(cookie.removeprefix("visits=") or 0) + 1
self.reply(200, f"Visit number {visits}\n",
extra=[("Set-Cookie", f"visits={visits}")])
import http.cookiejar
import urllib.request
from serve import running
jar = http.cookiejar.CookieJar()
browser = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar))
with running(42083):
for _ in range(3):
with browser.open("http://127.0.0.1:42083/count") as response:
cookie = response.headers["Set-Cookie"]
print("[client]", response.read(), "Set-Cookie:", cookie)
print("[client] the jar holds:", [(c.name, c.value) for c in jar])
$ python cookie_counter.py
[client] b'Visit number 1\n' Set-Cookie: visits=1
[client] b'Visit number 2\n' Set-Cookie: visits=2
[client] b'Visit number 3\n' Set-Cookie: visits=3
[client] the jar holds: [('visits', '3')]
[server] GET /count HTTP/1.1 -> 200
[server] GET /count HTTP/1.1 -> 200
[server] GET /count HTTP/1.1 -> 200
The counter lives in the browser: a visitor could edit the cookie and claim a thousand visits. Anything the server must trust, such as who is logged in, stays on the server, and the cookie holds only an identifier too long and random to guess (Exercise 8.13).
Safe use
Cookies are also how a site, or an advertiser present on many sites, recognises the same browser from visit to visit. Browsers let you see and delete the cookies of each site, block the cookies of sites other than the one you are visiting, and delete everything when the window is closed. A private window starts with no cookies and forgets them at the end.
8.5 What runs where
The server’s code ran on the server: it chose the answer, and the browser received only the result. A page can also carry code that runs in the browser, written in the language JavaScript. Such code reacts to events, a click on a button, a key typed in a box, the end of loading, by running a function called a handler: it can check a form before it is sent, or change part of the page without loading a new one. Whatever runs in the browser can be read and changed by the user, so a server checks every value it receives again.
Definition 8.11 (HTTPS)
HTTPS is HTTP sent over an encrypted connection: the same requests and responses, but anyone who watches the packets on the way sees only unreadable bytes, and the browser checks that the server really is the one named in the address. Grade 12 explains how.
History — The web
The web was proposed in March 1989 by Tim Berners-Lee, then working at a European physics laboratory, as a way to share documents linked to one another. By the end of 1990 the first web server and the first browser ran there, and the address of the first site was info.cern.ch. HTTP, HTML and URLs were the three pieces of the proposal, and they still are.
8.6 Exercises
Exercise 8.1 ★
Give the scheme, host, port, path, query string and fragment of https://maps.brenmoor.example/route?from=3&to=17#map. Which port does the browser use?
Solution
Solution of Exercise 8.1.
Scheme https, host maps.brenmoor.example, no port in the address, path /route, query string from=3&to=17, fragment map. With https and no port, the browser uses port .
Exercise 8.2 ★
Give the class of each status code, and say whose fault each error is: 201, 301, 403, 500, 503.
Solution
Solution of Exercise 8.2.
201: success (the resource was created). 301: redirection (the resource has moved for good). 403: client error (the request is refused). 500 and 503: server errors (the server failed, or is not available for now). The 4xx codes blame the request; the 5xx codes blame the server.
Exercise 8.3 ★
The page’s form has method="get". A user types the lost code and presses Search. Write the request line the browser sends.
Solution
Solution of Exercise 8.3.
GET /search?title=the+lost+code HTTP/1.1: the form’s parameter goes into the query string, and in a form’s query string the spaces become +.
Exercise 8.4 ★
A browser visits /count twice, then deletes the site’s cookies, then visits it once more. What does each response say, and what is in the jar at the end?
Exercise 8.5 ★
Write query_params(url), which returns the dictionary of the parameters of an address’s query string, without urllib. Leave the values percent-encoded.
Solution
Solution of Exercise 8.5.
Cut the address at # and keep what comes before; keep what follows the first ?; split it at each &; split each pair at its first = (exercises/query_params.py). An address without ? gives an empty dictionary.
Exercise 8.6 ★★
A student writes a response by hand as a status line, a Content-Type header, then the body. The client waits and never shows the page. Find the two things missing, and say what each one tells the client.
Solution
Solution of Exercise 8.6.
The empty line after the headers, which tells the client that the headers are over, and the Content-Length header, which tells it how many bytes of body to read. Without them the client cannot know where the headers end or where the body ends, so it keeps waiting for more (exercises/build_response.py).
Exercise 8.7 ★★
In the site, the last branch of do_GET answers 404. What would happen to a request for an unknown path if that branch were missing? Why is an answer always needed?
Solution
Solution of Exercise 8.7.
The function would end without sending anything: the client would wait for a response that never comes, until it gives up. HTTP pairs every request with one response, so even a wrong request must be answered, with an error code that tells the client what went wrong.
Exercise 8.8 ★★
Count the bytes of the request of the raw exchange listing, the \r\n included. How many of them are headers and empty line, and how many request line?
Solution
Solution of Exercise 8.8.
The request line GET /hello HTTP/1.1 has characters, bytes with its line end. Host: 127.0.0.1 takes , Connection: close takes , and the empty line : bytes of headers and empty line. That makes bytes in all, the value computed by the function request_bytes of exercises/build_response.py.
Exercise 8.9 ★★
A login form uses method="get" over http. The address after logging in is /login?user=noor&password=tulip7. List three places where the password can now be read, and correct the form.
Solution
Solution of Exercise 8.9.
The browser’s history, the server’s log of request lines, and every machine on the way, since http is not encrypted (also anyone looking at the screen, and any page the browser reports the address to). Use method="post", so that the password travels in the body, and serve the site over https.
Exercise 8.10 ★★
Percent-encode café & co by hand, as in a path (space as %20). Then explain why a raw & cannot be left inside a query string’s value.
Solution
Solution of Exercise 8.10.
caf%C3%A9%20%26%20co: é is the UTF-8 bytes C3 A9, the space 20 and & 26. In a query string & separates two parameters, so a raw & inside a value would cut it in two and start a parameter named co.
Exercise 8.11 ★★
Add a route /sum?a=2&b=40 to the site that answers the sum, 42, and answers 400 (bad request) when a parameter is missing or not a whole number.
Solution
Solution of Exercise 8.11.
In do_GET, for the path /sum, read a and b from parse_qs(url.query), convert them with int, and answer the sum; if a parameter is missing (KeyError) or not a whole number (ValueError), answer 400 with a short message (exercises/site_plus.py). The tests ask for /sum?a=2&b=40 and get 42, and for /sum?a=2 and get 400.
Exercise 8.12 ★★★
A page names stylesheet and images. Each new connection costs one round trip before the first request, and each request and its response cost one more. How many round trips does loading the page take with a new connection for every request? With a single connection reused? Why can the stylesheet never be requested in the same round trip as the page?
Solution
Solution of Exercise 8.12.
There are requests: the page, stylesheet and images. With a new connection each: round trips. With one connection reused: . The browser learns the stylesheet’s address only by reading the HTML, which arrives at the end of the page’s round trip.
Exercise 8.13 ★★★
Write a route /basket?add=bread that keeps a shopping basket per visitor on the server: a dictionary from a session identifier to the list of items, the identifier made with secrets.token_hex(8) and sent in a cookie. Why is it safer than keeping the basket itself in the cookie?
Solution
Solution of Exercise 8.13.
On a request without a known session cookie, make an identifier with secrets.token_hex(8), store an empty list under it in a dictionary on the server, and send Set-Cookie: session=...; then add the item to that visitor’s list (exercises/site_plus.py). The visitor can see and change only a random identifier, which cannot be guessed; the basket, and anything the server must trust, never leaves the server.
Exercise 8.14 ★★★
A route /a redirects to /b, and /b redirects to /a. What does a client do? Try it with urllib, and explain how a client can detect such a loop.
Solution
Solution of Exercise 8.14.
The client follows /a, /b, /a, … A careless client would loop for ever. urllib remembers the addresses it was sent to: after the same address has come back a few times (nine requests in our run), it stops with an error saying that the redirections would lead to an infinite loop. A client can count the redirections of one request and give up past a limit, or stop when an address comes back.
Exercise 8.15 ★★★
A site deletes a book from its catalogue when GET /delete?book=12 is requested, from a link on an administrator’s page. Describe how a search engine’s crawler, which follows every link it finds, could empty the catalogue, and propose a correct design.
Solution
Solution of Exercise 8.15.
A crawler reads the administrator’s page, finds the links /delete?book=1, /delete?book=2, …, and requests each one with GET, since following a link is a GET: every book is deleted. GET must be safe. Deleting should be a POST, sent by a form button on a page that only a logged-in administrator can reach; a crawler does not submit forms.
8.7 Problem: What One Page Costs
Problem 8.1
Weekend problem — how long the library page takes to load
The program exercises/page_cost.py starts the library site, requests page.html as a browser would, reads it, requests every resource it names, and prints the size of every body. Take a latency of ms: a round trip, a message there and its answer back, takes ms. Opening a connection costs one round trip; each request and its response cost one more.
Part I — One page and its resources.
- Read
page.html: which resources does it name, and with which tags? - How many requests does loading the page take in all?
- Which request must come first, and why?
- Which status code does each of them receive?
Part II — Requests and bytes.
- Run the program. Give the size of each body and the total.
- The response headers of the site take about bytes per response. Estimate the total number of bytes received, headers included. Which part of it is headers?
- The requests a browser sends are about bytes each, with many headers. Compare the bytes sent and the bytes received.
- At megabits per second, how long does it take to receive the bytes of question 6? Compare with one round trip.
Part III — Round trips.
- With a new connection for each request, how many round trips does the page take, and how many milliseconds?
- With one connection reused for every request?
- A browser opens up to six connections at once to one server. With two connections opened together after the HTML has arrived, how many round trips does the page take?
- Which matters more for this page: the number of bytes or the number of round trips?
- With one reused connection, what latency would make the page take a whole second?
Part IV — Caching.
- On a second visit, the browser still holds the four resources. If it asks for each one again with a header saying which copy it has, the server can answer
304 Not Modifiedwith no body. How many round trips does that visit take with one connection? - If the server says, in a header of the first visit, that the resources stay valid for a day, the browser does not ask at all. How many round trips then?
- Why can the HTML page itself rarely be kept that way?
- A reader opens the page ten times a day. With one reused connection, how many round trips per day does the day-long validity save, compared with asking again each time as in question 14?
- State the result: the requests, the bytes and the round trips of the page, and its load time with a new connection per request and with one reused connection.
Solution
Solution of Problem 8.1.
1. style.css, with a link tag, and logo.svg, map.svg and clock.svg, with img tags.
2. : the page and its resources.
3. The page: the other addresses are known only once its HTML has been read.
4. 200 for all five.
5. , , , and bytes: bytes of content.
6. bytes of headers, so about bytes; the headers are more than a third of it.
7. About bytes sent, more than the received: for small resources, the requests cost as much as the answers.
8. bits, at bits per second: about ms, against ms for one round trip.
9. round trips, ms.
10. round trips, ms.
11. round trips for the connection and the page; then each of the two new connections takes round trip to open and for its two resources, at the same time as the other: round trips, ms.
12. The round trips: the bytes take about ms, each round trip ms.
13. round trips in ms: a latency of about ms, which is common on a distant or poor mobile connection.
14. Still round trips: the answers carry no body, but each question still costs a round trip.
15. : the connection and the page.
16. The page changes (new books, opening hours, the results of a search): a copy kept for a day could show stale content.
17. round trips per visit, so per day, seconds of waiting saved.
18. The library page takes requests and bytes of content, about KB with the headers. At a latency of ms it loads in round trips, ms, with a new connection per request, and in round trips, ms, with one reused connection: the time goes into round trips, not bytes.