Beispiel #1
0
class FlaskJanitoo(object):

    def __init__(self, app=None, options=None, db=None):
        self._app = app
        self._db = db
        self.options = options
        if self.options is not None and 'conf_file' in self.options and self.options['conf_file'] is not None:
            logging_fileConfig(self.options['conf_file'])
        self._listener = None
        self._listener_lock = None
        self._sleep = 0.25
        self.menu_left = []
        # Bower
        self.bower = Bower()
        # Caching
        self.cache = Cache()

    def __del__(self):
        """
        """
        try:
            self.stop_listener()
        except Exception:
            pass

    def init_app(self, app, options, db=None):
        """
        """
        if app is not None:
            self._app = app
        if options is not None:
            self.options = options
        if db is not None:
            self._db = db
        if self.options is not None and 'conf_file' in self.options and self.options['conf_file'] is not None:
            logging_fileConfig(self.options['conf_file'])

        # Flask-Cache
        self.cache.init_app(self._app)
        # Flask-Bower
        self.bower.init_app(self._app)

        self._event_manager = EventManager(self._app)
        self._app.jinja_env.globals["emit_event"] = self._event_manager.template_emit
        if not hasattr(self._app, 'extensions'):
            self._app.extensions = {}
        self._app.extensions['options'] = self.options
        self._app.extensions['bower'] = self.bower
        self._app.extensions['cache'] = self.cache
        self._app.extensions['janitoo'] = self
        try:
            self._sleep = int(self._app.config['FLASKJANITOO_SLEEP'])
            if self._sleep <= 0 :
                self._sleep = 0.25
        except KeyError:
            self._sleep = 0.25
        except ValueError:
            self._sleep = 0.25
        # Use the newstyle teardown_appcontext if it's available,
        # otherwise fall back to the request context
        if hasattr(self._app, 'teardown_appcontext'):
            self._app.teardown_appcontext(self.teardown)
        else:
            self._app.teardown_request(self.teardown)
        signal.signal(signal.SIGTERM, self.signal_term_handler)
        signal.signal(signal.SIGINT, self.signal_term_handler)
        self._listener_lock = threading.Lock()

        self.create_listener()

    def create_listener(self):
        """Create the listener on first call
        """
        self._listener = ListenerThread(self._app, self.options)

    @property
    def listener(self):
        """Start the listener on first call
        """
        self.start_listener()
        return self._listener

    def start_listener(self):
        """Start the listener on first call
        """
        try:
            self._listener_lock.acquire()
            if not self._listener.is_alive():
                self._listener.start()
        finally:
            self._listener_lock.release()

    def stop_listener(self):
        """Stop the listener
        """
        try:
            self._listener_lock.acquire()
            self._listener.stop()
            try:
                self._listener.join()
            except RuntimeError:
                pass
            self._listener = None
        finally:
            self._listener_lock.release()

    def extend_blueprints(self, group):
        """
        """
        for entrypoint in iter_entry_points(group = '%s.blueprint'%'janitoo_manager'):
            logger.info('Add blueprint from %s', entrypoint.module_name )
            bprint, url = entrypoint.load()()
            self._app.register_blueprint(bprint, url_prefix=url)
        for entrypoint in iter_entry_points(group = '%s.menu_left'%group):
            logger.info('Extend menu_left with %s', entrypoint.module_name )
            self.menu_left.append(entrypoint.load()())
        self._app.template_context_processors[None].append(lambda : dict(jnt_menu_left=self.menu_left))

    def extend_network(self, group):
        """"Extend the network with methods found in entrypoints
        """
        if self._listener and self._listener.network:
            self._listener.network.extend_from_entry_points(group)
        else:
            raise RuntimeError("Can't extend an uninitialized network")

    def extend_listener(self, group):
        """"Extend the network with methods found in entrypoints
        """
        if self._listener:
            self._listener.extend_from_entry_points(group)
        else:
            raise RuntimeError("Can't extend an uninitialized listener")

    def signal_term_handler(self, signal, frame):
        """
        """
        logger.info("[ %s ] - Received signal %s", self.__class__.__name__, signal)
        if self._listener and self._listener.is_alive():
            self._listener.stop()
            try:
                self._listener.join()
            except AssertionError:
                logger.exception("Catched exception in signal_term_handler: ")
            except RuntimeError:
                logger.exception("Catched exception in signal_term_handler: ")
        sys.exit(0)

    #~ def connect(self):
        #~ return sqlite3.connect(current_app.config['SQLITE3_DATABASE'])

    #~ @property
    #~ def backend(self):
        #~ ctx = stack.top
        #~ if ctx is not None:
            #~ if not hasattr(ctx, 'tinyflow_backend'):
                #~ ctx.tinyflow_backend = self._backend
            #~ return ctx.tinyflow_backend
#~
    #~ @property
    #~ def thread(self):
        #~ ctx = stack.top
        #~ if ctx is not None:
            #~ if not hasattr(ctx, 'tinyflow_server'):
                #~ ctx.tinyflow_server = self._server
            #~ return ctx.tinyflow_server
#~
    def teardown(self, exception):
        pass
Beispiel #2
0
 def create_listener(self):
     """Create the listener on first call
     """
     self._listener = ListenerThread(self._app, self.options)