Beispiel #1
0
    def from_uri(self, cls, name, host, *args, **kwargs):
        '''Construct a ``MqttProxy`` from a MQTT broker hostname.

        Parameters
        ----------
        cls : class
            Class type from which to extract properties and methods to expose.
        name : str
            Name of MQTT root topic to subscribe to, e.g., ``dropbot`` will
            subscribe to ``/dropbot/+/#``.
        host : str
            Hostname to which MQTT client should connect, e.g., ``localhost``.
        *args, **kwargs
            Additional parameters passed to MQTT ``Client`` constructor.

        Returns
        -------
        MqttProxy
            Proxy to object exposed through MQTT.
        '''
        async_ = kwargs.pop('async_', False)
        signals = blinker.Namespace()
        client = get_client(name, signals, *args, **kwargs)
        client.connect_async(host)
        client.loop_start()
        client.signals = signals
        client.connected.wait()
        proxy = self(cls, client, async_=async_)
        super(MqttProxy, proxy).__setattr__('_owns_client', True)
        return proxy
Beispiel #2
0
 def __init__(self, app=None):
     """Init method.
     """
     self.app = app
     if app is not None:
         self.init_app(app)
     self.namespace = blinker.Namespace()
Beispiel #3
0
class Proposal(object):
    """Class storing proposal signals."""
    signals = blinker.Namespace()
    proposal_applied = signals.signal(
        "Proposal applied",
        """
        :instance: The object that modified after applying of proposal.
      """,
    )
Beispiel #4
0
class Import(object):
    """Class storing import signals."""
    signals = blinker.Namespace()
    mapping_created = signals.signal(
        "Mapping created",
        """
        :instance: The object that mapped via import.
      """,
    )
Beispiel #5
0
    def __init__(self, address='192.168.42.1', port=7878):
        self.address = address
        self.port = port

        self._decoder = json.JSONDecoder()
        self._buffer = ""

        ns = blinker.Namespace()
        self.raw_message = ns.signal('raw-message')
        self.event = ns.signal('event')
Beispiel #6
0
 def __init__(self, url, watchdog=None, loop=None):
     self._resp_queue = asyncio.Queue(loop=loop)
     self.loop = loop
     assert url.startswith('ws://') or url.startswith('wss://')
     self.url = url
     self._websocket = None
     self._ws_recv_handler_task = None
     self._watchdog_task = None
     self.watchdog_time = watchdog
     self._signal_ns = blinker.Namespace()
def test_singletons():
    ns = blinker.Namespace()
    assert not ns
    s1 = ns.signal('abc')
    assert s1 is ns.signal('abc')
    assert s1 is not ns.signal('def')
    assert 'abc' in ns
    # weak by default, already out of scope
    assert 'def' not in ns
    del s1
    assert 'abc' not in ns
Beispiel #8
0
class EventHandler(logging.Handler):
    signals = blinker.Namespace()
    on_log_emit = signals.signal('logrecord',
                                 doc="""\
    Sent when a log record was emitted.

    :keyword :class:`logging.LogRecord` record: the LogRecord
    """)

    def emit(self, record):
        self.on_log_emit.send(record=record)
Beispiel #9
0
def test_namespace():
    ns = blinker.Namespace()
    assert not ns
    s1 = ns.signal('abc')
    assert s1 is ns.signal('abc')
    assert s1 is not ns.signal('def')
    assert 'abc' in ns

    del s1
    collect_acyclic_refs()

    assert 'def' in ns
    assert 'abc' in ns
Beispiel #10
0
 def __init__(self):
     if not self._initialized:
         self._configs = {}
         self._sub_keys = {}
         self._monitors = {}
         self._monitor_interval = 60
         self._initialized = True
         self._namespace = self.__class__.DEFAULT_NAMESPACE
         self._signal_namespace = blinker.Namespace()
         self._update_signals = {}
         self._update_signals[self.__class__.DEFAULT_NAMESPACE] = \
             self._signal_namespace.signal(
                 self.__class__._update_signal_name(
                     self.__class__.DEFAULT_NAMESPACE))
Beispiel #11
0
class EventHandler(logging.Handler):
    """ Subclass of :py:class:`logging.Handler` that emits a
        :py:class:`blinker.base.Signal` whenever a new record is emitted.
    """
    signals = blinker.Namespace()
    on_log_emit = signals.signal('logrecord',
                                 doc="""\
    Sent when a log record was emitted.

    :keyword :class:`logging.LogRecord` record: the LogRecord
    """)

    def emit(self, record):
        self.on_log_emit.send(record=record)
