Realtime updates of wwwroot files when --dev is used.

This commit is contained in:
Leo Vasanko 2023-11-01 14:53:57 +00:00
parent 742b05ed66
commit a435a30c88

View File

@ -2,6 +2,7 @@ import mimetypes
from importlib.resources import files
from urllib.parse import unquote
import asyncio
import brotli
from sanic import Blueprint, Sanic, raw
from sanic.exceptions import Forbidden, NotFound
@ -64,27 +65,36 @@ www = {}
@app.before_server_start
def load_wwwroot(app):
www.clear()
global www
wwwnew = {}
base = files("cista") / "wwwroot"
paths = ["."]
while paths:
path = paths.pop(0)
current = base / path
print(">>>", current)
for p in current.iterdir():
if p.is_dir():
print(p)
paths.append(current / p.parts[-1])
continue
name = p.relative_to(base).as_posix()
mime = mimetypes.guess_type(name)[0] or "application/octet-stream"
data = p.read_bytes()
# Use old data if not changed
if name in www and www[name][0] == data:
wwwnew[name] = www[name]
continue
# Precompress with Brotli
br = brotli.compress(data)
if len(br) >= len(data):
br = False
print(name, len(data), len(br) if br else br, mime)
www[name] = data, br, mime
wwwnew[name] = data, br, mime
www = wwwnew
@app.add_task
async def refresh_wwwroot():
while app.debug:
await asyncio.sleep(0.5)
load_wwwroot(app)
@app.get("/<path:path>", static=True)
async def wwwroot(req, path=""):