Skip to content

Added routing #432

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 25, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 40 additions & 1 deletion patterns/structural/mvc.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
"""

from abc import ABC, abstractmethod
from inspect import signature
from sys import argv


class Model(ABC):
Expand Down Expand Up @@ -113,6 +115,23 @@ def show_item_information(self, item_name):
self.view.show_item_information(item_type, item_name, item_info)


class Router:
def __init__(self):
self.routes = {}

def register(self, path, controller, model, view):
model = model()
view = view()
self.routes[path] = controller(model, view)

def resolve(self, path):
if self.routes.get(path):
controller = self.routes[path]
return controller
else:
return None


def main():
"""
>>> model = ProductModel()
Expand Down Expand Up @@ -147,6 +166,26 @@ def main():


if __name__ == "__main__":
import doctest
router = Router()
router.register("products", Controller, ProductModel, ConsoleView)
controller = router.resolve(argv[1])

command = str(argv[2]) if len(argv) > 2 else None
args = ' '.join(map(str, argv[3:])) if len(argv) > 3 else None

if hasattr(controller, command):
command = getattr(controller, command)
sig = signature(command)

if len(sig.parameters) > 0:
if args:
command(args)
else:
print("Command requires arguments.")
else:
command()
else:
print(f"Command {command} not found in the controller.")

import doctest
doctest.testmod()