class MySignal: def __init__(self): self.signals = {} self.signal = Namespace() def init_app(self, app): pass def addSignal(self, classname, option): logger.debug('add signal {}.{}'.format(classname, option)) if '{}.{}'.format(classname, option) not in self.signals.keys(): self.signals['{}.{}'.format(classname, option)] = self.signal.signal('{}.{}'.format(classname, option)) def send(self, classname, option, **extra): logger.debug('send signal {}.{} with: {}'.format(classname, option, extra)) logger.info('send signal {}.{}'.format(classname, option)) if '{}.{}'.format(classname, option) in self.signals.keys(): payload = '{}.{}'.format(classname, option) if extra: extra['sender'] = payload payload = json.dumps(extra) self.signals['{}.{}'.format(classname, option)].send(str(payload)) def connect(self, classname, option, func): logger.debug('connect signal {}.{} with func: {}()'.format(classname, option, func.__name__)) if not '{}.{}'.format(classname, option) in self.signals.keys(): self.signals['{}.{}'.format(classname, option)] = self.signal.signal('{}.{}'.format(classname, option)) self.signals['{}.{}'.format(classname, option)].connect(func) def disconnect(self, classname, option, func): if '{}.{}'.format(classname, option) in self.signals.keys(): self.signals['{}.{}'.format(classname, option)].disconnect(func)
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()
class Logger(): def __init__(self): self.signals = Namespace() self.log = self.signals.signal("log") self.log.connect(self.logMessage) def writeLog(self, message): try: name = "shortstopEngine_" + time.strftime("%d%b%Y") + ".log" path = "data/logs/" with open(os.path.abspath(path + name), "a") as f: f.write(message) return True except Exception as e: return False def logMessage(self, sender=None, message="", type="", source=""): try: id = uuid.uuid4().int log = {"uuid": id, "type": type, "source": source, "message" : message} if self.writeLog(json.dumps(log) + ","): return True return False except Exception as e: print e return False
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 Execution(): 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) #Actions def post(self, action, **kwargs): if action == "start": self.start.send(self) elif action == "stop": self.stop.send(self) return {}
# -*- coding: utf-8 -*- """ rstblog.signals ~~~~~~~~~~~~~~~ Blinker signals for the modules and other hooks. :copyright: (c) 2013 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ from blinker import Namespace signals = Namespace() #: before the file is processed. The context is already prepared and if #: the given program was able to extract configuration from the file, it #: will already be stored on the context. before_file_processed = signals.signal('before_file_processed') #: after the file was prepared after_file_prepared = signals.signal('after_file_prepared') #: after the file was published (public: yes) after_file_published = signals.signal('after_file_published') #: fired the moment before a template is rendered with the context object #: that is about to be passed to the template. before_template_rendered = signals.signal('before_template_rendered') #: fired right before the build finished. This is the perfect place to
import os.path from functools import wraps from flask import Flask, current_app, Response, request, Blueprint from flask_sqlalchemy import SQLAlchemy from sqlalchemy.types import TypeDecorator from blinker import Namespace from sqlalchemy import LargeBinary, Text from jsonrpc.backend.flask import JSONRPCAPI import bitcoin.core.serialize from jsonrpcproxy import SmartDispatcher app = Flask(__name__) database = SQLAlchemy(app) SIGNALS = Namespace() WALLET_NOTIFY = SIGNALS.signal('WALLET_NOTIFY') BLOCK_NOTIFY = SIGNALS.signal('BLOCK_NOTIFY') # Copied from http://flask.pocoo.org/snippets/8/ def check_auth(username, password): """This function is called to check if a username / password combination is valid. """ return (username == current_app.config['rpcuser'] and password == current_app.config['rpcpassword']) def authenticate(): """Sends a 401 response that enables basic auth""" return Response( 'Could not verify your access level for that URL.\n'
# This file is part of Indico. # Copyright (C) 2002 - 2019 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from blinker import Namespace _signals = Namespace() items = _signals.signal('items', """ Expected to return one or more `SideMenuItem` to be added to the side menu. The *sender* is an id string identifying the target menu. """) sections = _signals.signal('sections', """ Expected to return one or more `SideMenuSection` objects to be added to the side menu. The *sender* is an id string identifying the target menu. """)
# Indico 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 3 of the # License, or (at your option) any later version. # # Indico 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 Indico; if not, see <http://www.gnu.org/licenses/>. from blinker import Namespace _signals = Namespace() clone = _signals.signal( "clone", """ Expected to return an instance of a ``EventCloner`` subclass implementing the cloning behavior. The *sender* is the event object. """, ) management_url = _signals.signal( "management-url", """ Expected to return a URL for the event management page of the plugin. This is used when someone who does not have event management access wants
# -*- coding: utf-8 -*- """ byceps.blueprints.shop.signals ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2015 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from blinker import Namespace shop_signals = Namespace() order_placed = shop_signals.signal('order-placed') order_canceled = shop_signals.signal('order-canceled') order_paid = shop_signals.signal('order-paid')
""" def __init__(self, name, doc=None): self.name = name self.__doc__ = doc def _fail(self, *args, **kwargs): raise RuntimeError('signalling support is unavailable ' 'because the blinker library is ' 'not installed.') send = lambda *a, **kw: None # noqa connect = disconnect = has_receivers_for = receivers_for = \ temporarily_connected_to = _fail del _fail # the namespace for code signals. If you are not mongoengine code, do # not put signals in here. Create your own namespace instead. _signals = Namespace() pre_init = _signals.signal('pre_init') post_init = _signals.signal('post_init') pre_save = _signals.signal('pre_save') pre_save_post_validation = _signals.signal('pre_save_post_validation') post_save = _signals.signal('post_save') pre_delete = _signals.signal('pre_delete') post_delete = _signals.signal('post_delete') pre_bulk_insert = _signals.signal('pre_bulk_insert') post_bulk_insert = _signals.signal('post_bulk_insert')
import time from blinker import Namespace from .histogram import Histogram, DEFAULT_SIZE, DEFAULT_ALPHA from .meter import Meter timer_signals = Namespace() call_too_long = timer_signals.signal("call_too_long") class Timer(object): def __init__(self, threshold = None, size=DEFAULT_SIZE, alpha=DEFAULT_ALPHA, clock = time): super(Timer, self).__init__() self.meter = Meter(clock=clock) self.hist = Histogram(clock=clock) self.threshold = threshold def get_count(self): return self.hist.get_count() def get_sum(self): return self.hist.get_sum() def get_max(self): return self.hist.get_max() def get_min(self): return self.hist.get_min() def get_mean(self): return self.hist.get_mean() def get_stddev(self):
#!/usr/bin/env python # -*- coding: utf-8 -*- signalsAvailable = False try: from blinker import Namespace signalsAvailable = True except ImportError: class Namespace(object): def signal(self, name, doc=None): return _DummySignal(name, doc) pass class _DummySignal(object): def __init__(self, name, doc=None): self.name = name self.doc = doc def _fail(self, *args, **options): raise RuntimeError('ooooo') send = lambda *a, **kw: None connect = disconnect = has_recivers_for = recivers_for = temporaily_connected_to = connected_to = _fail del _fail _signals = Namespace() requestContextTearingDown = _signals.signal('requestcontext-tearing-down') appContextTearingDown = _signals.signal('appcontext-tearing-down')
# modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (at your option) any later version. # # Indico 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 Indico; if not, see <http://www.gnu.org/licenses/>. from blinker import Namespace _signals = Namespace() moved = _signals.signal('moved', """ Called when a category is moved into another category. The `sender` is the category and the old parent category is passed in the `old_parent` kwarg. """) created = _signals.signal('created', """ Called when a new category is created. The `sender` is the new category. """) updated = _signals.signal('created', """ Called when a category is modified. The `sender` is the updated category. """)
# Indico 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 3 of the # License, or (at your option) any later version. # # Indico 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 Indico; if not, see <http://www.gnu.org/licenses/>. from blinker import Namespace _signals = Namespace() moved = _signals.signal('moved', """ Called when the parent of a category is changed. The `sender` is the category, the old/new parents are passed using the `old_parent` and `new_parent` kwargs. """) created = _signals.signal('created', """ Called when a new category is created. The `sender` is the new category, its parent category is passed in the `parent` kwarg. """) deleted = _signals.signal('deleted', """ Called when a category is deleted. The `sender` is the category. """)
# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Signals for frontend and API server requests.""" # Local modules from blinker import Namespace _signals = Namespace() # A release has been created or updated via the API. Sender is the app. # Arguments are (models.Build, models.Release). Signal is sent immediately # *after* the Release is committed to the DB. release_updated_via_api = _signals.signal('release-update') # A run has been created or updated via the API. Sender is the app. Arguments # are (models.Build, models.Release, models.Run). Signal is sent immediately # *after* the Run is committed to the DB. run_updated_via_api = _signals.signal('run-updated')
from flask.ext import login from flask.ext.oauthlib import client as oauth from google.appengine.api import users from google.appengine.ext import ndb import flask import unidecode import config import model import task import util from blinker import Namespace from main import app _signals = Namespace() ############################################################################### # Flask Login ############################################################################### login_manager = login.LoginManager() class AnonymousUser(login.AnonymousUserMixin): id = 0 admin = False name = 'Anonymous' user_db = None def key(self): return None
from blinker import Namespace from flask import current_app from flamaster.extensions import db from .models import Shelf __all__ = [ 'price_created', 'price_updated', 'price_deleted', 'order_created', 'order_paid', 'cart_created', 'carts_removed', 'cart_removed' ] logger = logging.getLogger(__name__) signals = Namespace() price_created = signals.signal('price_created') price_updated = signals.signal('price_updated') price_deleted = signals.signal('price_deleted') order_created = signals.signal('order-created') order_paid = signals.signal('order-paid') cart_created = signals.signal('cart-created') cart_removed = signals.signal('cart-removed') carts_removed = signals.signal('carts-removed') # @user_registered.connect # def create_customer_for_newcommer(sender, app): # sender['user'].customer = Customer()
# This file is part of Indico. # Copyright (C) 2002 - 2018 European Organization for Nuclear Research (CERN). # # Indico 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 3 of the # License, or (at your option) any later version. # # Indico 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 Indico; if not, see <http://www.gnu.org/licenses/>. from blinker import Namespace _signals = Namespace() get_definitions = _signals.signal('get-definitions', """ Expected to return a list of AgreementDefinition classes. """)
class Namespace(object): def signal(self, name, doc=None): return _DummySignal(name, doc) pass class _DummySignal(object): def __init__(self, name, doc=None): self.name = name self.doc = doc def _fail(self, *args, **options): raise RuntimeError('signalling support is unavailable ' 'because the blinker library is ' 'not installed.') send = lambda *a, **kw: None connect = disconnect = has_recivers_for = recivers_for = temporaily_connected_to = connected_to = _fail del _fail _signals = Namespace() templateRendered = _signals.signal('template-rendered') requestStarted = _signals.signal('request-started') requestFinished = _signals.signal('request-finished') requestContextTearingDown = _signals.signal('requestcontext-tearing-down') gotRequestException = _signals.signal('got-request-exception') appContextTearingDown = _signals.signal('appcontext-tearing-down')
# License, or (at your option) any later version. # # Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """Record module signals.""" from blinker import Namespace _signals = Namespace() record_viewed = _signals.signal('record-viewed') """ This signal is sent when a detailed view of record is displayed. Parameters: recid - id of record id_user - id of user or 0 for guest request - flask request object Example subscriber: .. code-block:: python def subscriber(sender, recid=0, id_user=0, request=None): ...
# # INSPIRE 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 3 of the License, or # (at your option) any later version. # # INSPIRE 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 INSPIRE. If not, see <http://www.gnu.org/licenses/>. # # In applying this license, CERN does not waive the privileges and immunities # granted to it by virtue of its status as an Intergovernmental Organization # or submit itself to any jurisdiction. """Record module signals.""" from __future__ import absolute_import, division, print_function from blinker import Namespace _signals = Namespace() after_record_enhanced = _signals.signal('after-record-enhanced') """Signal is sent before a record is indexed and after all the enchancers have populated it. """
# This file is part of Indico. # Copyright (C) 2002 - 2019 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from blinker import Namespace _signals = Namespace() cli = _signals.signal('cli', """ Expected to return one or more click commands/groups. If they use `indico.cli.core.cli_command` / `indico.cli.core.cli_group` they will be automatically executed within a plugin context and run within a Flask app context by default. """) shell_context = _signals.signal('shell-context', """ Called after adding stuff to the `indico shell` context. Receives the `add_to_context` and `add_to_context_multi` keyword args with functions which allow you to add custom items to the context. """) get_blueprints = _signals.signal('get-blueprints', """ Expected to return one or more IndicoPluginBlueprint-based blueprints which will be registered on the application. The Blueprint must be named either *PLUGINNAME* or *compat_PLUGINNAME*. """)
# -*- coding: utf-8 -*- from blinker import Namespace signals = Namespace() test = signals.signal('test')
# This file is part of Indico. # Copyright (C) 2002 - 2019 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from blinker import Namespace _signals = Namespace() print_badge_template = _signals.signal('print-badge-template', """ Called when printing a badge template. The registration form is passed in the `regform` kwarg. """)
class Namespace(object): def signal(self, name, doc=None): return _FakeSignal(name, doc) class _FakeSignal(object): """If blinker is unavailable, create a fake class with the same interface that allows sending of signals but will fail with an error on anything else. Instead of doing anything on send, it will just ignore the arguments and do nothing instead. """ def __init__(self, name, doc=None): self.name = name self.__doc__ = doc def _fail(self, *args, **kwargs): raise RuntimeError('signalling support is unavailable ' 'because the blinker library is ' 'not installed.') send = lambda *a, **kw: None connect = disconnect = has_receivers_for = receivers_for = \ temporarily_connected_to = connected_to = _fail del _fail # The namespace for code signals. If you are not oauthlib code, do # not put signals in here. Create your own namespace instead. _signals = Namespace() # Core signals. scope_changed = _signals.signal('scope-changed')
# License, or (at your option) any later version. # # Indico 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 Indico; if not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals from blinker import Namespace _signals = Namespace() folder_created = _signals.signal('folder-created', """ Called when a new attachment folder is created. The *sender* is the new `AttachmentFolder` object. The user who created the folder is passed in the `user` kwarg. This signal is never triggered for the internal default folder. """) folder_deleted = _signals.signal('folder-deleted', """ Called when a folder is deleted. The *sender* is the `AttachmentFolder` that was deleted. The user who deleted the folder is passed in the `user` kwarg. """)
# Indico 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 3 of the # License, or (at your option) any later version. # # Indico 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 Indico; if not, see <http://www.gnu.org/licenses/>. from blinker import Namespace _signals = Namespace() note_added = _signals.signal('note-added', """ Called when a note is added. The `sender` is the note. """) note_modified = _signals.signal('note-modified', """ Called when a note is modified. The `sender` is the note. """) note_deleted = _signals.signal('note-deleted', """ Called when a note is deleted. The `sender` is the note. """)
# coding: utf-8 from blinker import Namespace signals = Namespace() start_request = signals.signal("forecast.start_request", doc="Signal emitted by context manager before RequestHandler._execute()") end_request = signals.signal("forecast.end_request", doc="Signal emitted by context manager after RequestHandler._execute()") middleware_failure = signals.signal("forecast.middleware_failure", doc="Signal emitted when a middleware fails.")
# -*- coding: utf-8 -*- # # This file is part of Zenodo. # Copyright (C) 2015 CERN. # # Zenodo 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 3 of the License, or # (at your option) any later version. # # Zenodo 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 Zenodo. If not, see <http://www.gnu.org/licenses/>. # # In applying this licence, CERN does not waive the privileges and immunities # granted to it by virtue of its status as an Intergovernmental Organization # or submit itself to any jurisdiction. """Quota module signals.""" from blinker import Namespace _signals = Namespace() resource_usage_updated = _signals.signal('resource-usage-updated') """Signal sent when a resource usage metric has been updated."""