Skip to content
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

WIP register before_request hook #13

Merged
merged 4 commits into from Nov 14, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions app/controllers/home_controller.py
@@ -1,6 +1,11 @@
class HomeController:
before_request = ["hi"]

def index(self):
return "home"

def hello(self):
return "hello"

def hi(self):
print("hi")
20 changes: 19 additions & 1 deletion mvc_flask/__init__.py
@@ -1,5 +1,4 @@
from importlib import import_module
from pathlib import Path

from flask import Flask
from flask.blueprints import Blueprint
Expand All @@ -13,6 +12,8 @@ def __init__(self, app: Flask = None):
self.init_app(app)

def init_app(self, app):
self.hook = Hook()

app.template_folder = "views"

self.register_blueprint(app)
Expand All @@ -24,8 +25,12 @@ def register_blueprint(self, app: Flask):
for route in Router._method_route().items():
controller = route[0]
blueprint = Blueprint(controller, controller)

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

self.hook.register(view_func, blueprint)

for resource in route[1]:
blueprint.add_url_rule(
rule=resource.path,
Expand All @@ -34,3 +39,16 @@ def register_blueprint(self, app: Flask):
methods=[resource.method],
)
app.register_blueprint(blueprint)


class Hook:
def register(self, ctrl, blueprint):
accept_attributes = ["before_recquest"]
attrs = [attr for attr in dir(ctrl()) if attr in accept_attributes]
if attrs:
for attr in attrs:
values = getattr(ctrl(), attr)

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