#!/usr/bin/env python3 import time, os try: from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler except: Observer = None FileSystemEventHandler = object class DogHandler(FileSystemEventHandler): last_reload = 0 def __init__(self, webview): super().__init__() self.webview = webview def on_modified(self, event): if os.path.isfile(event.src_path): stamp = int(time.time()) # 1秒内有多个修改, 不重复reload if stamp == self.last_reload: return self.last_reload = stamp self.webview.reload() def create_hmr_server(options = None): if Observer is None: print('Warning: HMR server depends on "python-watchdog". Please install it before using it') dog = None else: dog = Observer() def wrapper(app, extra = None): if dog is None: return if app.root: dog.schedule(DogHandler(app), app.root, recursive=True) dog.start() else: raise SyntaxError('Web root must be set before HMR server starts.') return wrapper