|
4 | 4 | """
|
5 | 5 |
|
6 | 6 | from abc import ABC, abstractmethod
|
| 7 | +from inspect import signature |
| 8 | +from sys import argv |
7 | 9 |
|
8 | 10 |
|
9 | 11 | class Model(ABC):
|
@@ -113,6 +115,23 @@ def show_item_information(self, item_name):
|
113 | 115 | self.view.show_item_information(item_type, item_name, item_info)
|
114 | 116 |
|
115 | 117 |
|
| 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 | + |
116 | 135 | def main():
|
117 | 136 | """
|
118 | 137 | >>> model = ProductModel()
|
@@ -147,6 +166,26 @@ def main():
|
147 | 166 |
|
148 | 167 |
|
149 | 168 | 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.") |
151 | 189 |
|
| 190 | + import doctest |
152 | 191 | doctest.testmod()
|
0 commit comments