Browse Source

place frontend controller

Guénaël Muller 5 years ago
parent
commit
852dfdfa8b
1 changed files with 47 additions and 0 deletions
  1. 47 0
      backend/tracim_backend/views/frontend.py

+ 47 - 0
backend/tracim_backend/views/frontend.py View File

@@ -0,0 +1,47 @@
1
+import os
2
+
3
+from pyramid.response import Response
4
+from pyramid.config import Configurator
5
+from tracim_backend.exceptions import PageNotFound
6
+from tracim_backend.views import BASE_API_V2
7
+from tracim_backend.lib.utils.request import TracimRequest
8
+from tracim_backend.views.controllers import Controller
9
+
10
+INDEX_PAGE_NAME = 'index.html'
11
+
12
+
13
+class FrontendController(Controller):
14
+
15
+    def __init__(self, dist_folder_path: str):
16
+        self.dist_folder_path = dist_folder_path
17
+
18
+    def not_found_view(self, context, request: TracimRequest):
19
+
20
+        if request.path.startswith(BASE_API_V2):
21
+            raise PageNotFound('{} is not a valid path'.format(request.path)) from context
22
+        return self.index(context, request)
23
+
24
+    def index(self, context, request: TracimRequest):
25
+        index_file_path = os.path.join(self.dist_folder_path, INDEX_PAGE_NAME)
26
+        if not os.path.exists(index_file_path):
27
+            raise FileNotFoundError()
28
+        with open(index_file_path) as file:
29
+            return Response(
30
+                content_type='text/html',
31
+                body=file.read()
32
+            )
33
+
34
+    def bind(self, configurator: Configurator) -> None:
35
+
36
+        configurator.add_notfound_view(self.not_found_view)
37
+        # index.html for /index.html and /
38
+        configurator.add_route('root', '/', request_method='GET')
39
+        configurator.add_view(self.index, route_name='root')
40
+        configurator.add_route('index', INDEX_PAGE_NAME, request_method='GET')
41
+        configurator.add_view(self.index, route_name='index')
42
+
43
+        for dirname in os.listdir(self.dist_folder_path):
44
+            configurator.add_static_view(
45
+                name=dirname,
46
+                path=os.path.join(self.dist_folder_path, dirname)
47
+            )