Beispiel #12
0
def monitor():
    signals = blinker.Namespace()

    @asyncio.coroutine
    def dropbot_monitor(*args):
        try:
            yield asyncio.From(db.monitor.monitor(*args))
        except asyncio.CancelledError:
            _L().info('Stopped DropBot monitor.')

    monitor_task = cancellable(dropbot_monitor)
    thread = threading.Thread(target=monitor_task, args=(signals, ))
    thread.daemon = True
    thread.start()
    return monitor_task
Beispiel #13
0
def main(signals=None, resolution=(1280, 720), device_id=0):
    '''
    Launch chip webcam monitor thread and view window.
    '''
    if signals is None:
        signals = blinker.Namespace()

    thread = threading.Thread(target=chip_video_process,
                              args=(signals, resolution[0], resolution[1],
                                    device_id))
    thread.start()

    loop = asyncio.get_event_loop()

    # Launch window to view chip video.
    loop.run_until_complete(show_chip(signals))

    # Close background thread.
    signals.signal('exit-request').send('main')
Beispiel #14
0
def execute_step(plugin_kwargs):
    '''
    .. versionadded:: 2.32

    XXX Coroutine XXX

    Execute a single protocol step.

    Parameters
    ----------
    plugin_kwargs : dict
        Plugin keyword arguments, indexed by plugin name.

    Returns
    -------
    list
        Return values from plugin ``on_step_run()`` coroutines.
    '''
    # Take snapshot of arguments for current step.
    plugin_kwargs = copy.deepcopy(plugin_kwargs)

    signals = blinker.Namespace()

    @asyncio.coroutine
    def notify_signals_connected():
        yield asyncio.From(asyncio.sleep(0))
        signals.signal('signals-connected').send(None)

    loop = asyncio.get_event_loop()
    # Get list of coroutine futures by emitting `on_step_run()`.
    plugin_step_tasks = emit_signal("on_step_run",
                                    args=[plugin_kwargs, signals])
    future = asyncio.wait(plugin_step_tasks.values())

    loop.create_task(notify_signals_connected())
    result = yield asyncio.From(future)
    raise asyncio.Return(result)
Beispiel #15
0
 def __init__(self):
     self.name = self.plugin_name
     self.signals = blinker.Namespace()
     self.task = None
     self._most_recent_message = {}
Beispiel #16
0
def main():
    def show():
        settings.setWindowState(settings.windowState() &
                                ~QtCore.Qt.WindowMinimized |
                                QtCore.Qt.WindowActive)
        settings.show()

    def __icon_activated(reason):
        if reason in (QtWidgets.QSystemTrayIcon.DoubleClick, ):
            if settings.isVisible():
                settings.hide()
            else:
                show()


    signals = blinker.Namespace()
    settings = DropBotSettings(signals)

    def get_icon(filename):
        icon_blob = pkgutil.get_data('dropbot_monitor.bin', filename)
        qpixmap = QtGui.QPixmap()
        qpixmap.loadFromData(icon_blob)
        return QtGui.QIcon(qpixmap)

    # Colour icon for app window.
    window_icon = get_icon('sci-bots.ico')
    settings.setWindowIcon(window_icon)
    settings.setWindowTitle('DropBot status')

    # White logo for system tray.
    tray_icon = get_icon('images/sci-bots-white-logo-disconnected.ico')
    tray = QtWidgets.QSystemTrayIcon(settings)
    tray.setIcon(tray_icon)

    tray.activated.connect(__icon_activated)

    # Context Menu
    ctmenu = QtWidgets.QMenu()
    actionshow = ctmenu.addAction("Show/Hide")
    actionshow.triggered.connect(lambda: settings.hide()
                                 if settings.isVisible() else show())
    actionquit = ctmenu.addAction("Quit")
    actionquit.triggered.connect(settings.close)

    @asyncio.coroutine
    def on_connected(sender, **message):
        def ui_code():
            tray.showMessage('DropBot connected', 'Connected to DropBot on '
                             'port %s' % message['dropbot'].port,
                             tray.MessageIcon.Information)
            tray.setToolTip('DropBot connected')

        invoker.invoke(ui_code)

    settings.monitor_task.signals.signal('connected')\
        .connect(on_connected, weak=False)

    @asyncio.coroutine
    def on_disconnected(sender, **message):
        tray.showMessage('DropBot disconnected', 'Disconnected from DropBot.',
                         QtWidgets.QSystemTrayIcon.MessageIcon.Warning)
        tray_icon = get_icon('images/sci-bots-white-logo-disconnected.ico')
        tray.setIcon(tray_icon)
        tray.setToolTip('No DropBot connection')

    settings.monitor_task.signals.signal('disconnected')\
        .connect(on_disconnected, weak=False)

    @asyncio.coroutine
    def on_chip_inserted(sender, **message):
        tray_icon = get_icon('images/sci-bots-white-logo-chip-inserted.ico')
        port = settings.monitor_task.dropbot.port

        def ui_code():
            tray.setIcon(tray_icon)
            tray.setToolTip('DropBot connected (%s) - chip inserted' % port)

        invoker.invoke(ui_code)

    settings.monitor_task.signals.signal('chip-inserted')\
        .connect(on_chip_inserted, weak=False)

    @asyncio.coroutine
    def on_chip_removed(sender, **message):
        tray_icon = get_icon('images/sci-bots-white-logo-chip-removed.ico')
        tray.setIcon(tray_icon)
        port = settings.monitor_task.dropbot.port
        tray.setToolTip('DropBot connected (%s) - no chip inserted' % port)

    settings.monitor_task.signals.signal('chip-removed')\
        .connect(on_chip_removed, weak=False)

    tray.setContextMenu(ctmenu)
    tray.show()
