15.1 The HTTP request-response model
The HTTP protocol is nearly stateless: a user agent (or browser) makes a request and the server provides a response. For services that don’t involve cookies, a client application can take a functional view of the protocol. We can build a client using the http.client
or urllib.request
module. An HTTP user agent can be implemented as a function like the following:
import urllib.request
def urllib_get(url: str) -> tuple[int, str]:
with urllib.request.urlopen(url) as response:
body_bytes = response.read()
encoding = response.headers.get_content_charset("utf-8")
return response.status, body_bytes.decode(encoding)
A program like wget or curl does this kind of processing using a URL supplied as a command-line argument. A browser does...