Skip to content

Commit

Permalink
refactor(__init__.py): improve code readability and maintainability i…
Browse files Browse the repository at this point in the history
…n FlaskMVC class and Hook class

In the FlaskMVC class:
- Change the variable name `view_func` to `instance_of_controller` to better reflect its purpose.
- Instead of calling `view_func()` multiple times, create an instance of the controller class and register it with the hook.
- Use the instance of the controller to retrieve the view function for each resource.

In the Hook class:
- Change the parameter name `ctrl` to `instance_of_controller` to better reflect its purpose.
- Use the instance of the controller to retrieve the hook methods.

These changes improve the readability and maintainability of the code by using more descriptive variable names and reducing code duplication.
  • Loading branch information
marcuxyz committed Nov 17, 2023
1 parent fba5dd0 commit 4e7d5e6
Showing 1 changed file with 11 additions and 8 deletions.
19 changes: 11 additions & 8 deletions mvc_flask/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,22 +41,22 @@ def register_blueprint(self, app: Flask):

obj = import_module(f"{self.path}.controllers.{controller}_controller")
view_func = getattr(obj, f"{controller.title()}Controller")

self.hook.register(view_func, blueprint)
instance_of_controller = view_func()
self.hook.register(instance_of_controller, blueprint)

for resource in route[1]:
blueprint.add_url_rule(
rule=resource.path,
endpoint=resource.action,
view_func=getattr(view_func(), resource.action),
view_func=getattr(instance_of_controller, resource.action),
methods=resource.method,
)

app.register_blueprint(blueprint)


class Hook:
def register(self, ctrl, blueprint):
def register(self, instance_of_controller, blueprint):
accept_attributes = [
"before_request",
"after_request",
Expand All @@ -66,11 +66,14 @@ def register(self, ctrl, blueprint):
"teardown_app_request",
"before_app_first_request",
]
attrs = [attr for attr in dir(ctrl()) if attr in accept_attributes]

attrs = [
attr for attr in dir(instance_of_controller) if attr in accept_attributes
]

if attrs:
for attr in attrs:
values = getattr(ctrl(), attr)

values = getattr(instance_of_controller, attr)
for value in values:
hook_method = getattr(ctrl(), value)
hook_method = getattr(instance_of_controller, value)
getattr(blueprint, attr)(hook_method)

0 comments on commit 4e7d5e6

Please sign in to comment.