Skip to content

Commit 821a4dc

Browse files
authored
Merge pull request #432 from cdorsman/mvc-routing
Added routing
2 parents 328b2d4 + a400094 commit 821a4dc

File tree

1 file changed

+40
-1
lines changed

1 file changed

+40
-1
lines changed

patterns/structural/mvc.py

+40-1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
"""
55

66
from abc import ABC, abstractmethod
7+
from inspect import signature
8+
from sys import argv
79

810

911
class Model(ABC):
@@ -113,6 +115,23 @@ def show_item_information(self, item_name):
113115
self.view.show_item_information(item_type, item_name, item_info)
114116

115117

118+
class Router:
119+
def __init__(self):
120+
self.routes = {}
121+
122+
def register(self, path, controller, model, view):
123+
model = model()
124+
view = view()
125+
self.routes[path] = controller(model, view)
126+
127+
def resolve(self, path):
128+
if self.routes.get(path):
129+
controller = self.routes[path]
130+
return controller
131+
else:
132+
return None
133+
134+
116135
def main():
117136
"""
118137
>>> model = ProductModel()
@@ -147,6 +166,26 @@ def main():
147166

148167

149168
if __name__ == "__main__":
150-
import doctest
169+
router = Router()
170+
router.register("products", Controller, ProductModel, ConsoleView)
171+
controller = router.resolve(argv[1])
172+
173+
command = str(argv[2]) if len(argv) > 2 else None
174+
args = ' '.join(map(str, argv[3:])) if len(argv) > 3 else None
175+
176+
if hasattr(controller, command):
177+
command = getattr(controller, command)
178+
sig = signature(command)
179+
180+
if len(sig.parameters) > 0:
181+
if args:
182+
command(args)
183+
else:
184+
print("Command requires arguments.")
185+
else:
186+
command()
187+
else:
188+
print(f"Command {command} not found in the controller.")
151189

190+
import doctest
152191
doctest.testmod()

0 commit comments

Comments
 (0)