custom_view.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import os.path
  2. from typing import List
  3. import justpy as jp
  4. from starlette.responses import FileResponse
  5. from starlette.routing import Route
  6. class CustomView(jp.JustpyBaseComponent):
  7. def __init__(self, vue_type, **options):
  8. self.vue_type = vue_type
  9. self.pages = {}
  10. self.classes = ''
  11. self.style = ''
  12. self.options = jp.Dict(**options)
  13. self.components = []
  14. super().__init__(temp=False)
  15. def react(self, _):
  16. pass
  17. def convert_object_to_dict(self):
  18. return {
  19. 'vue_type': self.vue_type,
  20. 'id': self.id,
  21. 'show': True,
  22. 'classes': self.classes,
  23. 'style': self.style,
  24. 'options': self.options,
  25. }
  26. @staticmethod
  27. def use(py_filepath: str, dependencies: List[str] = []):
  28. vue_filepath = os.path.realpath(py_filepath).replace('.py', '.js')
  29. for dependency in dependencies:
  30. is_remote = dependency.startswith('http://') or dependency.startswith('https://')
  31. src = dependency if is_remote else f'lib/{dependency}'
  32. if src not in jp.component_file_list:
  33. jp.component_file_list += [src]
  34. if not is_remote:
  35. filepath = f'{os.path.dirname(vue_filepath)}/{src}'
  36. route = Route(f'/{src}', lambda _, filepath=filepath: FileResponse(filepath))
  37. jp.app.routes.insert(0, route)
  38. if vue_filepath not in jp.component_file_list:
  39. filename = os.path.basename(vue_filepath)
  40. jp.app.routes.insert(0, Route(f'/{filename}', lambda _: FileResponse(vue_filepath)))
  41. jp.component_file_list += [filename]