Skip to content

Commit f79e5b3

Browse files
authored
refactor(__init__.py): improve code readability and maintainability in FlaskMVC class and Hook class (#52)
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.
1 parent fba5dd0 commit f79e5b3

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

mvc_flask/__init__.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -41,22 +41,22 @@ def register_blueprint(self, app: Flask):
4141

4242
obj = import_module(f"{self.path}.controllers.{controller}_controller")
4343
view_func = getattr(obj, f"{controller.title()}Controller")
44-
45-
self.hook.register(view_func, blueprint)
44+
instance_of_controller = view_func()
45+
self.hook.register(instance_of_controller, blueprint)
4646

4747
for resource in route[1]:
4848
blueprint.add_url_rule(
4949
rule=resource.path,
5050
endpoint=resource.action,
51-
view_func=getattr(view_func(), resource.action),
51+
view_func=getattr(instance_of_controller, resource.action),
5252
methods=resource.method,
5353
)
5454

5555
app.register_blueprint(blueprint)
5656

5757

5858
class Hook:
59-
def register(self, ctrl, blueprint):
59+
def register(self, instance_of_controller, blueprint):
6060
accept_attributes = [
6161
"before_request",
6262
"after_request",
@@ -66,11 +66,14 @@ def register(self, ctrl, blueprint):
6666
"teardown_app_request",
6767
"before_app_first_request",
6868
]
69-
attrs = [attr for attr in dir(ctrl()) if attr in accept_attributes]
69+
70+
attrs = [
71+
attr for attr in dir(instance_of_controller) if attr in accept_attributes
72+
]
73+
7074
if attrs:
7175
for attr in attrs:
72-
values = getattr(ctrl(), attr)
73-
76+
values = getattr(instance_of_controller, attr)
7477
for value in values:
75-
hook_method = getattr(ctrl(), value)
78+
hook_method = getattr(instance_of_controller, value)
7679
getattr(blueprint, attr)(hook_method)

0 commit comments

Comments
 (0)