Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit bc58040

Browse files
committedJun 21, 2024
Cache file reads for pyscript code
1 parent 4ac4ded commit bc58040

File tree

1 file changed

+30
-6
lines changed

1 file changed

+30
-6
lines changed
 

‎src/reactpy_django/utils.py

Lines changed: 30 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -460,19 +460,43 @@ def vdom_or_component_to_string(
460460
)
461461

462462

463-
def render_pyscript_template(file_path: str, uuid: str, root: str):
463+
def render_pyscript_template(file_paths: Sequence[str], uuid: str, root: str):
464464
"""Inserts the user's code into the PyScript template using pattern matching."""
465+
from django.core.cache import caches
466+
467+
from reactpy_django.config import REACTPY_CACHE
468+
465469
# Create a valid PyScript executor by replacing the template values
466470
executor = PYSCRIPT_COMPONENT_TEMPLATE.replace("UUID", uuid)
467471
executor = executor.replace("return root()", f"return {root}()")
468472

469-
# Insert the user code into the template
470-
user_code = Path(file_path).read_text(encoding="utf-8")
471-
user_code = user_code.strip().replace("\t", " ") # Normalize the code text
473+
# Fetch the user's PyScript code
474+
all_file_contents: list[str] = []
475+
for file_path in file_paths:
476+
# Try to get user code from cache
477+
cache_key = create_cache_key("pyscript", file_path)
478+
last_modified_time = os.stat(file_path).st_mtime
479+
file_contents: str = caches[REACTPY_CACHE].get(
480+
cache_key, version=int(last_modified_time)
481+
)
482+
if file_contents:
483+
all_file_contents.append(file_contents)
484+
485+
# If not cached, read from file system
486+
else:
487+
file_contents = Path(file_path).read_text(encoding="utf-8").strip()
488+
all_file_contents.append(file_contents)
489+
caches[REACTPY_CACHE].set(
490+
cache_key, file_contents, version=int(last_modified_time)
491+
)
492+
493+
# Prepare the PyScript code block
494+
user_code = "\n".join(all_file_contents) # Combine all user code
495+
user_code = user_code.replace("\t", " ") # Normalize the text
472496
user_code = textwrap.indent(user_code, " ") # Add indentation to match template
473-
executor = executor.replace(" def root(): ...", user_code)
474497

475-
return executor
498+
# Insert the user code into the PyScript template
499+
return executor.replace(" def root(): ...", user_code)
476500

477501

478502
def extend_pyscript_config(config: dict | str, extra_packages: Sequence) -> str:

0 commit comments

Comments
 (0)
Please sign in to comment.