Skip to content

Instantly share code, notes, and snippets.

@mscalora
Created November 23, 2022 14:34
Show Gist options
  • Save mscalora/b6f86291353c360cb5550dc978129069 to your computer and use it in GitHub Desktop.
Save mscalora/b6f86291353c360cb5550dc978129069 to your computer and use it in GitHub Desktop.
Python 3 HTTP Server Example
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib import parse
import json
def run_server(port):
class Server(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write("""
<html><head><title>GET</title></head>
<body style="display: grid; place-items: center;">
<form method="POST">
<p>Blue: <input name="blue" value="robin's egg"></p>
<p>Green: <input name="green" value="sea foam"></p>
<p>Red: <input name="red" type="range" min="0" max ="100" step="0.01" value="27.76"></p>
<p><button>Submit</button></p>
</form>
</body></html>
""".encode("utf-8"))
def do_POST(self):
length = int(self.headers.get('content-length'))
field_data = self.rfile.read(length)
fields = parse.parse_qs(str(field_data,"UTF-8"))
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(("""
<html><head><title>POST</title></head>
<body style="display: grid; place-items: center;">
<pre>%s</pre>
</body></html>
""" % (json.dumps(fields, indent=2))).encode("UTF-8"))
handler_class = Server
httpd = HTTPServer(('', port), handler_class)
print('Browse to http://localhost:%s' % port)
httpd.serve_forever()
if __name__ == '__main__':
run_server(8888)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment