-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.py
80 lines (61 loc) · 2.13 KB
/
router.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
import traceback
from routes import Mapper
from urllib.parse import urlparse, parse_qs
getMap = Mapper()
postMap = Mapper()
putMap = Mapper()
deleteMap = Mapper()
def executeController(map, requestHandler):
try:
parsedPath = urlparse(requestHandler.path)
contentLength = int(requestHandler.headers.get('content-length', 0))
body = requestHandler.rfile.read(contentLength).decode('utf-8')
result = map.match(parsedPath.path)
if (result == None):
return None
function = result['controller']
request = Request(
args = result,
query = parse_qs(parsedPath.query),
headers = requestHandler.headers,
body = body
)
return function(request)
except BaseException:
print(traceback.format_exc())
return Response(statusCode = 500, responseBody = "Internal Server Error")
def doGet(requestHandler):
return executeController(getMap, requestHandler)
def doPost(requestHandler):
return executeController(postMap, requestHandler)
def doPut(requestHandler):
return executeController(putMap, requestHandler)
def doDelete(requestHandler):
return executeController(deleteMap, requestHandler)
def registerRoute(map, routePath):
def wrap(f):
map.connect(routePath, controller=f)
def wrapped_f(*args):
f(*args)
return wrapped_f
return wrap
def get(routePath):
return registerRoute(getMap, routePath)
def post(routePath):
return registerRoute(postMap, routePath)
def put(routePath):
return registerRoute(putMap, routePath)
def delete(routePath):
return registerRoute(deleteMap, routePath)
class Request:
def __init__(self, args = {}, query = {}, headers = None, body = None):
self.args = args
self.query= query
self.headers = headers
self.body = body
class Response:
def __init__(self, statusCode = 200, responseBody = None, contentType = "text/plain", headers = {}):
self.statusCode = statusCode
self.responseBody = responseBody
self.contentType = contentType
self.headers = headers