-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.py
101 lines (91 loc) · 2.71 KB
/
http.py
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#!/usr/bin/python
# -*- coding: utf-8 -*-
import BaseHTTPServer
import urlparse
import cgi
import json
class Html:
def __init__(self, html):
self.html = html
def serve(self, response):
response.send_response(200)
response.send_header('Content-Type', 'text/html; charset=UTF-8');
response.end_headers()
response.wfile.write(self.html.to_string())
class Text:
def __init__(self, text):
self.text = text
def serve(self, response):
response.send_response(200)
response.send_header('Content-Type', 'text/plain; charset=UTF-8');
response.end_headers()
response.wfile.write(self.text)
class Json:
def __init__(self, data):
self.data = data
def serve(self, response):
response.send_response(200)
response.send_header('Content-Type', 'application/json');
response.end_headers()
json.dump(self.data, response.wfile)
class Created:
def __init__(self, location):
self.location = location
def serve(self, response):
response.send_response(302)
response.send_header('Location', self.location);
response.end_headers()
class Error:
def __init__(self, code, status):
self.code = code
self.status = status
def serve(self, response):
response.send_response(self.code, self.status)
response.end_headers()
class Handler:
def __init__(self, do_GET, do_POST, **children):
self.do_GET = do_GET
self.do_POST = do_POST
self.children = children
def find(self, path):
if path == [] or path[0] not in self.children:
return (self, path)
else:
return self.children[path[0]].find(path[1:])
def serve(address, root_handler):
class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def get_path(self):
return self.path.split('/')[1:]
def serve_not_found(self):
self.send_error(404, 'invalid path: {}'.format(self.path))
def serve_invalid_method(self, method):
self.send_error(405, 'invalid method: {}'.format(method))
def do_GET(self):
(handler, args) = root_handler.find(self.get_path())
if handler:
if handler.do_GET:
handler.do_GET(self, args).serve(self)
else:
self.serve_invalid_method('GET')
else:
self.serve_not_found()
def do_POST(self):
(handler, args) = root_handler.find(self.get_path())
if handler:
if handler.do_POST:
content_type = self.headers['Content-Type']
if content_type == 'application/x-www-form-urlencoded':
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={"REQUEST_METHOD": "POST"}
)
else:
raise Exception("Unsupported content type: "+content_type)
handler.do_POST(self, args, form).serve(self)
else:
self.serve_invalid_method('POST')
else:
self.serve_not_found()
httpd = BaseHTTPServer.HTTPServer(address, MyHandler)
httpd.serve_forever()