class Signals(): signals = Namespace() # Special instance to collect context for each instance, # required for status_change signal handling StatusChangeSignalObjectContext = collections.namedtuple( "StatusChangeSignalObjectContext", [ "instance", # instance, with modified status "old_status", # old status value "new_status", # new status value ], ) status_change = signals.signal( 'Status Changed', """ This is used to signal any listeners of any changes in model object status attribute """) workflow_cycle_start = signals.signal( 'Workflow Cycle Started ', """ This is used to signal any listeners of any workflow cycle start attribute """)
def test_failing_receiver(base_app, event_entrypoints, caplog): """Test failing signal receiver function.""" try: _signals = Namespace() my_signal = _signals.signal('my-signal') def failing_event_builder(event, sender_app): raise Exception('builder-exception') base_app.config.update( dict(STATS_EVENTS=dict(event_0=dict( signal=my_signal, event_builders=[failing_event_builder])))) InvenioStats(base_app) current_queues.declare() with caplog.at_level(logging.ERROR): my_signal.send(base_app) error_logs = [r for r in caplog.records if r.levelno == logging.ERROR] assert len(error_logs) == 1 assert error_logs[0].msg == 'Error building event' assert error_logs[0].exc_info[1].args[0] == 'builder-exception' # Check that no event was sent to the queue assert get_queue_size('stats-event_0') == 0 finally: current_queues.delete()
def test_register_receivers(base_app, event_entrypoints): """Test signal-receiving/event-emitting functions registration.""" try: _signals = Namespace() my_signal = _signals.signal('my-signal') def event_builder1(event, sender_app, signal_param, *args, **kwargs): event.update(dict(event_param1=signal_param)) return event def event_builder2(event, sender_app, signal_param, *args, **kwargs): event.update(dict(event_param2=event['event_param1'] + 1)) return event base_app.config.update( dict(STATS_EVENTS=dict(event_0=dict( signal=my_signal, event_builders=[event_builder1, event_builder2])))) InvenioStats(base_app) current_queues.declare() my_signal.send(base_app, signal_param=42) my_signal.send(base_app, signal_param=42) events = [event for event in current_stats.consume('event_0')] # two events should have been created from the sent events. They should # have been both processed by the two event builders. assert events == [{'event_param1': 42, 'event_param2': 43}] * 2 finally: current_queues.delete()
def __init__(self, app): self.__app = app # self.__log = app.log self.__log = logging.getLogger(__name__) #: Dictionary of registered signals. Dictionary key is the registered signal name. #: Value is an instance of :class:`~groundwork.signals.Signal`. self.signals = {} #: Dictionary of registered receivers. Dictionary key is the registered receiver name. #: Value is an instance of :class:`~groundwork.signals.Receiver`. self.receivers = {} # We must use an unique namespace for our signals. Otherwise we get problems with multiple applications or # application recreation, because blinker throws every signal to a "singleton container", which stays # the same for the whole runtime of the python interpreter. No cleanup or anything else. # So registered signals and receivers keep registered, whatever you do with the app. # How to use namespace in blinker? See: # http://flask.pocoo.org/docs/0.11/signals/#creating-signals for blinker namespace usage # https://github.com/jek/blinker/blob/master/blinker/base.py#L432 #: Used blinker namespace object to register signals only for the context of a single groundwork application #: instance self._namespace = Namespace() self.__log.info("Application signals initialised")
class Event(object): events = Namespace() @classmethod def fire(cls, name, *args, **kwargs): name = "orator.%s" % name signal = cls.events.signal(name) for response in signal.send(*args, **kwargs): if response[1] is False: return False @classmethod def listen(cls, name, callback, *args, **kwargs): name = "orator.%s" % name signal = cls.events.signal(name) signal.connect(callback, weak=False, *args, **kwargs) @classmethod def forget(cls, name, *args, **kwargs): name = "orator.%s" % name signal = cls.events.signal(name) for receiver in signal.receivers: signal.disconnect(receiver, *args, **kwargs)
def test_failing_receiver(base_app, caplog): """Test failing signal receiver function.""" try: _signals = Namespace() my_signal = _signals.signal('my-signal') def failing_event_builder(event, sender_app): raise Exception('builder-exception') # NOTE: event_0 already exists from the mocked events decorate further. base_app.config['STATS_EVENTS']['event_0'].update({ 'signal': my_signal, 'event_builders': [failing_event_builder] }) InvenioStats(base_app) current_queues.declare() with caplog.at_level(logging.ERROR): my_signal.send(base_app) error_logs = [r for r in caplog.records if r.levelno == logging.ERROR] assert len(error_logs) == 1 assert error_logs[0].msg == 'Error building event' assert error_logs[0].exc_info[1].args[0] == 'builder-exception' # Check that no event was sent to the queue assert get_queue_size('stats-event_0') == 0 finally: current_queues.delete()
class Signals: """Defines signals that are thrown on database changes.""" _namespace = Namespace() changed = _namespace.signal("changed") deleted = _namespace.signal("deleted") new = _namespace.signal("new")
def init_ag(self): self.ag = BlankObject() self.ag.app = self self.ag.view_functions = {} self.ag.hierarchy_import_cache = {} self.ag.hierarchy_file_cache = {} self.ag.events_namespace = Namespace() ag._push_object(self.ag)
def init(self, min_server_num=1): self.blinker = Namespace() self.services = {} self.service_list_change_signal = {} self.min_server_num = min_server_num self.linked_cluster = {} self.watched_service = {} self.watched_service_nodes = defaultdict(list) self.watched_service_nodes_signals = defaultdict(list)
class Signals(): signals = Namespace() status_change = signals.signal( 'Status Changed', """ This is used to signal any listeners of any changes in model object status attribute """) workflow_cycle_start = signals.signal( 'Workflow Cycle Started ', """ This is used to signal any listeners of any workflow cycle start attribute """)
class SpreadsPlugin(object): # pragma: no cover """ Plugin base class. """ signals = Namespace() on_progressed = signals.signal('plugin:progressed', doc="""\ Sent by a :class:`SpreadsPlugin` when it has progressed in a long-running operation. :argument :class:`SpreadsPlugin`: the SpreadsPlugin that progressed :keyword float progress: the progress as a value between 0 and 1 """) @classmethod def configuration_template(cls): """ Allows a plugin to define its configuration keys. The returned dictionary has to be flat (i.e. no nested dicts) and contain a OptionTemplate object for each key. Example:: { 'a_setting': OptionTemplate(value='default_value'), 'another_setting': OptionTemplate(value=[1, 2, 3], docstring="A list of things"), # In this case, 'full-fat' would be the default value 'milk': OptionTemplate(value=('full-fat', 'skim'), docstring="Type of milk", selectable=True), } :return: dict with unicode: OptionTemplate(value, docstring, selection) """ pass def __init__(self, config): """ Initialize the plugin. :param config: The global configuration object, by default only the section with plugin-specific values gets stored in the `config` attribute, if the plugin has a `__name__` attribute. :type config: confit.ConfigView """ if hasattr(self, '__name__'): self.config = config[self.__name__] else: self.config = config
def __init__(self): self.signals = Namespace() self.start = self.signals.signal("start") self.start.connect(execution.start) self.stop = self.signals.signal("stop") self.stop.connect(execution.stop) self.pause = self.signals.signal("pause") self.pause.connect(execution.pause) self.shutdown = self.signals.signal("shutdown") self.shutdown.connect(execution.shutdown)
class Signals(object): """Class storing various general purpose signals Class storing various general purpose non-RESTful signals. """ # pylint: disable=too-few-public-methods signals = Namespace() custom_attribute_changed = signals.signal( "Custom Attribute updated", """ Indicates that a custom attribute was successfully saved to database. :obj: The model instance :value: New custom attribute value :service: The instance of model handling the Custom Attribute update operation """, )
def __init__(self, servers=None, username=None, password=None, base_path='/', retry_max_delay=2, max_retries=None, handler=None, local_mode=False, lazy=True): if has_kazoo: self.local_mode = local_mode self.handler_class = SequentialGeventHandler else: self.local_mode = True self.handler_class = None self.base_path = base_path self.watched_blinker = Namespace() self.watched_node = {} self.watched_path = {} self.watched_path_callback = set() self.servers = servers or '127.0.0.1:2181' self.username = username self.password = password self._client = None self._client_lock = None self.default_acl = [] self.retry_max_delay = retry_max_delay self.max_retries = max_retries self.lazy = lazy #: ``True`` if the :meth:`BaseClient.start` is in progress at least. #: You should never check the session state from this attribute. It #: will not be assigned ``False`` until the :meth:`BaseClient.stop` #: has being called explicitly, even if the connection is lost already. self.started = False #: The background threading to manage the aliveness of session. self.starting = None # record the pid when Huskar inits # Huskar can't be run in multiprocess env self.huskar_pid = os.getpid() # record zk actual connection server self.host = None
def stop(self): """Stop client and close the connection.""" # disconnect signals self.watched_blinker = Namespace() self.watched_node = {} self.watched_path = {} self.watched_path_callback = set() if not getattr(self, '_client', None): return if getattr(self.starting, 'kill', None): self.starting.kill() with self.client_lock: self.started = False with self.suppress_kazoo_exception('huskar_sdk_v2.stop'): self.client.remove_listener(self._state_listener) self.client.stop() self.client.close() del self.client if self.starting is not None: self.starting.join() self.starting = None
from flask import current_app from blinker import Namespace from dbhelper import DBHelper import datetime DB = DBHelper emitting_signal = Namespace() def summary_signal(user_id): DB.click_summary(user_id, date=datetime.datetime.utcnow()) summary = emitting_signal.signal('summary_signal') summary.connect(summary_signal, current_app)
from flask import Flask, jsonify from blinker import Namespace # 创建信号 model_signal = Namespace() model_saved = model_signal.signal('models-signal') app = Flask(__name__) app.config['DEBUG'] = True class LuckyModel: def __init__(self): self.data = {} def save(self, id, name): self.data[id] = name ret = model_saved.send(self, id=id, name=name) print(ret) model = LuckyModel() @model_saved.connect_via(model) def add_balance(sender, id, name): print(sender, id, name) print("add balance 执行了") return True
# initialize impersonation impersonation = Impersonation() # initialize celery celery = Celery( backend=config.get("CELERY_RESULT_BACKEND"), broker=config.get("CELERY_BROKER_URL"), result_expires=(30 * 60), # 30 minutes ) # initialize Flask-Mail mail = Mail() # create custom namespace for signals event = Namespace() # subscribe user_logged_in signal to generate auth token @user_logged_in.connect def generate_session_token(sender, user, **extra): sess['session_token'] = user.generate_session_token() def random_generator(size=8, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for _ in range(size)) def allowed_file(filename, allowed): return '.' in filename and \ filename.lower().rsplit('.', 1)[1] in allowed
from blinker import Namespace namespace = Namespace() #: Trigerred when an HTTP request is issued against the API on_api_call = namespace.signal('on-api-call')
from blinker import signal, Namespace ns = Namespace() a = lambda x: '{},+1'.format(x)
from __future__ import absolute_import import logging import functools import collections import simplejson as json from blinker import Namespace from huskar_sdk_v2.utils import combine from huskar_sdk_v2.consts import COMPONENT_PATH, OVERALL, SIG_CLIENT_RESTART logger = logging.getLogger(__name__) blinker = Namespace() def require_connection(func): """A decorator for :py:class:`~.components.BaseComponent` methods to ensure ``self.start`` had already invoked. Remember to set ``self.started`` in ``self.start`` and clear it in ``self.init``. """ @functools.wraps(func) def wrapper(self, *args, **kwargs): if self.lazy and not self.local_mode: if not self.started: self.start() self.started_timeout.wait() return func(self, *args, **kwargs)
""" byceps.blueprints.snippet.signals ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from blinker import Namespace snippet_signals = Namespace() snippet_created = snippet_signals.signal('snippet-created') snippet_updated = snippet_signals.signal('snippet-updated')
def __init__(self, blinker_namespace=None): if blinker_namespace is None: blinker_namespace = Namespace() self.namespace = blinker_namespace
# KuberDock - is a platform that allows users to run applications using Docker # container images and create SaaS / PaaS based on these applications. # Copyright (C) 2017 Cloud Linux INC # # This file is part of KuberDock. # # KuberDock is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # KuberDock is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with KuberDock; if not, see <http://www.gnu.org/licenses/>. from blinker import Namespace users_signals = Namespace() user_logged_in = users_signals.signal('user_logged_in') user_logged_out = users_signals.signal('user_logged_out') user_logged_in_by_another = users_signals.signal('user_logged_in_by_another') user_logged_out_by_another = users_signals.signal('user_logged_out_by_another') user_get_all_settings = users_signals.signal('user_get_all_settings') user_get_setting = users_signals.signal('user_get_setting') user_set_setting = users_signals.signal('user_set_setting')
from blinker import Namespace flasktasks_signals = Namespace() event_created = flasktasks_signals.signal('event-created') promoter_created = flasktasks_signals.signal('castmember-created') venue_created = flasktasks_signals.signal('venue-created')
class Restful(object): """Class storing REST-related signals.""" signals = Namespace() model_posted = signals.signal( "Model POSTed", """ Indicates that a model object was received via POST and will be committed to the database. The sender in the signal will be the model class of the POSTed resource. The following arguments will be sent along with the signal: :obj: The model instance created from the POSTed JSON. :src: The original POSTed JSON dictionary. :service: The instance of Resource handling the POST request. """,) collection_posted = signals.signal( "Collection POSTed", """ Indicates that a list of models was received via POST and will be committed to the database. The sender in the signal will be the model class of the POSTed resource. The following arguments will be sent along with the signal: :objects: The model instance created from the POSTed JSON. :src: The original POSTed JSON dictionary. :service: The instance of Resource handling the POST request. """,) model_posted_after_commit = signals.signal( "Model POSTed - after", """ Indicates that a model object was received via POST and has been committed to the database. The sender in the signal will be the model class of the POSTed resource. The following arguments will be sent along with the signal: :obj: The model instance created from the POSTed JSON. :src: The original POSTed JSON dictionary. :service: The instance of Resource handling the POST request. :event: Instance of an Event (if change took place) or None otherwise """,) model_put = signals.signal( "Model PUT", """ Indicates that a model object update was received via PUT and will be updated in the database. The sender in the signal will be the model class of the PUT resource. The following arguments will be sent along with the signal: :obj: The model instance updated from the PUT JSON. :src: The original PUT JSON dictionary. :service: The instance of Resource handling the PUT request. """,) model_put_after_commit = signals.signal( "Model PUT - after", """ Indicates that a model object update was received via PUT and has been updated in the database. The sender in the signal will be the model class of the PUT resource. The following arguments will be sent along with the signal: :obj: The model instance updated from the PUT JSON. :src: The original PUT JSON dictionary. :service: The instance of Resource handling the PUT request. :event: Instance of an Event (if change took place) or None otherwise """,) model_deleted = signals.signal( "Model DELETEd", """ Indicates that a model object was DELETEd and will be removed from the databse. The sender in the signal will be the model class of the DELETEd resource. The followin garguments will be sent along with the signal: :obj: The model instance removed. :service: The instance of Resource handling the DELETE request. """,) model_deleted_after_commit = signals.signal( "Model DELETEd - after", """ Indicates that a model object was DELETEd and has been removed from the database. The sender in the signal will be the model class of the DELETEd resource. The followin garguments will be sent along with the signal: :obj: The model instance removed. :service: The instance of Resource handling the DELETE request. :event: Instance of an Event (if change took place) or None otherwise """,)
from flask import request, current_app from blinker import Namespace from . import models, ext from OctBlog.config import OctBlogSettings search_engine_submit_urls = OctBlogSettings['search_engine_submit_urls'] octblog_signals = Namespace() post_visited = octblog_signals.signal('post-visited') post_pubished = octblog_signals.signal('post-published') @post_visited.connect def on_post_visited(sender, post, **extra): tracker = models.Tracker() tracker.post = post # if request.headers.getlist("X-Forwarded-For"): # ip = request.headers.getlist("X-Forwarded-For")[0] # else: # ip = request.remote_addr proxy_list = request.headers.getlist('X-Forwarded-For') tracker.ip = request.remote_addr if not proxy_list else proxy_list[0] tracker.user_agent = request.headers.get('User-Agent') tracker.save() try: post_statistic = models.PostStatistics.objects.get(post=post)
import time try: from blinker import Namespace except ImportError: Namespace = None from .histogram import Histogram, DEFAULT_SIZE, DEFAULT_ALPHA from .meter import Meter if Namespace is not None: timer_signals = Namespace() call_too_long = timer_signals.signal("call_too_long") else: call_too_long = None class Timer(object): """ A timer metric which aggregates timing durations and provides duration statistics, plus throughput statistics via Meter and Histogram. """ def __init__(self, threshold=None, size=DEFAULT_SIZE, alpha=DEFAULT_ALPHA, clock=time, sink=None, sample=None): super(Timer, self).__init__() self.meter = Meter(clock=clock) self.hist = Histogram(size=size,
from blinker import Namespace _signals = Namespace() can_access = _signals.signal( 'can-access', """ Called when `ProtectionMixin.can_access` is used to determine if a user can access something or not. The `sender` is the type of the object that's using the mixin. The actual instance is passed as `obj`. The `user` and `allow_admin` arguments of `can_access` are passed as kwargs with the same name. The `authorized` argument is ``None`` when this signal is called at the beginning of the access check and ``True`` or ``False`` at the end when regular access rights have already been checked. For expensive checks (such as anything involving database queries) it is recommended to skip the check while `authorized` is ``None`` since the regular access check is likely to be cheaper (due to ACLs being preloaded etc). If the signal returns ``True`` or ``False``, the access check succeeds or fails immediately. If multiple subscribers to the signal return contradictory results, ``False`` wins and access is denied. """) can_manage = _signals.signal( 'can-manage', """ Called when `ProtectionMixin.can_manage` is used to determine if a user can manage something or not. The `sender` is the type of the object that's using the mixin. The
parser.add_argument( '-g', '--glia', default=app.config['LOGIN_SERVER'], help="glia server") args = parser.parse_args() app.config['LOCAL_PORT'] = args.port app.config['NO_UI'] = args.no_ui app.config['LOGIN_SERVER'] = args.glia # Setup SQLAlchemy database db = SQLAlchemy(app) # Setup Blinker namespace notification_signals = Namespace() # Setup attachment access attachments = uploads.UploadSet('attachments', uploads.IMAGES) uploads.configure_uploads(app, (attachments)) # Setup loggers # Flask is configured to route logging events only to the console if it is in debug # mode. This overrides this setting and enables a new logging handler which prints # to the shell. loggers = [app.logger, logging.getLogger('synapse')] console_handler = logging.StreamHandler(stream=sys.stdout) console_handler.setFormatter(logging.Formatter(app.config['LOG_FORMAT'])) for l in loggers: del l.handlers[:] # remove old handlers