Refactor watchdog Observer handling to a mixin

This commit is contained in:
Kristóf Tóth 2018-04-14 20:36:43 +02:00
parent b082279916
commit 586c435cc2
4 changed files with 23 additions and 21 deletions

View File

@ -3,31 +3,24 @@
from functools import wraps
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler as FileSystemWatchdogEventHandler
from tfw.networking.event_handlers import ServerUplinkConnector
from tfw.components.decorators import RateLimiter
from tfw.components.mixins import ObserverMixin
from tfw.config.logs import logging
LOG = logging.getLogger(__name__)
class DirectoryMonitor:
class DirectoryMonitor(ObserverMixin):
def __init__(self, directory):
self.observer = Observer()
ObserverMixin.__init__(self)
self.eventhandler = WebideReloadWatchdogEventHandler()
self.observer.schedule(self.eventhandler, directory, recursive=True)
self.pause, self.resume = self.eventhandler.pause, self.eventhandler.resume
def watch(self):
self.observer.start()
def stop(self):
self.observer.stop()
self.observer.join()
@property
def ignore(self):
return self.eventhandler.ignore

View File

@ -6,10 +6,9 @@ from re import findall
from re import compile as compileregex
from abc import ABC, abstractmethod
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
from tfw.components.mixins import CallbackMixin
from tfw.components.mixins import CallbackMixin, ObserverMixin
from tfw.components.decorators import RateLimiter
@ -24,13 +23,13 @@ class CallbackEventHandler(PatternMatchingEventHandler, ABC):
callback()
class HistoryMonitor(CallbackMixin, ABC):
class HistoryMonitor(CallbackMixin, ObserverMixin, ABC):
def __init__(self, histfile):
CallbackMixin.__init__(self)
ObserverMixin.__init__(self)
self.histfile = histfile
self._history = []
self._last_length = len(self._history)
self.observer = Observer()
self.observer.schedule(CallbackEventHandler([self.histfile],
self._fetch_history,
self._invoke_callbacks),
@ -60,13 +59,6 @@ class HistoryMonitor(CallbackMixin, ABC):
if self._last_length < len(self._history):
self._execute_callbacks(self.history)
def watch(self):
self.observer.start()
def stop(self):
self.observer.stop()
self.observer.join()
class BashMonitor(HistoryMonitor):
@property

View File

@ -3,3 +3,4 @@
from .supervisor_mixin import SupervisorMixin
from .callback_mixin import CallbackMixin
from .observer_mixin import ObserverMixin

View File

@ -0,0 +1,16 @@
# Copyright (C) 2018 Avatao.com Innovative Learning Kft.
# All Rights Reserved. See LICENSE file for details.
from watchdog.observers import Observer
class ObserverMixin:
def __init__(self):
self.observer = Observer()
def watch(self):
self.observer.start()
def stop(self):
self.observer.stop()
self.observer.join()