2019-10-22 15:17:44 +02:00
|
|
|
#!/usr/bin/env python3
|
2019-10-22 12:47:55 +02:00
|
|
|
|
|
|
|
from http import server
|
|
|
|
from urllib import parse
|
|
|
|
|
|
|
|
class SimpleHandler(server.BaseHTTPRequestHandler):
|
|
|
|
|
|
|
|
def do_GET(self):
|
|
|
|
self.send_response(200)
|
|
|
|
self.end_headers()
|
|
|
|
|
|
|
|
parsed = parse.urlparse(self.path)
|
|
|
|
path = parsed.path
|
|
|
|
query = parsed.query
|
|
|
|
query_components = parse.parse_qsl(query)
|
|
|
|
|
|
|
|
if path == "/":
|
2019-10-22 15:44:26 +02:00
|
|
|
msg = self.get_components(path, query, query_components)
|
2019-10-22 12:47:55 +02:00
|
|
|
elif path == "/ying":
|
2019-10-22 15:44:26 +02:00
|
|
|
msg = self.get_ying()
|
2019-10-22 12:47:55 +02:00
|
|
|
elif path == "/yang":
|
2019-10-22 15:44:26 +02:00
|
|
|
msg = self.get_yang()
|
2019-10-22 12:47:55 +02:00
|
|
|
elif path == "/squares":
|
2019-10-22 15:41:11 +02:00
|
|
|
msg = self.get_squares(query_components)
|
2019-10-22 12:47:55 +02:00
|
|
|
else:
|
|
|
|
msg = "Error 404"
|
2019-10-22 15:17:44 +02:00
|
|
|
self.wfile.write(msg.encode('utf-8'))
|
2019-10-22 12:47:55 +02:00
|
|
|
|
2019-10-22 15:41:11 +02:00
|
|
|
def get_squares(self, query_components):
|
2019-10-22 12:47:55 +02:00
|
|
|
if len(query_components) != 2:
|
|
|
|
msg = "Invalid number of Query Components! Two components needed."
|
|
|
|
else:
|
|
|
|
if query_components[0][0] != 'von' or query_components[1][0] != 'bis':
|
2019-10-29 13:16:54 +01:00
|
|
|
msg = "Invalid Query Components! First key should be 'von', second key 'bis'."
|
2019-10-22 12:47:55 +02:00
|
|
|
self.wfile.write(msg.encode('utf-8'))
|
|
|
|
else:
|
|
|
|
try:
|
|
|
|
von = int(query_components[0][1])
|
|
|
|
bis = int(query_components[1][1])
|
|
|
|
except:
|
|
|
|
msg = "One or both query values are not integer."
|
|
|
|
else:
|
|
|
|
msg = "<table border='1'>"
|
|
|
|
for i in range(von, bis+1):
|
|
|
|
msg += f"<tr><td>{i}</td><td>{i**2}</td></tr>"
|
|
|
|
msg += "</table>"
|
2019-10-22 15:17:44 +02:00
|
|
|
return msg
|
2019-10-22 12:47:55 +02:00
|
|
|
|
|
|
|
|
2019-10-22 15:44:26 +02:00
|
|
|
def get_ying(self):
|
2019-10-22 12:47:55 +02:00
|
|
|
msg = "<a href='/yang'>Ying</a>"
|
2019-10-22 15:17:44 +02:00
|
|
|
return msg
|
2019-10-22 12:47:55 +02:00
|
|
|
|
2019-10-22 15:44:26 +02:00
|
|
|
def get_yang(self):
|
2019-10-22 12:47:55 +02:00
|
|
|
msg = "<a href='/ying'>Yang</a>"
|
2019-10-22 15:17:44 +02:00
|
|
|
return msg
|
2019-10-22 12:47:55 +02:00
|
|
|
|
2019-10-22 15:44:26 +02:00
|
|
|
def get_components(self, path, query, query_components):
|
2019-10-22 12:47:55 +02:00
|
|
|
msg = f"Path: {path}\nQuery: {query}\nComponents: {str(query_components)}"
|
2019-10-22 15:17:44 +02:00
|
|
|
return msg
|
2019-10-22 12:47:55 +02:00
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
port = 60000
|
|
|
|
handler = SimpleHandler
|
|
|
|
address = ('', port)
|
|
|
|
|
|
|
|
server = server.HTTPServer(address, handler)
|
|
|
|
server.serve_forever()
|