frontend.py 1.7KB

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