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

post rest of chapter 8 code

parent 064fd848
No related branches found
No related tags found
No related merge requests found
......@@ -142,7 +142,7 @@ class Tab:
url = elt.attributes["action"]
url = resolve_url(url, self.url)
headers, body = request(url, body)
self.load(url, body)
def scrolldown(self):
max_y = max(self.document.height - (HEIGHT - CHROME_PX), 0)
......@@ -172,11 +172,12 @@ class Tab:
y = obj.y - self.scroll + CHROME_PX
canvas.create_line(x, y, x, y + obj.height)
def load(self, url):
def load(self, url, body=None):
self.url = url
self.scroll = 0
self.focus = None
self.history.append(url)
headers, body = request(url)
headers, body = request(url, body)
self.nodes = HTMLParser(body).parse()
print_tree(self.nodes)
......@@ -305,6 +306,7 @@ class Browser:
self.tabs.append(new_tab)
self.draw()
# if payload == None, then send a GET request
# otherwise, send a POST request with the payload as the body
def request(url, payload=None):
......
import socket
import urllib.parse
counter = 0
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):
print(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
global counter
counter += 1
return "200 OK", f"<html>hello you are the lucky {counter}th visitor</html>"
def handle_connection(conx):
req = conx.makefile("b")
......@@ -20,7 +62,8 @@ def handle_connection(conx):
headers = {}
for line in req:
line = line.decode('utf8')
if line == '\r\n': break
if line == '\r\n':
break
header, value = line.split(":", 1)
headers[header.lower()] = value.strip()
......@@ -40,6 +83,7 @@ def handle_connection(conx):
conx.send(response.encode('utf8'))
conx.close()
if __name__ == "__main__":
s = socket.socket(
family=socket.AF_INET,
......
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