Skip to content
Snippets Groups Projects
Commit 679877a2 authored by James R. Wilcox's avatar James R. Wilcox
Browse files

copy ch8->ch9

parent e7c0b437
No related branches found
No related tags found
No related merge requests found
pre { background-color: gray; }
a { color: blue; }
i { font-style: italic; }
b { font-weight: bold; }
small { font-size: 90%; }
big { font-size: 110%; }
input {
font-size: 16px; font-weight: normal; font-style: normal;
background-color: lightblue;
}
button {
font-size: 16px; font-weight: normal; font-style: normal;
background-color: orange;
}
This diff is collapsed.
import socket
import urllib.parse
ENTRIES = ["James was here"]
def show_comments():
out = "<!doctype html><html><body>"
for entry in ENTRIES:
out += f"<p>{entry}</p>"
out += "<form action=add method=post>"
out += "<p><input name=guest></p>"
out += "<p><button>Sign the book!</button></p>"
out += "</form>"
out += "</body></html>"
return out
def do_request(method, url, headers, body):
if method == "GET" and url == "/":
return "200 OK", show_comments()
elif method == "POST" and url == "/add":
params = form_decode(body)
return "200 OK", add_entry(params)
else:
return "404 Not Found", not_found(url, method)
def form_decode(body):
params = {}
for field in body.split("&"):
name, value = field.split("=", 1)
name = urllib.parse.unquote_plus(name)
value = urllib.parse.unquote_plus(value)
params[name] = value
return params
def add_entry(params):
if 'guest' in params:
ENTRIES.append(params['guest'])
return show_comments()
def not_found(url, method):
out = "<!doctype html>"
out += "<h1>{} {} not found!</h1>".format(method, url)
return out
def handle_connection(conx):
req = conx.makefile("b")
reqline = req.readline().decode("utf8")
method, url, version = reqline.split(" ", 2)
assert method in ["GET", "POST"]
headers = {}
for line in req:
line = line.decode('utf8')
if line == '\r\n':
break
header, value = line.split(":", 1)
headers[header.lower()] = value.strip()
print(method, url, version, headers)
if 'content-length' in headers:
length = int(headers['content-length'])
body = req.read(length).decode('utf8')
else:
body = None
status, body = do_request(method, url, headers, body)
response = "HTTP/1.0 {}\r\n".format(status)
response += "Content-Length: {}\r\n".format(
len(body.encode("utf8")))
response += "\r\n" + body
conx.send(response.encode('utf8'))
conx.close()
if __name__ == "__main__":
s = socket.socket(
family=socket.AF_INET,
type=socket.SOCK_STREAM,
proto=socket.IPPROTO_TCP,
)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('', 8000))
s.listen()
while True:
conx, addr = s.accept()
handle_connection(conx)
<html>
<body>
<form action="/submit" method="post">
<p>Name: <input name=name value=1></p>
<p>Comment: <input name=comment value=2></p>
<p><button>Submit!</button></p>
</form>
</body>
</html>
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment