-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.py
105 lines (78 loc) · 2.1 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import importlib
'''
Inspired by: https://github.com/daveh/php-mvc/blob/master/Core/Router.php
A simple router class that translates
a route (e.g., '/about') into a controller.
Example:
# Create a new instance of Router.
router = Router()
# Associate the AthleteController with the
# /athletes route. Call the controller's
# __init__ method when the route is dispatched.
router.add('/athletes', {'controller': 'AthleteController'})
# Create a new instance of AthleteController
# and call it's __init__ method. The
# __init__ method would more than likely
# render a view.
router.dispatch('/atheletes')
'''
class Router():
def __init__(self):
self.__routes = {}
self.__active_controller = None
self.__log = []
'''
Create a new route
@param route {str}
@param controller {str}
'''
def add(self, route, controller):
if not route in self.__routes:
self.__routes[route] = {
'controller': controller,
'router': self
}
'''
Get all the routes
@return {dict}
'''
def get_routes(self):
return self.__routes
'''
Remove a route
@param route {str}
'''
def remove(self, route):
if route in self.__routes:
del self.__routes[route]
'''
Return dispatch history.
@return {list}
'''
def get_log(self):
return self.__log
'''
Return the last dispatched item. It
is -2 because -1 is the current item.
@return {dict}
'''
def get_last_log_item(self):
return self.__log[-2]
'''
Instantiate a new instance of
the controller associated with
a route.
@param route {str}
@param payload {dict} Data to send to
the controller.
'''
def dispatch(self, route, payload = {}):
if route in self.__routes:
current_route = self.__routes[route]
controller = current_route['controller']
# Dynamically import the controller from the controller module
controllers_module = importlib.import_module('controllers')
controller_class = getattr(controllers_module, controller)
payload['__route'] = route
self.__log.append({'route': route, 'payload': payload})
self.__active_controller = controller_class(current_route['router'], payload)