auto reload at file change

This commit is contained in:
2025-04-12 20:49:48 +02:00
parent d99683eab9
commit 3e73280e7a
3 changed files with 27 additions and 19 deletions

36
main.py
View File

@@ -1,7 +1,8 @@
import os
from flask import Flask
from watchdog.observers import Observer
from flask import Flask, Response
import threading
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
# -------------- VARIABLES --------------
html_file_path = r"PATH"
@@ -12,20 +13,27 @@ scroll_pixels = 100
scroll_interval = 3 # seconds
bottom_wait_time = 3 # seconds
top_wait_time = 3 # seconds
reload_interval = 35 # seconds
# -------------- END VARIABLES --------------
app = Flask(__name__)
file_change_event = threading.Event()
class FileChangeHandler(FileSystemEventHandler):
def __init__(self, app):
self.app = app
def on_modified(self, event):
if event.src_path == html_file_path:
with self.app.app_context():
self.app.config["TEMPLATES_AUTO_RELOAD"] = True
file_change_event.set()
@app.route("/_file_change")
def file_change_stream():
def stream():
while True:
file_change_event.wait()
yield "data: reload\n\n"
file_change_event.clear()
return Response(stream(), content_type="text/event-stream")
@app.route("/")
@@ -38,12 +46,11 @@ def serve_html():
scroll-behavior: smooth;
}}
</style>
<script>
<script>
let scrollAmount = {scroll_pixels};
let scrollInterval = {scroll_interval} * 1000;
let bottomWaitTime = {bottom_wait_time} * 1000;
let topWaitTime = {top_wait_time} * 1000;
let reloadInterval = {reload_interval} * 1000;
let scrollPos = 0;
let scrollingDown = true;
@@ -76,7 +83,10 @@ def serve_html():
window.onload = function() {{
window.scrollTo(0, 0);
if (document.body.scrollHeight <= window.innerHeight) {{
setTimeout(reloadPage, reloadInterval);
const eventSource = new EventSource('/_file_change');
eventSource.onmessage = function() {{
location.reload();
}};
}} else {{
setTimeout(autoScroll, topWaitTime);
}}
@@ -87,7 +97,7 @@ def serve_html():
if __name__ == "__main__":
event_handler = FileChangeHandler(app)
event_handler = FileChangeHandler()
observer = Observer()
observer.schedule(
event_handler, path=os.path.dirname(html_file_path), recursive=False
@@ -97,4 +107,4 @@ if __name__ == "__main__":
app.run(host=host, port=port)
except KeyboardInterrupt:
observer.stop()
observer.join()
observer.join()