Being able to write an HTTP server in Python opens up a whole world of possibilities for sharing your clever code and posts with the world, through an API or through the browser. I wanted to figure out how to do it, and here are my notes.
https://www.brandonrohrer.com/http_server
1/
https://www.brandonrohrer.com/http_server
1/
Comments
from http. server import BaseHTTPRequestHandler
class RequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
…
2/
1. a status report
2. some headers
3. a body (optional)
In do_GET() use the headers information to read in the body as a dict.
content_length = int(self.headers['Content-Length'])
request_body = json.loads(
self.rfile. read(content_length).decode('utf-8')
)
3/
answer = request_body["val_a"] + request_body["val_b"]
response_body = json.dumps({"sum": answer}).encode("utf-8")
4/
self.send_response(200)
Send the header information
self.send_header("Content-type", "application/json")
self.send_header("Content-Length", len(response_body))
self.end_headers()
And send the response body
self.wfile.write(response_body)
5/
from http. server import HTTPServer
host = "192.168.1.42"
port = 8000
httpd = HTTPServer((host, port), RequestHandler)
httpd. serve_forever()
6/
from http. server import HTTPServer
from socketserver import ThreadingMixIn
class ThreadingServer(ThreadingMixIn, HTTPServer):
pass
Everything else is exactly the same.
7/
Here, one of my goals was actually to learn more about http, so I went with a lower level approach.