aboutsummaryrefslogtreecommitdiffstats
path: root/pysite/route_manager.py
blob: f61c4f651a88e8353bf40491f9acddf10a06ba41 (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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# coding=utf-8
import importlib
import inspect
import os

from flask import Flask, abort, g

import rethinkdb

from pysite.base_route import BaseView, ErrorView, RouteView

__author__ = "Gareth Coles"

DB_HOST = os.environ.get("RETHINKDB_HOST")
DB_PORT = os.environ.get("RETHINKDB_PORT")
DB_DATABASE = os.environ.get("RETHINKDB_DATABASE")
DB_TABLE = os.environ.get("RETHINKDB_TABLE")

TEMPLATES_PATH = "../templates"
STATIC_PATH = "../static"


class RouteManager:
    def __init__(self):
        self.app = Flask(
            __name__, template_folder=TEMPLATES_PATH, static_folder=STATIC_PATH, static_url_path="/static"
        )
        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
                            cls is not RouteView and
                            BaseView in cls.__mro__
                    ):
                        cls.setup(self.app)
                        print(f"View loaded: {cls.name: <25} ({module.__name__}.{cls_name})")

    def setup_db(self):
        connection = self.get_db_connection(connect_database=False)

        try:
            rethinkdb.db_create(DB_DATABASE).run(connection)
            rethinkdb.db(DB_DATABASE).table_create(DB_TABLE).run(connection)
            print("Database created")
        except rethinkdb.RqlRuntimeError:
            print("Database found")
        finally:
            connection.close()

        self.app.before_request(self.db_before_request)
        self.app.teardown_request(self.db_teardown_request)

    def get_db_connection(self, connect_database=True):
        if connect_database:
            return rethinkdb.connect(host=DB_HOST, port=DB_PORT, db=DB_DATABASE)
        else:
            return rethinkdb.connect(host=DB_HOST, port=DB_PORT)

    def db_before_request(self):
        try:
            # g is the Flask global context object
            g.rdb_conn = self.get_db_connection()
        except rethinkdb.RqlDriverError:
            abort(503, "Database connection could be established.")

    def db_teardown_request(self, _):
        try:
            # g is the Flask global context object
            g.rdb_conn.close()
        except AttributeError:
            pass