Beispiel #17
0
import blinker
from flask import request, current_app, g
from flask.signals import got_request_exception, request_finished
from werkzeug.exceptions import ClientDisconnected

from raven.conf import setup_logging
from raven.base import Client
from raven.middleware import Sentry as SentryMiddleware
from raven.handlers.logging import SentryHandler
from raven.utils.compat import urlparse
from raven.utils.encoding import to_unicode
from raven.utils.wsgi import get_headers, get_environ
from raven.utils.conf import convert_options

raven_signals = blinker.Namespace()
logging_configured = raven_signals.signal('logging_configured')


def make_client(client_cls, app, dsn=None):
    return client_cls(**convert_options(
        app.config,
        defaults={
            'dsn':
            dsn,
            'include_paths': (set(app.config.get('SENTRY_INCLUDE_PATHS', []))
                              | set([app.import_name])),
            # support legacy RAVEN_IGNORE_EXCEPTIONS
            'ignore_exceptions':
            app.config.get('RAVEN_IGNORE_EXCEPTIONS', []),
            'extra': {
Beispiel #18
0
 def setUp(self):
     self.signals = blinker.Namespace()
     self.signal_ = self.signals.signal('signal-')
     self.mock_listener = mock.MagicMock()
Beispiel #19
0
def monitor(client=None):
    if client is None:
        client = Client()
        client.on_connect = on_connect
        client.connect_async('localhost')
        client.loop_start()
        client_created = True
    else:
        client_created = False

    signals = blinker.Namespace()

    @asyncio.coroutine
    def _on_dropbot_connected(sender, **message):
        monitor_task.connected.clear()
        dropbot_ = message['dropbot']
        monitor_task.dropbot = dropbot_
        client.on_message = ft.partial(on_message, 'dropbot', proxy=dropbot_)

        device_id = str(dropbot_.uuid)
        connect_topic = '/dropbot/%(uuid)s/signal' % {'uuid': device_id}
        send_topic = '/dropbot/%(uuid)s/send-signal' % {'uuid': device_id}

        # Bind blinker signals namespace to corresponding MQTT topics.
        bind(signals=signals,
             paho_client=client,
             connect_topic=connect_topic,
             send_topic=send_topic)

        dropbot_.update_state(event_mask=EVENT_CHANNELS_UPDATED
                              | EVENT_SHORTS_DETECTED | EVENT_ENABLE)

        client.publish('/dropbot/%(uuid)s/properties' % {'uuid': device_id},
                       payload=dropbot_.properties.to_json(),
                       qos=1,
                       retain=True)

        prefix = '/dropbot/' + device_id
        monitor_task.device_id = device_id
        monitor_task.property = ft.partial(wait_for_result, client, 'property',
                                           prefix)
        monitor_task.call = ft.partial(wait_for_result, client, 'call', prefix)
        monitor_task.connected.set()

    @asyncio.coroutine
    def _on_dropbot_disconnected(sender, **message):
        monitor_task.connected.clear()
        monitor_task.dropbot = None
        unbind(signals)
        client.publish('/dropbot/%(uuid)s/properties' %
                       {'uuid': monitor_task.device_id},
                       payload=None,
                       qos=1,
                       retain=True)

    signals.signal('connected').connect(_on_dropbot_connected, weak=False)
    signals.signal('disconnected').connect(_on_dropbot_disconnected,
                                           weak=False)

    def stop():
        if getattr(monitor_task, 'dropbot', None) is not None:
            monitor_task.dropbot.set_state_of_channels(pd.Series(),
                                                       append=False)
            monitor_task.dropbot.update_state(capacitance_update_interval_ms=0,
                                              hv_output_enabled=False)
        try:
            unbind(monitor_task.signals)
        except RuntimeError as e:
            _L().warning('%s', e)
        monitor_task.cancel()
        if client_created:
            client.loop_stop()
            client.disconnect()

    monitor_task = cancellable(catch_cancel(db.monitor.monitor))
    monitor_task.connected = threading.Event()
    thread = threading.Thread(target=monitor_task, args=(signals, ))
    thread.daemon = True
    thread.start()
    monitor_task.signals = signals
    monitor_task.stop = stop
    monitor_task.close = stop
    return monitor_task
def index():
    if request.method == 'POST':
        g.name = request.form['params']
        return redirect('/')
    else:
        return """
                <a>首页<a>
                <form action='/' method='post'>
                    <input type='text' name='params' value=''><br>
                    <input type='submit' value='提交'>
                <form>
                """


# 创建信号
signal = blinker.Namespace()
send_signal = signal.signal("登录信息使用场景")


# 监听信号
def loginLog(val):
    username = g.name
    now = datetime.datetime.now()
    ipAddress = request.remote_addr
    LogData = f"用户:{username},通过ip为{ipAddress}的地址在{now}时间点登录服务"
    with open('LoginLog.txt', mode='a') as f:
        f.write(LogData + "\n")
        f.close()


send_signal.connect(loginLog)
Beispiel #21
0
    pass


@template_rendered.connect_via(app)
@callback_output_decorator
def template_rendered_callback(sender, **extra):
    pass


@message_flashed.connect_via(app)
@callback_output_decorator
def message_flashed_callback(sender, **extra):
    pass


custom_signal = blinker.Namespace()
index_called = custom_signal.signal("index_called")


@index_called.connect_via(app)
@callback_output_decorator
def index_called_custom_callback(sender, **extra):
    pass


#####################################END##########################################


@app.route("/")
def index():
    print("Handling Request")
Beispiel #22
0
def execute_steps(steps, signals=None):
    '''
    .. versionadded:: 2.32

    Parameters
    ----------
    steps : list[dict]
        List of plugin keyword argument dictionaries.
    signals : blinker.Namespace, optional
        Signals namespace where signals are sent through.

    Signals
    -------
    step-started
        Parameters::
        - ``i``: step index
        - ``plugin_kwargs``: plugin keyword arguments
        - ``steps_count``: total number of steps
    step-completed
        Parameters::
        - ``i``: step index
        - ``plugin_kwargs``: plugin keyword arguments
        - ``steps_count``: total number of steps
        - ``result``: list of plugin step return values
    '''
    if signals is None:
        signals = blinker.Namespace()

    for i, step_i in enumerate(steps):
        # Send notification that step has completed.
        responses = signals.signal('step-started')\
            .send('execute_steps', i=i, plugin_kwargs=step_i,
                  steps_count=len(steps))
        yield asyncio.From(asyncio.gather(*(r[1] for r in responses)))
        # XXX Execute `on_step_run` coroutines in background thread
        # event-loop.
        try:
            done, pending = yield asyncio.From(execute_step(step_i))

            exceptions = []

            for d in done:
                try:
                    d.result()
                except Exception as exception:
                    exceptions.append(exception)
                    _L().debug('Error: %s', exception, exc_info=True)

            if exceptions:
                use_markup = False
                monospace_format = '<tt>%s</tt>' if use_markup else '%s'

                if len(exceptions) == 1:
                    message = (' ' + monospace_format % exceptions[0])
                elif exceptions:
                    message = ('\n%s' % '\n'.join(' - ' + monospace_format % e
                                                  for e in exceptions))
                raise RuntimeError('Error executing step:%s' % message)
        except asyncio.CancelledError:
            _L().debug('Cancelling protocol.', exc_info=True)
            raise
        except Exception as exception:
            _L().debug('Error executing step: `%s`', exception, exc_info=True)
            raise
        else:
            # All plugins have completed the step.
            # Send notification that step has completed.
            responses = signals.signal('step-completed')\
                .send('execute_steps', i=i, plugin_kwargs=step_i,
                      result=[r.result() for r in done],
                      steps_count=len(steps))
            yield asyncio.From(asyncio.gather(*(r[1] for r in responses)))
Beispiel #23
0
def connect(svg_source=None):
    '''
    .. versionchanged:: 0.9.0
        Attach ``electrodes_graph``, ``channels_graph``, and ``chip_info``
        attributes to ``proxy`` to expose adjacent electrode ids and channel
        numbers, along with detailed chip design info parsed from SVG file.
    .. versionchanged:: 0.9.0
        Attach ``proxy`` attribute to monitor task to DropBot handle.
    .. versionchanged:: 0.9.0
        Attach ``signals`` attribute to monitor task to expose signals
        namespace to calling code.  Dump ``shorts-detected`` messages to
        ``stdout``.
    '''
    signals = blinker.Namespace()

    connected = threading.Event()
    proxy = None

    @asyncio.coroutine
    def dump(*args, **kwargs):
        print('args=`%s`, kwargs=`%s`' % (args, kwargs))

    @asyncio.coroutine
    def on_connected(*args, **kwargs):
        proxy = kwargs['dropbot']
        proxy.chip_info = chip_info
        proxy.electrodes_graph = electrodes_graph
        proxy.channels_graph = channels_graph
        proxy.turn_off_all_channels()
        proxy.stop_switching_matrix()
        proxy.neighbours = channel_neighbours
        proxy.electrode_neighbours = neighbours

        proxy.enable_events()

        proxy.update_state(hv_output_enabled=True,
                           hv_output_selected=True,
                           voltage=100,
                           frequency=10e3)

        # Disable channels in contact with copper tape.
        disabled_channels_mask_i = proxy.disabled_channels_mask
        # Disable channels with no neighbours defined.
        neighbour_counts = channel_neighbours.groupby(level='channel').count()
        disabled_channels_mask_i[neighbour_counts.loc[
            neighbour_counts < 1].index] = 1
        proxy.disabled_channels_mask = disabled_channels_mask_i

        connected.proxy = proxy
        connected.set()

    @asyncio.coroutine
    def on_disconnected(*args, **kwargs):
        raise IOError('Lost DropBot connection.')

    @asyncio.coroutine
    def ignore(*args, **kwargs):
        raise asyncio.Return('ignore')

    def _connect(*args):
        signals.clear()
        signals.signal('chip-inserted').connect(dump, weak=False)
        signals.signal('connected').connect(on_connected, weak=False)
        signals.signal('disconnected').connect(on_disconnected, weak=False)
        signals.signal('shorts-detected').connect(dump, weak=False)
        signals.signal('version-mismatch').connect(ignore, weak=False)

        monitor_task = cancellable(db.monitor.monitor)
        thread = threading.Thread(target=monitor_task, args=(signals, ))
        thread.daemon = True
        thread.start()

        while not connected.wait(1):
            pass

        monitor_task.proxy = connected.proxy
        return monitor_task

    def close(*args):
        connected.clear()
        proxy.stop_switching_matrix()
        proxy.update_state(drops_update_interval_ms=int(0))
        time.sleep(1.)
        monitor_task.cancel()

    chip_info, electrodes_graph, neighbours = load_device(svg_source)

    # Convert `neighbours` to use channel numbers instead of electrode ids.
    electrode_channels = pd.Series(
        {e['id']: e['channels'][0]
         for e in chip_info['electrodes']})
    index = pd.MultiIndex\
        .from_arrays([electrode_channels[neighbours.index
                                         .get_level_values('id')],
                      neighbours.index.get_level_values('direction')],
                     names=('channel', 'direction'))
    channel_neighbours = pd.Series(electrode_channels[neighbours].values,
                                   index=index)
    channels_graph = nx.Graph([
        tuple(map(electrode_channels.get, e)) for e in electrodes_graph.edges
    ])

    monitor_task = _connect()
    monitor_task.signals = signals
    return monitor_task
Beispiel #24
0
import blinker
from flask import Flask

from alerta.exceptions import ApiError, RejectException

hook_signals = blinker.Namespace()

pre_receive_hook = hook_signals.signal('pre-receive')
post_receive_hook = hook_signals.signal('post-receive')
status_change_hook = hook_signals.signal('status-change')
take_action_hook = hook_signals.signal('take-action')


class HookTrigger:

    def __init__(self, app: Flask=None) -> None:
        self.app = app
        if app is not None:
            self.init_app(app)

    def init_app(self, app: Flask) -> None:
        pre_receive_hook.connect(self.process_pre_receive)
        post_receive_hook.connect(self.process_post_receive)
        status_change_hook.connect(self.process_status_change)
        take_action_hook.connect(self.process_take_action)

    def process_pre_receive(self, alert):
        # not used
        pass

    def process_post_receive(self, alert):
Beispiel #25
0
import copy
import blinker
import logging
import inspect
import datetime
import functools
import itsdangerous
import flask_cloudy
from passlib.hash import bcrypt
from . import (app_context, ext, g, config)
from flask import (send_file, session)

# ------------------------------------------------------------------------------
# signal

__signals_namespace = blinker.Namespace()


def signal(fn):
    """
    @signal
    A decorator to mark a function as a signal emitter
    It will turn the function into a decorator that can be used to
    receive signal with: $fn_name.pre, $fn_name.post
    *pre will execute before running the function
    *post will run after running the function

    # What are signals
    Signals help you decouple applications by sending notifications 
    when actions occur elsewhere in the application. 
    In short, signals allow certain senders to notify subscribers that 
Beispiel #26
0
import json
import os
import uuid
from datetime import datetime
from typing import Any, List

import blinker
import requests
from flask import Flask, g

from alerta.utils.format import CustomJSONEncoder

audit_signals = blinker.Namespace()

admin_audit_trail = audit_signals.signal('admin')
write_audit_trail = audit_signals.signal('write')
read_audit_trail = audit_signals.signal('read')  # not used
auth_audit_trail = audit_signals.signal('auth')


class AuditTrail:
    def __init__(self, app: Flask = None) -> None:
        self.app = app
        if app is not None:
            self.init_app(app)

    def init_app(self, app: Flask) -> None:
        self.audit_url = app.config['AUDIT_URL']

        if 'admin' in app.config['AUDIT_TRAIL']:
            if app.config['AUDIT_LOG']:
Beispiel #27
0
import blinker

coprs_signals = blinker.Namespace()

build_finished = coprs_signals.signal("build-finished")
copr_created = coprs_signals.signal("copr-created")
Beispiel #28
0
from werkzeug.utils import secure_filename
from datetime import datetime
import tempfile
from path import path
from definitions import (EDITABLE_METADATA, METADATA, STAGES, STAGE_ORDER,
                         INITIAL_STAGE, COUNTRIES_MC, COUNTRIES_CC, COUNTRIES,
                         THEMES, PROJECTIONS, RESOLUTIONS, EXTENTS, ALL_ROLES,
                         UNS_FIELD_DEFS)
import notification
import auth
from warehouse import get_warehouse, _current_user
from utils import format_datetime, exclusive_lock

parcel_views = flask.Blueprint('parcel', __name__)

parcel_signals = blinker.Namespace()
parcel_created = parcel_signals.signal('parcel-created')
file_uploaded = parcel_signals.signal('file-uploaded')
parcel_finalized = parcel_signals.signal('parcel-finalized')
parcel_deleted = parcel_signals.signal('parcel-deleted')
parcel_file_deleted = parcel_signals.signal('parcel-file-deleted')


@parcel_views.route('/')
def index():
    return flask.render_template('index.html')


def get_filter_arguments():
    return {k: v for k, v in flask.request.args.items() if k in METADATA and v}
Beispiel #29
0
class Restful(object):
    """Class storing REST-related signals."""

    signals = blinker.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_before_commit = signals.signal(
        "Model PUT - before",
        """
      Indicates that a model object update was received via PUT and has been
      precessed but not yet stored 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
        :initial_state: A named tuple of initial values of an object before
          applying any change.
      """,
    )
    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
        :initial_state: A named tuple of initial values of an object before
          applying any change.
      """,
    )
    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
      """,
    )
Beispiel #30
0
"""Blinker signals used for sending end receiving events"""

from __future__ import absolute_import

import blinker

namespace = blinker.Namespace()

#: The event signal is sent when Supermann receives an event from Supervisor
#: Receivers should take `sender` (the Supermann instance) and `event` as args
event = namespace.signal('supervisor:event')

#: The process signal is sent for each Supervisor child process when an event
#: is received. It is sent a ``psutil.Process`` object for that process, and
#: the data from the Supervisor ``getProcessInfo`` function.
process = namespace.signal('supervisor:process')