21 — HTTP — asking a web server
HTTP is how programs ask web servers for pages. The example
examples/http-client.nme asks your own computer for a file over
http://localhost:8000. It is a learning project, not advice.
Serve a folder first, then run the example in a second terminal:
python3 -m http.server 8000
nme run examples/http-client
the server answered: hello from http!
Steps
urllibis a standard Python library, so it needs no installation. The program imports the part that talks to servers and picks a URL:
run it →# part of examples/http-client.nme import urllib.request url = "http://localhost:8000/hello.txt"localhostmeans "this computer", and8000is the port the server from the first terminal listens on.urlopenopens a connection to that URL and returns a response. The response is not text yet — it is bytes — so it must be read and decoded:
run it →# part of examples/http-client.nme with urllib.request.urlopen(url) as response: body = response.read().decode("utf-8")The
withblock closes the connection when it ends, and.decode("utf-8")turns the bytes into a string.The last line shows the answer.
body.strip()removes the newline the server sent with the file:
run it →# part of examples/http-client.nme show "the server answered: " + body.strip()nme checkverifies the program even without a server — checking only needs the syntax, running needs the server:nme check examples/http-clientThe Korean twin
examples/http-client.ko.nmewrites the same program; only the finalshowbecomes말해 "서버 응답: " + body.strip(). Runnme r examples/http-client.koagainst the same folder for the same result in Korean.
Try it yourself
Add a second file, hello2.txt, to the folder you serve and change url to
point at it. Restart nothing — the server reads files on demand — then run the
example again to see the new file.
What you learned
python3 -m http.server 8000serves the current folder onlocalhost:8000.urllib.request.urlopen(url)opens a connection and returns a response.- A response must be read with
.read()and decoded with.decode("utf-8"). body.strip()removes the newline the server sent with the file.