feat(hot-reload): Implement HotReloader.reload and reload_all
This commit is contained in:
+36
-1
@@ -29,4 +29,39 @@ class HotReloader:
|
||||
@classmethod
|
||||
def restore_state(cls, app: Any, state: dict[str, Any]) -> None:
|
||||
for key, value in state.items():
|
||||
setattr(app, key, value)
|
||||
setattr(app, key, value)
|
||||
|
||||
@classmethod
|
||||
def reload(cls, module_name: str, app: Any) -> bool:
|
||||
if module_name not in cls.HOT_MODULES:
|
||||
cls.last_error = f"Module {module_name} not registered"
|
||||
cls.is_error_state = True
|
||||
return False
|
||||
|
||||
hm = cls.HOT_MODULES[module_name]
|
||||
state = cls.capture_state(app, hm.state_keys)
|
||||
|
||||
try:
|
||||
import importlib
|
||||
import sys
|
||||
if module_name in sys.modules:
|
||||
old_module = sys.modules[module_name]
|
||||
importlib.reload(old_module)
|
||||
else:
|
||||
importlib.import_module(module_name)
|
||||
cls.last_error = None
|
||||
cls.is_error_state = False
|
||||
return True
|
||||
except Exception:
|
||||
cls.restore_state(app, state)
|
||||
cls.last_error = traceback.format_exc()
|
||||
cls.is_error_state = True
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def reload_all(cls, app: Any) -> bool:
|
||||
success = True
|
||||
for name in cls.HOT_MODULES:
|
||||
if not cls.reload(name, app):
|
||||
success = False
|
||||
return success
|
||||
Reference in New Issue
Block a user