aboutsummaryrefslogtreecommitdiffstats
path: root/pysite/route_manager.py
blob: 501076b7c7fc4fe2e8b6203d999debd615233b29 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# coding=utf-8
import importlib
import inspect
import os

from flask import Flask

from pysite.base_route import BaseView, ErrorView

__author__ = "Gareth Coles"


class RouteManager:
    def __init__(self):
        self.app = Flask(__name__)
        self.app.secret_key = os.environ.get("WEBPAGE_SECRET_KEY")

        self.load_views()

    def run(self):
        self.app.run(port=int(os.environ.get("WEBPAGE_PORT")), debug=False)

    def load_views(self, location="pysite/views"):
        for filename in os.listdir(location):
            if os.path.isdir(f"{location}/{filename}"):
                # Recurse if it's a directory; load ALL the views!
                self.load_views(location=f"{location}/{filename}")
                continue

            if filename.endswith(".py") and not filename.startswith("__init__"):
                module = importlib.import_module(f"{location}/{filename}".replace("/", ".")[:-3])

                for cls_name, cls in inspect.getmembers(module):
                    if (
                            inspect.isclass(cls) and
                            cls is not BaseView and
                            cls is not ErrorView and
                            (BaseView in cls.__mro__ or ErrorView in cls.__mro__)
                    ):
                        cls.setup(self.app)
                        print(f"View loaded: {cls.name: <25} ({module.__name__}.{cls_name})")