]>
git.mar77i.info Git - hublib/blob - hub/staticresource.py
4 from pathlib
import Path
6 from .utils
import scramble
12 def __init__(self
, path
):
14 self
.mime_type
= mimetypes
.guess_type(self
.remove_template_ext(str(path
)))[0]
18 def load_content(self
):
19 with open(self
.path
, "rb") as fh
:
23 if self
.path
.stat().st_mtime
!= self
.mtime
:
24 self
.content
= self
.load_content()
27 def render(self
, context_vars
):
29 if self
.path
.suffix
== self
.template_ext
:
30 for k
, v
in context_vars
.items():
31 content
= content
.replace(b
"{{ %s }}" % k
.encode(), v
.encode())
35 return f
"<StaticFile at \"{os.sep.join(self.path.parts[-2:])}\" [{self.mime_type}]>"
38 def remove_template_ext(cls
, filename
):
39 if filename
.endswith(cls
.template_ext
):
40 filename
= filename
[:-4]
45 def __init__(self
, secret
, current_hubapp
, master_ws_uri
):
47 hub_js_path
= Path(__file__
).parent
/ "hub.js"
49 "/hub.js": StaticFile(hub_js_path
),
52 "master_ws_uri": json
.dumps(master_ws_uri
),
55 self
.setup(secret
, current_hubapp
)
57 def setup(self
, secret
, current_hubapp
):
58 hubapp_dir
= Path(__file__
).parents
[1] / "hubapps" / current_hubapp
59 for file in os
.listdir(hubapp_dir
):
60 uri_file
= StaticFile
.remove_template_ext(file)
61 if uri_file
.startswith("master."):
62 uri
= f
"/{scramble(secret, uri_file)}"
63 if uri_file
== "master.html":
65 self
.context_vars
[uri_file
.replace(".", "_")] = uri
68 self
.static_files
[uri
] = StaticFile(hubapp_dir
/ file)
69 if uri_file
== "index.html":
70 self
.static_files
["/"] = self
.static_files
[uri
]
72 async def on_get(self
, req
, resp
):
74 index_uri
= f
"/index.html"
77 res
= self
.static_files
[path
]
78 resp
.data
= res
.render(self
.context_vars
)
79 resp
.content_type
= res
.mime_type
81 def add_routes(self
, app
):
82 for uri_template
in self
.static_files
:
83 app
.add_route(uri_template
, self
)