瀏覽代碼

place frontend controller

Guénaël Muller 6 年之前
父節點
當前提交
852dfdfa8b
共有 1 個文件被更改,包括 47 次插入0 次删除
  1. 47 0
      backend/tracim_backend/views/frontend.py

+ 47 - 0
backend/tracim_backend/views/frontend.py 查看文件

@@ -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
+            )