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_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()
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 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 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()
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)
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 {}
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 {}
# 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): ... """
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
# 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. """)
from threading import Thread from blinker import Namespace from flask import request, url_for from mongoengine import DoesNotExist from originblog.models import Tracker, PostStatistic from originblog.settings import BlogSettings from originblog.utils import submit_url_to_baidu # 创建信号 app_signals = Namespace() post_visited = app_signals.signal('post-visited') post_published = app_signals.signal('post-published') # 创建信号订阅者 @post_visited.connect def on_post_visited(sender, post, **kwargs): """更新文章统计数据与浏览记录 文章被浏览后,获取浏览者信息并更新文章统计数据 """ tracker = Tracker(post=post) # 获取请求来源ip与用户代理 proxy_list = request.headers.getlist('X-Forwarded-For') tracker.ip = proxy_list[0] if proxy_list else request.remote_addr tracker.user_agent = request.headers.get('User-Agent') tracker.save() # 获取该文章的统计数据,若不存在则创建并初始化
# This file is part of Indico. # Copyright (C) 2002 - 2021 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. The list of registration objects are passed in the `registrations` kwarg and it may be modified. ''')
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
class Namespace: def signal(self, name, doc=None): return _FakeSignal(name, doc) class _FakeSignal: """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')
# # 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. """Account module signals.""" from blinker import Namespace _signals = Namespace() profile_updated = _signals.signal('profile-updated') """Signal sent when a user profile is updated. Example subscriber .. code-block:: python def listener(sender, *args, **kwargs): pass from invenio_accounts.signals import profile_updated profile_updated.connect( listener, sender='' )
# # 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. """
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')
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() @price_created.connect def put_on_shelf(sender, price_option_id, quantity):
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')
# 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*. """)
# 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. """) deleted = _signals.signal('deleted', """ Called when a category is deleted. The `sender` is the category. """)
""" 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')
""" byceps.blueprints.news.signals ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2018 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from blinker import Namespace news_signals = Namespace() item_published = news_signals.signal('item-published')
# -*- coding: utf-8 -*- from blinker import Namespace signals = Namespace() test = signals.signal('test')
# # 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() app_created = _signals.signal('app-created', """ Called when the app has been created. The *sender* is the flask app. """) import_tasks = _signals.signal('import-tasks', """ Called when Celery needs to import all tasks. Use this signal if you have modules containing task registered using one of the Celery decorators but don't import them anywhere. The signal handler should only ``import`` these modules and do nothing else. """) after_process = _signals.signal('after-process', """ Called after an Indico request has been processed. """) before_retry = _signals.signal('before-retry', """ Called before an Indico request is being retried.
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')
from blinker import Namespace namespace = Namespace() #: Trigerred when an HTTP request is issued against the API on_api_call = namespace.signal('on-api-call')
# 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. """)
""" 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')
# -*- 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."""
# -*- 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')
# Namespace 的作用,为了防止多人开发的时候,信号名字冲突的问题 from blinker import Namespace from datetime import datetime from flask import request, g, template_rendered namespace = Namespace() login_signal = namespace.signal('login') # 定义登陆日志函数 def login_log(sender): # 记录用户名,login_log函数中传参 登录时间 IP地址 # 获取时间 now = datetime.now() # 获取ip地址,通过导入request获取 ip = request.remote_addr # 将这些信息组合到log_line中,进行日志的保存 log_line = "{username}*{now}*{ip}".format(username=g.username, now=now, ip=ip) # 打开文件写入信息,了解open函数的运用 with open('login_log.txt', 'a') as l: l.write(log_line + '\n') print('用户登录') l = open('login_log.txt', 'r') print(l.read()) login_signal.connect(login_log)
# This file is part of Indico. # Copyright (C) 2002 - 2021 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() booking_created = _signals.signal( 'booking-created', """ Executed after a booking has been successfully created. The *sender* is the new `Reservation` object. """) booking_state_changed = _signals.signal( 'booking-state-changed', """ Executed after a booking has been cancelled/rejected/accepted. The *sender* is the `Reservation` object. """) booking_deleted = _signals.signal( 'booking-deleted', """ Executed after a booking has been deleted. The *sender* is the `Reservation` object. """) booking_occurrence_state_changed = _signals.signal( 'booking-occurrence-state-changed', """ Executed after the state of a booking occurrence changed.
# 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() # legacy access_granted = _signals.signal( 'access-granted', """ Called when a principal in an `AccessController` is granted access. The `sender` is the `AccessController`; the `principal` is passed as a kwarg. """) access_revoked = _signals.signal( 'access-revoked', """ Called when a principal in an `AccessController` is revoked access. The `sender` is the `AccessController`; the `principal` is passed as a kwarg. """) modification_granted = _signals.signal( 'modification-granted', """ Called when a principal in an `AccessController` is granted modification access. The `sender` is the `AccessController`; the `principal` is passed as a kwarg. """)
# 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 to go to the event management area. He is then redirected to one of the URLs returned by plugins, i.e. it is not guaranteed that the user ends up on a specific plugin's management page. The signal should return None if the current user (available via ``session.user``) cannot access the management area. The *sender* is the event object. """,
# 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. """)
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)
# # 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. """) title_changed = _signals.signal('title-changed', """ Called when the title of a category is changed. The `sender` is the category, the old/new titles are passed in the `old` and `new` kwargs. """)
# 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. """)
# 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')
"""Signals for Invenio-MaDMP.""" from blinker import Namespace _signals = Namespace() record_changed = _signals.signal("record-changed") dataset_changed = _signals.signal("dataset-changed") dmp_changed = _signals.signal("dmp-changed")
# -*- coding: utf-8 -*- from blinker import Namespace __all__ = ( 'post_make_purchase_order', 'post_make_invoice', 'post_make_down_payment_invoice', 'post_update_invoicebase', 'post_register_invoice', 'post_cancel_invoice', 'post_client_changed_invoice_state', ) _signals = Namespace() post_make_purchase_order = _signals.signal('post_make_purchase_order') post_make_invoice = _signals.signal('post_make_invoice') post_make_down_payment_invoice = _signals.signal( 'post_make_down_payment_invoice') post_update_invoicebase = _signals.signal('post_update_invoicebase') post_register_invoice = _signals.signal('post_register_invoice') post_cancel_invoice = _signals.signal('post_cancel_invoice') post_client_changed_invoice_state = _signals.signal( 'post_client_changed_invoice_state')
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' 'You have to login with proper credentials', 401,
# 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')
# 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. """) folder_updated = _signals.signal('folder-updated', """ Called when a folder is updated. The *sender* is the `AttachmentFolder` that was updated. The user who updated the folder is passed in the `user` kwarg. """)
# -*- coding: utf-8 -*- # # Copyright (C) 2020 CESNET # # oarepo-s3 is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """S3 file storage support tasks for Invenio.""" from blinker import Namespace _signals = Namespace() before_upload_complete = _signals.signal('before_upload_complete') """ A signal being sent just before a multipart upload is completed :param record: the record the file is associated with :param file: FileInstance instance of file being completed :param parts: list of uploaded file parts :param multipart_config: dict containing the multipart upload session config """ after_upload_complete = _signals.signal('after_upload_complete') """ A notification called after the multipart upload is completed :param record: the record the file is associated with :param file: FileInstance instance of the uploaded file """ before_upload_abort = _signals.signal('before_upload_abort')
~~~~~~~~~~~~~~~ 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 #: write some more files to the build folder. before_build_finished = signals.signal('before_build_finished')
# This file is part of Indico. # Copyright (C) 2002 - 2021 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() app_created = _signals.signal( 'app-created', """ Called when the app has been created. The *sender* is the flask app. """) import_tasks = _signals.signal( 'import-tasks', """ Called when Celery needs to import all tasks. Use this signal if you have modules containing task registered using one of the Celery decorators but don't import them anywhere. The signal handler should only ``import`` these modules and do nothing else. """) after_process = _signals.signal( 'after-process', """ Called after an Indico request has been processed. This signal is executed for both RH classes and legacy JSON-RPC services. """) after_commit = _signals.signal(
# This file is part of SwarmSense IoT Platform # Copyright (c) 2018, Baseapp Systems And Softwares Private Limited # Authors: Gopal Lal # # License: www.baseapp.com/swarmsense-whitelabel-iot-platoform from blinker import Namespace _signals = Namespace() sensor_pre_create = _signals.signal('sensor-before-create', """ Called before a sensor is created. """) sensor_created = _signals.signal('sensor_created', """ Called when a sensor is created """)
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)
# This file is part of Indico. # Copyright (C) 2002 - 2021 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() process_args = _signals.signal( 'process-args', """ Executed right after `_process_args` of an `RH` instance has been called. The *sender* is the RH class, the current instance is passed in *rh*. The return value of `_process_args` (usually ``None``) is available in *result*. """) check_access = _signals.signal( 'check-access', """ Executed right after `_check_access` of an `RH` instance has been called unless the access check raised an exception. The *sender* is the RH class, the current instance is passed in *rh*. """) before_process = _signals.signal( 'before-process', """ Executed right before `_process` of an `RH` instance is called. The *sender* is the RH class, the current instance is passed in *rh*. If a signal handler returns a value, the original `_process` method
def admin_required(f): decorator_order_guard(f, 'auth.admin_required') @functools.wraps(f) def decorated_function(*args, **kws): if is_logged_in() and current_user_db().admin: return f(*args, **kws) if not is_logged_in() and flask.request.path.startswith('/_s/'): return flask.abort(401) if not is_logged_in(): return flask.redirect(flask.url_for('signin', next=flask.request.url)) return flask.abort(403) return decorated_function permission_registered = _signals.signal('permission-registered') def permission_required(permission=None, methods=None): def permission_decorator(f): decorator_order_guard(f, 'auth.permission_required') # default to decorated function name as permission perm = permission or f.func_name meths = [m.upper() for m in methods] if methods else None permission_registered.send(f, permission=perm) @functools.wraps(f) def decorated_function(*args, **kws): if meths and flask.request.method.upper() not in meths:
# 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.")
# 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() app_created = _signals.signal( 'app-created', """ Called when the app has been created. The *sender* is the flask app. """) after_process = _signals.signal( 'after-process', """ Called after an Indico request has been processed. """) before_retry = _signals.signal( 'before-retry', """ Called before an Indico request is being retried. """) indico_help = _signals.signal( 'indico-help', """ Expected to return a dict containing entries for the *Indico help* page::