-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathexercise2.py
More file actions
61 lines (47 loc) · 1.58 KB
/
exercise2.py
File metadata and controls
61 lines (47 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
"""
Simple HTTP server.
https://docs.python.org/3/library/http.server.html
"""
from urllib.parse import urlparse, parse_qsl
from http.server import BaseHTTPRequestHandler, HTTPServer
class myHTTPServer_RequestHandler(BaseHTTPRequestHandler):
"""
HTTPRequestHandler class
Parsing of the request is done by the base class BaseHTTPRequestHandler.
"""
# GET
def do_GET(self):
# Send response status code
self.send_response(200)
# Send headers
self.send_header('Content-type', 'text/html')
self.end_headers()
parsed = urlparse(self.path)
x = parse_qsl(parsed.query)
message = " ".join([ "{}:{}".format(p[0],p[1]) for p in x])
# Write message content as utf-8 data
self.wfile.write(bytes(message, "utf8"))
return
# POST
def do_POST(self):
# Send response status code
self.send_response(200)
# Send headers
self.send_header('Content-type', 'text/html')
self.end_headers()
# Gets the size of data
l = int(self.headers.get("Content-length"))
# Gets the data itself (byte string)
vars = self.rfile.read(l)
# Input parameters (as a dict)
message = "Hello POST!"
# Write message content as utf-8 data
self.wfile.write(bytes(message, "utf8"))
return
def main():
server_address = ('127.0.0.1', 8080)
httpd = HTTPServer(server_address, myHTTPServer_RequestHandler)
print("running server...")
httpd.serve_forever()
if __name__ == "__main__":
main()