frontend.py 2.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import os
  2. from pyramid.renderers import render_to_response
  3. from pyramid.config import Configurator
  4. from tracim_backend.exceptions import PageNotFound
  5. from tracim_backend.models.applications import applications
  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. import spectra
  10. INDEX_PAGE_NAME = 'index.mak'
  11. APP_FRONTEND_PATH = 'app/{minislug}.app.js'
  12. class FrontendController(Controller):
  13. def __init__(self, dist_folder_path: str):
  14. self.dist_folder_path = dist_folder_path
  15. def _get_index_file_path(self):
  16. index_file_path = os.path.join(self.dist_folder_path, INDEX_PAGE_NAME)
  17. if not os.path.exists(index_file_path):
  18. raise FileNotFoundError()
  19. return index_file_path
  20. def not_found_view(self, context, request: TracimRequest):
  21. if request.path.startswith(BASE_API_V2):
  22. raise PageNotFound('{} is not a valid path'.format(request.path)) from context # nopep8
  23. return self.index(context, request)
  24. def index(self, context, request: TracimRequest):
  25. app_config = request.registry.settings['CFG']
  26. # TODO - G.M - 2018-08-07 - Refactor autogen valid app list for frontend
  27. frontend_apps = []
  28. for app in applications:
  29. app_frontend_path = APP_FRONTEND_PATH.replace('{minislug}',
  30. app.minislug) # nopep8
  31. app_path = os.path.join(self.dist_folder_path,
  32. app_frontend_path) # nopep8
  33. if os.path.exists(app_path):
  34. frontend_apps.append(app)
  35. return render_to_response(
  36. self._get_index_file_path(),
  37. {
  38. 'colors': {
  39. 'primary': spectra.html('#7d4e24'),
  40. },
  41. 'applications': frontend_apps,
  42. }
  43. )
  44. def bind(self, configurator: Configurator) -> None:
  45. configurator.add_notfound_view(self.not_found_view)
  46. # index.html for /index.html and /
  47. configurator.add_route('root', '/', request_method='GET')
  48. configurator.add_view(self.index, route_name='root')
  49. configurator.add_route('index', INDEX_PAGE_NAME, request_method='GET')
  50. configurator.add_view(self.index, route_name='index')
  51. for dirname in os.listdir(self.dist_folder_path):
  52. configurator.add_static_view(
  53. name=dirname,
  54. path=os.path.join(self.dist_folder_path, dirname)
  55. )