Created
March 10, 2019 20:18
-
-
Save sleepypioneer/7d475e82c3a5014ec77f704e292f6573 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
import json | |
from http.server import BaseHTTPRequestHandler, HTTPServer | |
HOST_NAME = 'localhost' # !!!REMEMBER TO CHANGE THIS!!! | |
PORT_NUMBER = 9000 | |
class MyHandler(BaseHTTPRequestHandler): | |
def do_HEAD(s): | |
s.send_response(200) | |
s.send_header("Content-type", "text/html") | |
s.end_headers() | |
def do_GET(s): | |
if "json" in s.headers['Content-type']: | |
content_length = int(s.headers['Content-Length']) | |
body = s.rfile.read(content_length) | |
jsonResponse = json.loads(body) | |
s.do_HEAD() | |
s.wfile.write(bytes("<html><head><title>Simple Server</title></head>", "utf-8")) | |
s.wfile.write(bytes("<body><p> Arh wonderful your favourite tree is </p>", "utf-8")) | |
s.wfile.write(bytes("<p> a <b>" + jsonResponse["myFavouriteTree"] + "</b></p>", "utf-8")) | |
s.wfile.write(bytes("</body></html>", "utf-8")) | |
else: | |
s.do_HEAD() | |
s.wfile.write(bytes("<html><head><title>Simple Server</title></head>", "utf-8")) | |
s.wfile.write(bytes("<body><p> I was expecting to find out your favourite tree </p>", "utf-8")) | |
s.wfile.write(bytes("</body></html>", "utf-8")) | |
if __name__ == '__main__': | |
myServer = HTTPServer((HOST_NAME, PORT_NUMBER), MyHandler) | |
print(time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER)) | |
try: | |
myServer.serve_forever() | |
except KeyboardInterrupt: | |
pass | |
myServer.server_close() | |
print(time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBERt)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment