Created
November 23, 2022 14:34
-
-
Save mscalora/b6f86291353c360cb5550dc978129069 to your computer and use it in GitHub Desktop.
Python 3 HTTP Server Example
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
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