changeset 1503:2796e73ed50c

tasks (brython): fix brython scripts loading.
author Goffi <goffi@goffi.org>
date Wed, 01 Mar 2023 17:55:25 +0100
parents e1ccba0d2b71
children 409d10211b20
files libervia/server/tasks/implicit/task_brython.py
diffstat 1 files changed, 27 insertions(+), 22 deletions(-) [+]
line wrap: on
line diff
--- a/libervia/server/tasks/implicit/task_brython.py	Thu Nov 24 17:34:31 2022 +0100
+++ b/libervia/server/tasks/implicit/task_brython.py	Wed Mar 01 17:55:25 2023 +0100
@@ -1,15 +1,18 @@
 #!/ur/bin/env python3
 
-import shutil
+from ast import literal_eval
 import json
 from pathlib import Path
-from ast import literal_eval
+import shutil
+from typing import Any, Dict
+
+from sat.core import exceptions
 from sat.core.i18n import _
 from sat.core.log import getLogger
-from sat.core import exceptions
 from sat.tools.common import utils
+
+from libervia.server.classes import Script
 from libervia.server.constants import Const as C
-from libervia.server.classes import Script
 from libervia.server.tasks import task
 
 
@@ -43,10 +46,11 @@
 
         try:
             import brython
+            from brython import version as brython_version
         except ModuleNotFoundError as e:
             log.error('"brython" module is missing, can\'t use browser code for Brython')
             raise e
-        ver = [int(v) for v in brython.implementation.split('.')[:3]]
+        ver = [int(v) for v in brython_version.implementation.split('.')[:3]]
         if ver != installed_ver:
             log.info(_("Installing Brython v{version}").format(
                 version='.'.join(str(v) for v in ver)))
@@ -59,9 +63,9 @@
             log.debug("Brython is already installed")
 
         self.WATCH_DIRS = []
-        self.setCommonScripts()
+        self.set_common_scripts()
 
-    def setCommonScripts(self):
+    def set_common_scripts(self):
         for dyn_data in self.resource.browser_modules["brython"]:
             url_hash = dyn_data['url_hash']
             import_url = f"/{C.BUILD_DIR}/{C.BUILD_DIR_DYN}/{url_hash}"
@@ -69,22 +73,22 @@
                 Script(src=f"/{C.BUILD_DIR}/brython.js"),
                 Script(src=f"/{C.BUILD_DIR}/brython_stdlib.js"),
             ])
-            dyn_data.setdefault('template', {})['body_onload'] = self.getBodyOnload(
+            dyn_data.setdefault('template', {})['body_onload'] = self.get_body_onload(
                 extra_path=[import_url])
             self.WATCH_DIRS.append(dyn_data['path'].resolve())
 
-    def getBodyOnload(self, debug=True, cache=True, extra_path=None):
-            on_load_opts = {"pythonpath": [f"/{C.BUILD_DIR}"]}
-            if debug:
-                on_load_opts[debug] = 1
-            if cache:
-                on_load_opts["cache"] = True
-            if extra_path is not None:
-                on_load_opts["pythonpath"].extend(extra_path)
+    def get_body_onload(self, debug=True, cache=True, extra_path=None):
+        on_load_opts: Dict[str, Any]  = {"pythonpath": [f"/{C.BUILD_DIR}"]}
+        if debug:
+            on_load_opts["debug"] = 1
+        if cache:
+            on_load_opts["cache"] = True
+        if extra_path is not None:
+            on_load_opts["pythonpath"].extend(extra_path)
 
-            return f"brython({json.dumps(on_load_opts)})"
+        return f"brython({json.dumps(on_load_opts)})"
 
-    def copyFiles(self, files_paths, dest):
+    def copy_files(self, files_paths, dest):
         for p in files_paths:
             log.debug(f"copying {p}")
             if p.is_dir():
@@ -95,7 +99,7 @@
                 shutil.copy(p, dest)
 
     async def onDirEvent(self, host, filepath, flags):
-        self.setCommonScripts()
+        self.set_common_scripts()
         await self.manager.runTaskInstance(self)
 
     def start(self):
@@ -113,16 +117,17 @@
                     dest.mkdir(exist_ok = True)
                     init_dest_url = f"/{C.BUILD_DIR}/{url_prefix}/__init__.py"
 
-                self.copyFiles(dyn_data['path'].glob('*py'), dest)
+                self.copy_files(dyn_data['path'].glob('*py'), dest)
 
                 init_file = dyn_data['path'] / '__init__.py'
                 if init_file.is_file():
                     self.resource.dyn_data_common['scripts'].update([
                         Script(src=f"/{C.BUILD_DIR}/brython.js"),
+                        Script(src=f"/{C.BUILD_DIR}/brython_stdlib.js"),
                         Script(type='text/python', src=init_dest_url)
                     ])
                     self.resource.dyn_data_common.setdefault(
-                        "template", {})['body_onload'] = self.getBodyOnload()
+                        "template", {})['body_onload'] = self.get_body_onload()
             else:
                 page_dyn_path = dyn_path / url_hash
                 log.debug(f"using dynamic path at {page_dyn_path}")
@@ -132,7 +137,7 @@
 
                 page_dyn_path.mkdir(parents=True, exist_ok=True)
                 log.debug("copying browser python files")
-                self.copyFiles(dyn_data['path'].iterdir(), page_dyn_path)
+                self.copy_files(dyn_data['path'].iterdir(), page_dyn_path)
 
                 script = Script(
                     type='text/python',