calendar-fetcher/webserver.py

71 lines
1.9 KiB
Python
Raw Normal View History

2023-10-08 21:12:55 +00:00
#!/usr/bin/python
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse, parse_qs
from calendar_fetcher import fetch_calendar
internalPort = 8014
outfile = "data/calendar.json"
# This class will handle any incoming request from
# a browser
class myHandler(BaseHTTPRequestHandler):
# Handler for the GET requests
def do_GET(self):
self.send_response(200)
parsed_url = urlparse(self.path)
query = parse_qs(parsed_url.query)
print("File: %s, query: %s" % (parsed_url.path, query), flush=True)
if parsed_url.path == "/":
self.send_header('Content-type','text/html')
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
self.wfile.write(b"<h1>Calendar Fetcher</h1>\n")
self.wfile.write(b"fetching...<br>\n")
print("fetching...")
self.wfile.flush()
data = fetch_calendar()
self.wfile.write(b"storing...<br>\n")
print("storing...")
self.wfile.flush()
f = open(outfile, "w")
f.write(data)
f.close()
self.wfile.write(b"Done.\nData got written to %s}<br>\n" % bytes(outfile, "utf8"))
print("Done.\nData got written to %s}" % outfile)
self.wfile.flush()
if __name__ == '__main__':
# Run the service
try:
print("Starting...")
server = HTTPServer(('', internalPort), myHandler)
print("Listening on port %d" % internalPort)
print("Ready to receive requests")
# Wait forever for incoming http requests
server.serve_forever()
except KeyboardInterrupt:
print ('^C received, shutting down the web server')
server.socket.close()