Skip to content

Instantly share code, notes, and snippets.

@Omie
Created September 6, 2022 10:49
Show Gist options
  • Save Omie/30740aecae823a6d5ec69acd8538c455 to your computer and use it in GitHub Desktop.
Save Omie/30740aecae823a6d5ec69acd8538c455 to your computer and use it in GitHub Desktop.
import json
import requests
import argparse
from http.server import HTTPServer, BaseHTTPRequestHandler
class S(BaseHTTPRequestHandler):
def _set_headers(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
def _html(self, message):
"""This just generates an HTML document that includes `message`
in the body. Override, or re-write this do do more interesting stuff.
"""
content = f"<html><body><h1>{message}</h1></body></html>"
return content.encode("utf8") # NOTE: must return a bytes object!
def get_transformed(self):
r = requests.get('https://api.coingecko.com/api/v3/exchange_rates')
d = r.json()
rates = d["rates"]
out = []
for k, v in rates.items():
_data = v
_data["symbol"] = k
# out.append([k, v["name"], v["unit"], v["value"], v["type"]])
out.append(_data)
return json.dumps(out).encode("utf8")
def do_GET(self):
self._set_headers()
self.wfile.write(self.get_transformed())
def do_HEAD(self):
self._set_headers()
def do_POST(self):
# Doesn't do anything with posted data
self._set_headers()
self.wfile.write(self._html("POST!"))
def run(server_class=HTTPServer, handler_class=S, addr="localhost", port=8000):
server_address = (addr, port)
httpd = server_class(server_address, handler_class)
print(f"Starting httpd server on {addr}:{port}")
httpd.serve_forever()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Run a simple HTTP server")
parser.add_argument(
"-l",
"--listen",
default="localhost",
help="Specify the IP address on which the server listens",
)
parser.add_argument(
"-p",
"--port",
type=int,
default=8000,
help="Specify the port on which the server listens",
)
args = parser.parse_args()
run(addr=args.listen, port=args.port)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment