X-Git-Url: https://git.mar77i.info/?a=blobdiff_plain;f=hub%2Fstaticresource.py;h=e1e86dd633b50cc0d9eb4368f22ee11aed1f6045;hb=66e1cc7886b1ce7092281a43b9ee7969366e6835;hp=9cc949ae7d54b9f974abfb11d579e0c65d798dba;hpb=c0e574584af0d45070e5fa81fcbcd1dccc2c5a42;p=hublib diff --git a/hub/staticresource.py b/hub/staticresource.py index 9cc949a..e1e86dd 100644 --- a/hub/staticresource.py +++ b/hub/staticresource.py @@ -1,3 +1,4 @@ +from io import BytesIO import json import mimetypes import os @@ -8,6 +9,9 @@ from .utils import scramble class StaticFile: template_ext = ".tpl" + template_filters = { + b"tojson": lambda value: json.dumps(value) + } def __init__(self, path): self.path = path @@ -19,18 +23,32 @@ class StaticFile: with open(self.path, "rb") as fh: return fh.read() - def get(self): - if self.path.stat().st_mtime != self.mtime: - self.content = self.load_content() - return self.content - - def render(self, context_vars): - content = self.get() + def get(self, context_vars): + content = self.load_content() if self.path.stat().st_mtime != self.mtime else self.content if self.path.suffix == self.template_ext: - for k, v in context_vars.items(): - content = content.replace(b"{{ %s }}" % k.encode(), v.encode()) + content = self.render(content, context_vars) + self.content = content return content + def render(self, content, context_vars): + bio = BytesIO() + pos = 0 + while True: + new_pos = content.find(b"{{", pos) + if new_pos < 0: + break + bio.write(content[pos:new_pos]) + end_pos = content.find(b"}}", new_pos) + assert end_pos > 0 + full_tag = content[new_pos + 2:end_pos].split(b"|", 1) + value = context_vars[full_tag[0].strip().decode()] + if len(full_tag) == 2: + value = self.template_filters[full_tag[1].strip()](value) + bio.write(value.encode()) + pos = end_pos + 2 + bio.write(content[pos:]) + return bio.getvalue() + def __str__(self): return f"" @@ -42,15 +60,10 @@ class StaticFile: class StaticResource: - def __init__(self, secret, current_hubapp, master_ws_uri): + def __init__(self, secret, current_hubapp): mimetypes.init() - hub_js_path = Path(__file__).parent / "hub.js" - self.static_files = { - "/hub.js": StaticFile(hub_js_path), - } - self.context_vars = { - "master_ws_uri": json.dumps(master_ws_uri), - } + self.static_files = {} + self.context_vars = {} self.master_uri = "" self.setup(secret, current_hubapp) @@ -75,7 +88,7 @@ class StaticResource: if path == "/": path = index_uri res = self.static_files[path] - resp.data = res.render(self.context_vars) + resp.data = res.get(self.context_vars) resp.content_type = res.mime_type def add_routes(self, app):