Last active
October 18, 2020 04:21
-
-
Save walison17/53e622feb5040f18dfd6cecafbea6d27 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from importlib import import_module | |
NEW = 'new' | |
EDIT = 'edit' | |
LIST = 'list' | |
DELETE = 'delete' | |
DEFAULT_ACTIONS = [NEW, EDIT, LIST, DELETE] | |
class Resource: | |
def __init__(self, resource_name, actions, views_module): | |
self.resource_name = resource_name | |
self.actions = actions | |
self.views_module = views_module | |
@property | |
def paths(self): | |
return [ | |
path( | |
self._create_url_path(action), | |
self._get_view_func(action), | |
name=self._create_route_name(action) | |
) | |
for action in self.actions | |
] | |
def _create_url_path(self, action): | |
patterns = { | |
NEW: '{resource}/{action}', | |
EDIT: '{resource}/{action}', | |
DELETE: '{resource}/{action}', | |
LIST: '{resource}/', | |
} | |
pattern = patterns.get(action, '{resource}/{action}') | |
return pattern.format(resource=self.resource_name, action=action) | |
def _get_view_func(self, action): | |
return getattr(self.views_module, f'{self.resource_name}_{action}') | |
def _create_route_name(self, action): | |
return f'{self.resource_name}-{action}' | |
class Router: | |
def __init__(self, views_module): | |
self.views_module = import_module(views_module) | |
self.resources = [] | |
def register(self, resource_name, actions=DEFAULT_ACTIONS): | |
self.resources.append(Resource(resource_name, actions, self.views_module)) | |
@property | |
def urlpatterns(self): | |
paths = [] | |
for resource in self.resources: | |
paths += resource.paths | |
return paths | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment