Python blinker.signal() Examples

The following are 30 code examples of blinker.signal(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module blinker , or try the search function .
Example #1
Source File: signals.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def send_safe(signal, logger, sender, **kwargs):
	"""
	Send a signal and catch any exception which may be raised during it's
	emission. Details regarding the error that occurs (including a stack trace)
	are logged to the specified *logger*. This is suitable for allowing signals
	to be emitted in critical code paths without interrupting the emitter.

	:param str signal: The name of the signal to send safely.
	:param logger: The logger to use for logging exceptions.
	:type logger: :py:class:`logging.Logger`
	:param sender: The sender for this signal emission.
	:param kwargs: The key word arguments to be forward to the signal as it is sent.
	"""
	return tuple(send_safe_iter(signal, logger, sender, **kwargs))

# campaign signals 
Example #2
Source File: server.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _send_safe_campaign_alerts(campaign, signal_name, sender, **kwargs):
	alert_subscriptions = tuple(subscription for subscription in campaign.alert_subscriptions if not subscription.has_expired)
	logger = logging.getLogger('KingPhisher.Server.CampaignAlerts')
	logger.debug("dispatching campaign alerts for '{0}' (sender: {1!r}) to {2:,} active subscriptions".format(signal_name, sender, len(alert_subscriptions)))
	if not alert_subscriptions:
		return
	signal = blinker.signal(signal_name)
	if not signal.receivers:
		logger.warning("users are subscribed to '{0}', and no signal handlers are connected".format(signal_name))
		return
	if not signal.has_receivers_for(sender):
		logger.info("users are subscribed to '{0}', and no signal handlers are connected for sender: {1}".format(signal_name, sender))
		return
	for subscription in alert_subscriptions:
		results = signals.send_safe(signal_name, logger, sender, alert_subscription=subscription, **kwargs)
		if any((result for (_, result) in results)):
			continue
		logger.warning("user {0} is subscribed to '{1}', and no signal handlers succeeded to send an alert".format(subscription.user.name, signal_name)) 
Example #3
Source File: server.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _do_rpc_method(self, *args, **kwargs):
		self.connection.settimeout(smoke_zephyr.utilities.parse_timespan('20s'))  # set a timeout as a fail safe
		self.rpc_session_id = self.headers.get(server_rpc.RPC_AUTH_HEADER, None)
		self.semaphore_acquire()

		http_method_handler = None
		try:
			signals.request_handle.send(self)
			http_method_handler = getattr(super(KingPhisherRequestHandler, self), 'do_RPC')
			http_method_handler(*args, **kwargs)
		except errors.KingPhisherAbortRequestError as error:
			if http_method_handler is None:
				self.logger.debug('rpc request aborted by a signal handler')
			else:
				self.logger.info('rpc request aborted')
			if not error.response_sent:
				self.respond_not_found()
		finally:
			self.semaphore_release()
		self.connection.settimeout(None) 
Example #4
Source File: frames.py    From MongoFrames with MIT License 6 votes vote down vote up
def unset(self, *fields):
        """Unset the given list of fields for this document."""

        # Send update signal
        signal('update').send(self.__class__, frames=[self])

        # Clear the fields from the document and build the unset object
        unset = {}
        for field in fields:
            self._document.pop(field, None)
            unset[field] = True

        # Update the document
        self.get_collection().update_one(
            {'_id': self._id},
            {'$unset': unset}
        )

        # Send updated signal
        signal('updated').send(self.__class__, frames=[self]) 
Example #5
Source File: frames.py    From MongoFrames with MIT License 6 votes vote down vote up
def insert_many(cls, documents):
        """Insert a list of documents"""
        from mongoframes.queries import to_refs

        # Ensure all documents have been converted to frames
        frames = cls._ensure_frames(documents)

        # Send insert signal
        signal('insert').send(cls, frames=frames)

        # Prepare the documents to be inserted
        documents = [to_refs(f._document) for f in frames]

        # Bulk insert
        ids = cls.get_collection().insert_many(documents).inserted_ids

        # Apply the Ids to the frames
        for i, id in enumerate(ids):
            frames[i]._id = id

        # Send inserted signal
        signal('inserted').send(cls, frames=frames)

        return frames 
Example #6
Source File: frames.py    From MongoFrames with MIT License 6 votes vote down vote up
def delete_many(cls, documents):
        """Delete multiple documents"""

        # Ensure all documents have been converted to frames
        frames = cls._ensure_frames(documents)

        all_count = len(documents)
        assert len([f for f in frames if '_id' in f._document]) == all_count, \
                "Can't delete documents without `_id`s"

        # Send delete signal
        signal('delete').send(cls, frames=frames)

        # Prepare the documents to be deleted
        ids = [f._id for f in frames]

        # Delete the documents
        cls.get_collection().delete_many({'_id': {'$in': ids}})

        # Send deleted signal
        signal('deleted').send(cls, frames=frames) 
Example #7
Source File: frames.py    From MongoFrames with MIT License 5 votes vote down vote up
def stop_listening(cls, event, func):
        """Remove a callback for a signal against the class"""
        signal(event).disconnect(func, sender=cls)

    # Misc. 
Example #8
Source File: trequestpool.py    From stig with GNU General Public License v3.0 5 votes vote down vote up
def requested_keys(self, sid):
        """Return keys requested by subscriber"""
        event = blinker.signal(sid)
        try:
            return self._keys[event]
        except KeyError:
            return () 
Example #9
Source File: frames.py    From MongoFrames with MIT License 5 votes vote down vote up
def insert(self):
        """Insert this document"""
        from mongoframes.queries import to_refs

        # Send insert signal
        signal('insert').send(self.__class__, frames=[self])

        # Prepare the document to be inserted
        document = to_refs(self._document)

        # Insert the document and update the Id
        self._id = self.get_collection().insert_one(document).inserted_id

        # Send inserted signal
        signal('inserted').send(self.__class__, frames=[self]) 
Example #10
Source File: frames.py    From MongoFrames with MIT License 5 votes vote down vote up
def update(self, *fields):
        """
        Update this document. Optionally a specific list of fields to update can
        be specified.
        """
        from mongoframes.queries import to_refs

        assert '_id' in self._document, "Can't update documents without `_id`"

        # Send update signal
        signal('update').send(self.__class__, frames=[self])

        # Check for selective updates
        if len(fields) > 0:
            document = {}
            for field in fields:
                document[field] = self._path_to_value(field, self._document)
        else:
            document = self._document

        # Prepare the document to be updated
        document = to_refs(document)
        document.pop('_id', None)

        # Update the document
        self.get_collection().update_one({'_id': self._id}, {'$set': document})

        # Send updated signal
        signal('updated').send(self.__class__, frames=[self]) 
Example #11
Source File: frames.py    From MongoFrames with MIT License 5 votes vote down vote up
def delete(self):
        """Delete this document"""

        assert '_id' in self._document, "Can't delete documents without `_id`"

        # Send delete signal
        signal('delete').send(self.__class__, frames=[self])

        # Delete the document
        self.get_collection().delete_one({'_id': self._id})

        # Send deleted signal
        signal('deleted').send(self.__class__, frames=[self]) 
Example #12
Source File: frames.py    From MongoFrames with MIT License 5 votes vote down vote up
def unset_many(self, documents, *fields):
        """Unset the given list of fields for this document."""

        # Ensure all documents have been converted to frames
        frames = cls._ensure_frames(documents)

        all_count = len(documents)
        assert len([f for f in frames if '_id' in f._document]) == all_count, \
                "Can't update documents without `_id`s"

        # Send update signal
        signal('update').send(cls, frames=frames)

        # Build the unset object
        unset = {}
        for field in fields:
            unset[field] = True

        # Clear the fields from the documents and build a list of ids to
        # update.
        ids = []
        for document in documents:
            ids.append(document._id)
            for frame in frames:
                frame._document.pop(field, None)

        # Update the document
        self.get_collection().update_many(
            {'_id': {'$in': ids}},
            {'$unset': unset}
        )

        # Send updated signal
        signal('updated').send(cls, frames=frames) 
Example #13
Source File: frames.py    From MongoFrames with MIT License 5 votes vote down vote up
def listen(cls, event, func):
        """Add a callback for a signal against the class"""
        signal(event).connect(func, sender=cls) 
Example #14
Source File: trequestpool.py    From stig with GNU General Public License v3.0 5 votes vote down vote up
def register(self, sid, callback, keys=(), tfilter=None):
        """Add new request to request pool

        sid: Subscriber ID (any hashable)
        callback: Callable that receives a tuple of Torrents on updates
        keys: Wanted Torrent keys
        tfilter: None for all torrents or TorrentFilter instance
        """
        log.debug('Registering subscriber: %s', sid)
        event = blinker.signal(sid)
        event.connect(callback)
        self._keys[event] = set(keys)
        self._tfilters[event] = tfilter

        # TODO issue #163: Enable call to skip_ongoing_request() if calling in
        # RequestPoller.set_request() doesn't help.

        # # It's possible that a currently ongoing request doesn't collect the
        # # keys this new callback needs.  In that case, the request is finished
        # # AFTER we added the callback, and the callback would be called with
        # # lacking keys, resuling in a KeyError.
        # # Therefore we ask the poller to dump the result of a currently
        # # ongoing request to prevent this.
        # if self.running:
        #     self.skip_ongoing_request()

        self._combine_requests() 
Example #15
Source File: decorators.py    From slack-machine with MIT License 5 votes vote down vote up
def on(event):
    """Listen for an event

    The decorated function will be called whenever a plugin (or Slack Machine itself) emits an
    event with the given name.

    :param event: name of the event to listen for. Event names are global
    """

    def on_decorator(f):
        e = signal(event)
        e.connect(f)
        return f

    return on_decorator 
Example #16
Source File: base.py    From slack-machine with MIT License 5 votes vote down vote up
def emit(self, event: str, **kwargs):
        """Emit an event

        Emit an event that plugins can listen for. You can include arbitrary data as keyword
        arguments.

        :param event: name of the event
        :param kwargs: any data you want to emit with the event
        :return: None
        """
        e = signal(event)
        e.send(self, **kwargs) 
Example #17
Source File: test_decorators.py    From slack-machine with MIT License 5 votes vote down vote up
def test_on(on_f):
    e = signal('test_event')
    assert bool(e.receivers) 
Example #18
Source File: engine.py    From sauron-engine with MIT License 5 votes vote down vote up
def __init__(
        self,
        context: Dict[str, Any] = None,
        job_model: Type[JobModel] = None,
        parser_class: Type[DefaultParser] = None,
        exporter_class: Type[DefaultExporter] = None,
    ):
        """
        - Sessions can be initialized with a context provided by the user
        - Job Model and Parser can be changed
        """
        if context:
            self.session = context

        if job_model:
            self.job_model_class = job_model

        if parser_class:
            self.parser_class = parser_class

        if exporter_class:
            self.exporter_class = exporter_class
        self.callables_collected: "OrderedDict[str, Dict[str, Any]]" = OrderedDict()

        self.runtime_metrics["jobs"] = {}
        self.runtime_metrics["total_runtime"] = 0

        self.signals["pre_engine_run"] = signal("pre_engine_run")
        self.signals["post_engine_run"] = signal("post_engine_run")
        self.signals["pre_job_call"] = signal("pre_job_call")
        self.signals["post_job_call"] = signal("post_job_call") 
Example #19
Source File: namespaces.py    From esdc-ce with Apache License 2.0 5 votes vote down vote up
def on_dc_switch(self):
        # Reload user object in request
        self.request.user = self.request.user.__class__.objects.get(pk=self.request.user.pk)
        self.setup_user()
        self.set_active_user()

        # Inform other sessions for this user about the DC change
        task_id = task_id_from_request(self.user_id, tt=TT_INTERNAL, tg=TG_DC_UNBOUND, dc_id=self.dc_id)
        self.last_tasks.append(task_id)
        new_task = signal('task-for-' + self.user_id)
        new_task.send('_dc_switch', task_id=task_id, event_status='internal')

    # noinspection PyUnusedLocal 
Example #20
Source File: namespaces.py    From esdc-ce with Apache License 2.0 5 votes vote down vote up
def que_monitor(self):
        new_task = signal('task-for-' + self.user_id)

        # noinspection PyUnusedLocal
        @new_task.connect
        def process_task(sender, task_id=None, event_status=None, **kwargs):
            self.log('Got signal for %s task %s', event_status, task_id, level=DEBUG)
            task_prefix = task_prefix_from_task_id(task_id)

            if task_prefix[4] != self.dc_id and task_prefix[3] != TG_DC_UNBOUND:
                self.log('Ignoring dc-bound task %s, because user works in DC %s', task_id, self.dc_id)
                return

            if event_status == 'sent':
                self._task_sent(task_id, event_status, sender, task_prefix[1])
            elif event_status == 'event':
                self._task_event(task_id, sender)
            elif event_status == 'internal':
                self._task_internal(task_id, sender, **kwargs)
            else:
                self._task_status(task_id, event_status, task_prefix[1])

        self.log('Ready')
        self.set_active_user()

        try:
            while True:
                sleep(1.0)
        finally:
            self.log('Game over')
            self.del_active_user() 
Example #21
Source File: trequestpool.py    From stig with GNU General Public License v3.0 5 votes vote down vote up
def remove(self, sid):
        """Unsubscribe previously registered subscriber"""
        log.debug('Removing subscriber: %s', sid)
        event = blinker.signal(sid)
        del self._keys[event]
        del self._tfilters[event]
        self._combine_requests() 
Example #22
Source File: notify.py    From pagure with GNU General Public License v2.0 5 votes vote down vote up
def blinker_publish(topic, message):
    _log.info("Sending blinker signal to: pagure - topic: %s", topic)
    ready = blinker.signal("pagure")
    ready.send("pagure", topic=topic, message=message) 
Example #23
Source File: topic_based_events.py    From Expert-Python-Programming-Third-Edition with MIT License 5 votes vote down vote up
def __init__(self):
        self._id = next(self._new_id)
        init_signal = signal("SelfWatch.init")
        init_signal.send(self)
        init_signal.connect(self.receiver) 
Example #24
Source File: __init__.py    From AstroBox with GNU Affero General Public License v3.0 5 votes vote down vote up
def stopJanus(self):
		with self._janusStartStopCondition:
			try:
				if self._JanusProcess is not None:
					#it's possible that a new client came it while stopping the camera feed
					#in that case we should not try to stop it
					if self._JanusProcess.returncode is None:
						self._logger.debug('Attempting to terminate the Janus process')
						self._JanusProcess.terminate()

						attempts = 6
						while self._JanusProcess.returncode is None and attempts > 0:
							time.sleep(0.3)
							self._JanusProcess.poll()
							attempts -= 1

						if self._JanusProcess.returncode is None:
							#still not terminated
							self._logger.debug('Janus didn\'t terminate nicely, let\'s kill it')
							self._JanusProcess.kill()
							self._JanusProcess.wait()

						self._logger.debug('Janus Stopped')

					self._JanusProcess = None
					self.sendEventToPeers('stopConnection')
					self._connectedPeers = {}

					#STOP TIMER FOR LOST PEERS
					if self.peersDeadDetacher:
						self.peersDeadDetacher.cancel()

					ready = signal('manage_fatal_error_webrtc')
					ready.disconnect(self.closeAllSessions)

					return True

			except Exception as e:
				self._logger.error("Error stopping Janus. Error: %s" % e)

			return False 
Example #25
Source File: flaskext.py    From sqlalchemy-jsonapi with MIT License 5 votes vote down vote up
def override(original, results):
    """
    If a receiver to a signal returns a value, we override the original value
    with the last returned value.

    :param original: The original value
    :param results: The results from the signal
    """
    overrides = [v for fn, v in results if v is not None]
    if len(overrides) == 0:
        return original
    return overrides[-1] 
Example #26
Source File: owned.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def owned_post_save(sender, document, **kwargs):
    '''
    Owned mongoengine.post_save signal handler
    Dispatch the `Owned.on_owner_change` signal
    once the document has been saved including the previous owner.

    The signal handler should have the following signature:
    ``def handler(document, previous)``
    '''
    if isinstance(document, Owned) and hasattr(document, '_previous_owner'):
        Owned.on_owner_change.send(document, previous=document._previous_owner) 
Example #27
Source File: owned.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def owned_pre_save(sender, document, **kwargs):
    '''
    Owned mongoengine.pre_save signal handler
    Need to fetch original owner before the new one erase it.
    '''
    if not isinstance(document, Owned):
        return
    changed_fields = getattr(document, '_changed_fields', [])
    if 'organization' in changed_fields:
        if document.owner:
            # Change from owner to organization
            document._previous_owner = document.owner
            document.owner = None
        else:
            # Change from org to another
            # Need to fetch previous value in base
            original = sender.objects.only('organization').get(pk=document.pk)
            document._previous_owner = original.organization
    elif 'owner' in changed_fields:
        if document.organization:
            # Change from organization to owner
            document._previous_owner = document.organization
            document.organization = None
        else:
            # Change from owner to another
            # Need to fetch previous value in base
            original = sender.objects.only('owner').get(pk=document.pk)
            document._previous_owner = original.owner 
Example #28
Source File: FreeCAD_Signal.py    From NodeEditor with MIT License 5 votes vote down vote up
def __init__(self, name="baked",**kvargs):

        super(self.__class__, self).__init__(name)
        self.inExec = self.createInputPin(DEFAULT_IN_EXEC_NAME, 'ExecPin', None, self.compute)
        self.outExec = self.createOutputPin(DEFAULT_OUT_EXEC_NAME, 'ExecPin')
        self.signal=self.createInputPin('step', 'FloatPin', 2)
        self.signal=self.createOutputPin('message', 'StringPin') 
Example #29
Source File: FreeCAD_Signal.py    From NodeEditor with MIT License 5 votes vote down vote up
def unsubscribe(self, *args, **kwargs):
        from blinker import signal
        sn=self.getData('signalName')
        send_data = signal(sn)
        send_data.disconnect(self.r)
        sayl()

        self.r=None
        self.sender = None
        self.kw = None 
Example #30
Source File: FreeCAD_Signal.py    From NodeEditor with MIT License 5 votes vote down vote up
def subscribe(self, *args, **kwargs):
        sayl()
        from blinker import signal
        sn=self.getData('signalName')

        send_data = signal(sn)
        @send_data.connect
        def receive_data(sender, **kw):
            print("%r: caught signal from %r, data %r" % (self.name,sender, kw))
            print ("SENDER",sender)
            
            try:
                self.sender = sender
                self.kw = kw
            except:
                print("PROBLEME mit sendern")
                return
            
            self.setData("senderName",sender)
            self.setData("senderMessage",self.kw['message'])
            self.setData("senderObject",self.kw['obj'])
            self.setColor(b=0,a=0.4)
            self.outExec.call()
            
            return ("got return from  "+ self.name)
            
        self.r=receive_data