webeng/http-server

69 lines
2.1 KiB
Python
Executable File

#!/usr/bin/env python3
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 == "/":
msg = self.get_components(path, query, query_components)
elif path == "/ying":
msg = self.get_ying()
elif path == "/yang":
msg = self.get_yang()
elif path == "/squares":
msg = self.get_squares(query_components)
else:
msg = "Error 404"
self.wfile.write(msg.encode('utf-8'))
def get_squares(self, query_components):
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':
msg = "Invalid Query Components! First key should be 'von', second key 'bis'."
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>"
return msg
def get_ying(self):
msg = "<a href='/yang'>Ying</a>"
return msg
def get_yang(self):
msg = "<a href='/ying'>Yang</a>"
return msg
def get_components(self, path, query, query_components):
msg = f"Path: {path}\nQuery: {query}\nComponents: {str(query_components)}"
return msg
if __name__ == "__main__":
port = 60000
handler = SimpleHandler
address = ('', port)
server = server.HTTPServer(address, handler)
server.serve_forever()