Ejemplo n.º 1
0
class PipelineSignals:
    __namespace__ = Namespace()
    completed = __namespace__.signal("completed")

    @classmethod
    def on_complete(cls, schedule, success: bool):
        cls.completed.send(schedule, success=success)
Ejemplo n.º 2
0
class EventManager:
    def __init__(self):
        self.space = Namespace()
        self.events = {}

    def trigger(self, event_name, **params):
        if self.events.get(event_name) is None:
            return
        self.events[event_name].send(current_app._get_current_object(),
                                     **params)

    def subscribe(self, event_name):
        if self.events.get(event_name) is None:
            self.events[event_name] = self.space.signal(event_name)
        return self.events[event_name].connect
Ejemplo n.º 3
0
 def __init__(self):
     self._signals = Namespace()
     
     #General Commands
     self.execute_commands = self._signals.signal("execute_commands")
     
     #Post Signals
     self.new_post = self._signals.signal("post-new")
     self.save_post = self._signals.signal("post-save")
     self.delete_post = self._signals.signal("post-delete")
     
     #Thread Signals
     self.prune_thread = self._signals.signal("prune")
     
     #Image Signals
     self.new_image = self._signals.signal("image-new")
     self.delete_image = self._signals.signal("image-delete")
     
     #Ban Signals
     self.new_ban = self._signals.signal("ban-new")
Ejemplo n.º 4
0
""" This file creates event notification signals for Flask-User.
    Signals are based on Flask.signals which are based on the blinker signals.
"""

# Copyright (c) 2013 by Ling Thio
# Author: Ling Thio ([email protected])
# License: Simplified BSD License, see LICENSE.txt for more details.


from flask.signals import Namespace

_signals = Namespace()                              # Place Flask-User signals in our own namespace

# *******************
# ** Flask Signals **
# *******************
# Flask signals are based on blinker. Neither Flask nor Flask-User installs blinker
# If you plan to use signals, please install blinker with 'pip install blinker'
# See http://flask.pocoo.org/docs/signals/

# Sent when a user changed their password
user_changed_password = _signals.signal('user.user_changed_password')

# Sent when a user changed their username
user_changed_username = _signals.signal('user.user_changed_username')

# Sent when a user confirmed their email
user_confirmed_email = _signals.signal('user.user_confirmed_email')

# Sent when a user submitted a password reset request
user_forgot_password = _signals.signal('user.forgot_password')
Ejemplo n.º 5
0
from werkzeug.local import LocalProxy

from flask import current_app
from flask.signals import Namespace

from kazoo.client import KazooClient

__all__ = ('Kazoo', )

__version__ = '0.1'

_signals = Namespace()

connection_state_changed = _signals.signal('state-change')


def _get_client():
    kazoo_client = current_app._get_current_object().extensions['kazoo']['client']
    return kazoo_client

kazoo_client = LocalProxy(_get_client)


class Kazoo(object):
    """Kazoo Client support for Flask."""

    def __init__(self, app=None):
        """
        If app argument provided then initialize cqlengine connection using
        application config values.
Ejemplo n.º 6
0
from flask import redirect, session
from flask import request as flask_req
from flask.signals import Namespace
from flask import _app_ctx_stack
from .._client import UserInfoMixin
from .._client import RemoteApp as _RemoteApp

__all__ = ['token_update', 'RemoteApp']

_signal = Namespace()
#: signal when token is updated
token_update = _signal.signal('token_update')


class RemoteApp(_RemoteApp, UserInfoMixin):
    """Flask integrated RemoteApp of :class:`~authlib.client.OAuthClient`.
    It has built-in hooks for OAuthClient. The only required configuration
    is token model.
    """
    def __init__(self, name, fetch_token=None, **kwargs):
        fetch_request_token = kwargs.pop('fetch_request_token', None)
        save_request_token = kwargs.pop('save_request_token', None)
        super(RemoteApp, self).__init__(name, fetch_token, **kwargs)

        self._fetch_request_token = fetch_request_token
        self._save_request_token = save_request_token

    def _send_token_update(self, token, refresh_token=None, access_token=None):
        self.token = token
        super(RemoteApp, self)._send_token_update(token, refresh_token,
                                                  access_token)
Ejemplo n.º 7
0
Archivo: signals.py Proyecto: nZac/keg
from __future__ import absolute_import
from __future__ import unicode_literals

from flask.signals import Namespace

_signals = Namespace()

# Call when application initializations is completed.
# Sender will be the application instance.
app_ready = _signals.signal('app-ready')

config_ready = _signals.signal('config-ready')
testing_run_start = _signals.signal('testing-run-start')

db_clear_pre = _signals.signal('db-clear-pre')
db_clear_post = _signals.signal('db-clear-post')
db_init_pre = _signals.signal('db-init-pre')
db_init_post = _signals.signal('db-init-post')
Ejemplo n.º 8
0
# coding: utf-8

import datetime
from functools import partial
from flask.signals import Namespace
from flask.ext.sqlalchemy import SQLAlchemy, BaseQuery
from flask.ext.principal import Need, UserNeed
from flask.ext.cache import Cache

__all__ = [
    'db', 'cache', 'YuanQuery', 'SessionMixin',
    'model_created', 'model_updated', 'model_deleted',
    'create_user_needs', 'TeamNeed',
]

signals = Namespace()
model_created = signals.signal('model-created')
model_updated = signals.signal('model-updated')
model_deleted = signals.signal('model-deleted')

db = SQLAlchemy()
cache = Cache()
TeamNeed = partial(Need, 'team')


def create_user_needs(owner_id, permission):
    rv = db.session.execute(
        'SELECT account_id FROM team_member '
        'JOIN team ON team_member.team_id=team.id '
        'AND team.owner_id=:id AND team._permission>:permission '
        'GROUP BY account_id', {'id': owner_id, 'permission': permission})
Ejemplo n.º 9
0
FEATURE_FLAGS_CONFIG = u'FEATURE_FLAGS'

EXTENSION_NAME = "FeatureFlags"


class StopCheckingFeatureFlags(Exception):
  """ Raise this inside of a feature flag handler to immediately return False and stop any further handers from running """
  pass


class NoFeatureFlagFound(Exception):
  """ Raise this when the feature flag does not exist. """
  pass


_ns = Namespace()
missing_feature = _ns.signal('missing-feature')


def AppConfigFlagHandler(feature=None):
  """ This is the default handler. It checks for feature flags in the current app's configuration.

  For example, to have 'unfinished_feature' hidden in production but active in development:

  config.py

  class ProductionConfig(Config):

    FEATURE_FLAGS = {
      'unfinished_feature' : False,
    }
Ejemplo n.º 10
0
from __future__ import absolute_import

from . import config

from flask import current_app, request
from flask.signals import Namespace

from .version import __version__


class SSOAttributeError(Exception):
    """General SSO Attribute error."""


# Signals
_signals = Namespace()

sso_logged_in = _signals.signal('sso-logged-in')
"""Sent when a user is logged in.

In addition to the app (which is the sender), it is passed `user`, which is
the user being logged in.
"""


class SSO(object):
    """Flask extension implementation."""
    def __init__(self, app=None):
        """Initialize login callback."""
        self.login_callback = None
        self.login_error_callback = None
Ejemplo n.º 11
0
    string_types = str,
    from itertools import zip_longest

    def b(s):
        return s.encode("latin-1")
else:
    from cStringIO import StringIO as BytesIO
    string_types = basestring,
    from itertools import izip_longest as zip_longest

    def b(s):
        return s


# Signals
_signals = Namespace()

#: Sent when a sitemap index is generated and given page will need to be
#: generated in the future from already calculated url set.
sitemap_page_needed = _signals.signal('sitemap-page-needed')


class Sitemap(object):
    """Flask extension implementation."""

    def __init__(self, app=None, force_domain=None):
        """Initialize login callback."""
        self.decorators = []
        self.url_generators = [self._routes_without_params]

        if app is not None:
Ejemplo n.º 12
0
from flask.signals import Namespace

namespace = Namespace()

pre_action = namespace.signal('pre-action')
post_action = namespace.signal('post-action')

Ejemplo n.º 13
0
except ImportError:
    from urllib.parse import quote
    from urllib.parse import urljoin
    from urllib.parse import urlencode

try:
    from urllib import urlopen
except ImportError:
    from urllib.request import urlopen

try:
    import simplejson as json
except ImportError:
    import json

_signals = Namespace()
wx_userinfo_fetched = _signals.signal("wx-userinfo-fetched")

blueprint = flask.Blueprint("wx_auth", __name__)


@blueprint.route("/authorize")
def authorize():
    auth_url = WXOAuth2.create_authorize_url(redirect_uri=url_for(".callback", _external=True))
    return flask.redirect(auth_url)


@blueprint.route("/callback")
def callback():
    code = flask.request.args.get("code", None)
    if not code:
Ejemplo n.º 14
0
from flask.ext.security import (user_datastore, login_manager,
                                get_post_login_redirect, current_user,
                                login_user, login_required, Security,
                                BadCredentialsError, User, get_class_by_name)

from flask import (Blueprint, redirect, flash, session, request, abort,
                   current_app)

from flask.signals import Namespace
from flask.ext.oauth import OAuth

from werkzeug.local import LocalProxy
from werkzeug.utils import import_string

_signals = Namespace()

URL_PREFIX_KEY = 'SOCIAL_URL_PREFIX'
APP_URL_KEY = 'SOCIAL_APP_URL'
CONNECTION_DATASTORE_KEY = 'SOCIAL_CONNECTION_DATASTORE'
CONNECT_ALLOW_REDIRECT_KEY = 'SOCIAL_CONNECT_ALLOW_REDIRECT'
CONNECT_DENY_REDIRECT_KEY = 'SOCIAL_CONNECT_DENY_REDIRECT'
FLASH_MESSAGES_KEY = 'SOCIAL_FLASH_MESSAGES'

POST_OAUTH_CONNECT_SESSION_KEY = 'post_oauth_connect_url'
POST_OAUTH_LOGIN_SESSION_KEY = 'post_oauth_login_url'

connection_datastore = LocalProxy(
    lambda: getattr(current_app, current_app.config[CONNECTION_DATASTORE_KEY]))

default_config = {
Ejemplo n.º 15
0
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from flask.signals import Namespace

ns = Namespace()

#: Sent when a metric needs to be updated
metric_need_update = ns.signal('metric:need-update')

#: Sent when a metric has been updated
metric_updated = ns.signal('metric:updated')
Ejemplo n.º 16
0
>>> ext = SSO(app=app)
"""

from __future__ import absolute_import

from . import config

from flask import current_app, request
from flask.signals import Namespace

class SSOAttributeError(Exception):
    pass


# Signals
_signals = Namespace()

#: Sent when a user is logged in. In addition to the app (which is the
#: sender), it is passed `user`, which is the user being logged in.
sso_logged_in = _signals.signal('sso-logged-in')


class SSO(object):
    """
    Flask extension

    Initialization of the extension:

    >>> from flask import Flask
    >>> from flask_sso import SSO
    >>> app = Flask('myapp')
Ejemplo n.º 17
0
from flask.signals import Namespace
from flask.ext.sqlalchemy import SQLAlchemy
from raven.contrib.flask import Sentry


sentry = Sentry()
db = SQLAlchemy()
db_signals = Namespace()
db_created = db_signals.signal('created')
Ejemplo n.º 18
0
from flask.ext.babelex import Domain
try:
    from collections import OrderedDict
except ImportError:
    from ordereddict import OrderedDict
from coaster.utils import getbool
from coaster.views import get_current_url, get_next_url

from flask import session, g, redirect, url_for, request, flash, abort, Response, jsonify, json, current_app
from flask.signals import Namespace

from . import translations
from ._version import *  # NOQA

# Signals
lastuser_signals = Namespace()

signal_user_session_refreshed = lastuser_signals.signal('user-session-refreshed')
signal_user_session_expired = lastuser_signals.signal('user-session-expired')
signal_user_looked_up = lastuser_signals.signal('user-looked-up')
signal_before_wrapped_view = lastuser_signals.signal('before-wrapped-view')

# Translations
flask_lastuser_translations = Domain(translations.__path__[0], domain='flask_lastuser')
_ = flask_lastuser_translations.gettext
__ = flask_lastuser_translations.lazy_gettext

# Bearer token, as per http://tools.ietf.org/html/draft-ietf-oauth-v2-bearer-15#section-2.1
auth_bearer_re = re.compile("^Bearer ([a-zA-Z0-9_.~+/-]+=*)$")

Ejemplo n.º 19
0
            if key in app.config:
                self.config[key] = app.config[key]
        self.app = app

    def config_from_env(self):
        for key in self.config:
            self.config[key] = os.environ.get(key, self.config[key])

    def send(self, message):
        if not message.from_email:
            message.set_from(self.config['MAIL_DEFAULT_SENDER'])

        # send signal
        email_dispatched.send(
            current_app._get_current_object(), message=message)

        if self.app and self.app.testing:
            return

        status, reason = self.sg.send(message)
        if status == 200:
            return status, reason
        else:
            raise SendEmailError('{}: {}'.format(status, message))

signals = Namespace()
email_dispatched = signals.signal("email-dispatched", doc="""
Signal sent when an email is dispatched. This signal will also be sent
in testing mode, even though the email will not actually be sent.
""")
Ejemplo n.º 20
0
from __future__ import unicode_literals, print_function

from datetime import datetime, timedelta
import six
from lazy import lazy
from abc import ABCMeta, abstractmethod, abstractproperty
from werkzeug.datastructures import CallbackDict
import flask
from flask.signals import Namespace
from flask_dance.consumer.backend.session import SessionBackend
from flask_dance.utils import getattrd, timestamp_from_datetime

_signals = Namespace()
oauth_authorized = _signals.signal('oauth-authorized')
oauth_error = _signals.signal('oauth-error')


class BaseOAuthConsumerBlueprint(six.with_metaclass(ABCMeta, flask.Blueprint)):
    def __init__(self,
                 name,
                 import_name,
                 static_folder=None,
                 static_url_path=None,
                 template_folder=None,
                 url_prefix=None,
                 subdomain=None,
                 url_defaults=None,
                 root_path=None,
                 login_url=None,
                 authorized_url=None,
                 backend=None):
Ejemplo n.º 21
0
from __future__ import absolute_import
from __future__ import unicode_literals

from flask.signals import Namespace

_signals = Namespace()

# Call when application initializations is completed.
# Sender will be the application instance.
app_ready = _signals.signal('app-ready')
config_ready = _signals.signal('config-ready')
testing_run_start = _signals.signal('testing-run-start')
Ejemplo n.º 22
0
from flask.signals import Namespace

ns = Namespace()

#: Sent when a metric needs to be updated
metric_need_update = ns.signal('metric:need-update')

#: Sent when a metric has been updated
metric_updated = ns.signal('metric:updated')
Ejemplo n.º 23
0
from sqlalchemy import event

from flask import g
from .core import SignallingSessionPlus as Session
from flask.signals import Namespace
from ..utils import (set_if_absent_and_get, append_if_absent, flatten,
                     ist_now)
from decimal import Decimal

db_signals = Namespace()
out_of_stock = db_signals.signal('out_of_stock')
shipment_status_change = db_signals.signal('shipment_status_change')
customer_init = db_signals.signal('customer_init')


def all_subclasses(cls):
    return cls.__subclasses__() + [
        g for s in cls.__subclasses__() for g in all_subclasses(s)]


def add_to_record(key, item, struct=g):
    append_if_absent(set_if_absent_and_get(struct, key, []), item)


class EventListener:

    def __init__(self, app=None):
        self.app = app
        if app:
            self.initialize_listeners()
Ejemplo n.º 24
0
import os.path
from warnings import warn
from inspect import getargspec

from genshi.template import (NewTextTemplate, MarkupTemplate, loader,
                             TemplateLoader)
from werkzeug.utils import cached_property
from flask import current_app

try:
    from flask import signals_available
except ImportError:
    signals_available = False
else:
    from flask.signals import Namespace
    signals = Namespace()
    template_generated = signals.signal('template-generated')


# there's more to Jinja context than just environment,
# but apparently the only thing jinja filters currently care about is this (and also whether autoescaping is on),
# hence these shims.
# XXX this does not take custom jinja filters into account, although I don't expect Genshi-minded users of @jinja2.contextfilter any time soon.
class FakeJinjaContext:
    def __init__(self, env):
        self.environment = env


class FakeJinjaEvalContext:
    def __init__(self, env):
        self.environment = env
Ejemplo n.º 25
0
# -*- coding: utf-8 -*-

from flask.signals import Namespace


baseframe_signals = Namespace()

form_validation_error = baseframe_signals.signal('form-validation-error')
form_validation_success = baseframe_signals.signal('form-validation-success')
exception_catchall = baseframe_signals.signal('exception-catchall')
Ejemplo n.º 26
0
from datetime import datetime, timedelta
from functools import wraps
from hashlib import sha1, md5

import hmac
import warnings
import sys

if sys.version < '3':  # pragma: no cover
    from urlparse import urlparse, urlunparse
else:  # pragma: no cover
    from urllib.parse import urlparse, urlunparse
    unicode = str

_signals = Namespace()

#: A proxy for the current user. If no user is logged in, this will be an
#: anonymous user
current_user = LocalProxy(lambda: _get_user())

#: The default name of the "remember me" cookie (``remember_token``)
COOKIE_NAME = 'remember_token'

#: The default time before the "remember me" cookie expires (365 days).
COOKIE_DURATION = timedelta(days=365)

#: Whether the "remember me" cookie requires Secure; defaults to ``None``
COOKIE_SECURE = None

#: Whether the "remember me" cookie uses HttpOnly or not; defaults to ``False``
Ejemplo n.º 27
0
from flask import current_app
from flask.signals import Namespace
applicationSingnals = Namespace()

onOrderRefunded = applicationSingnals.signal('order-refunded')
onOrderDiscounted = applicationSingnals.signal('order-discounted')

onOrderDiscountApproved = applicationSingnals.signal('order-discount-approved')
onOrderRefundApproved = applicationSingnals.signal('order-refund-approved')

onOrderDeleted = applicationSingnals.signal('order-deleted')
onOrderSerivceChanged = applicationSingnals.signal('order-service-changed')

onUserDeleted = applicationSingnals.signal('user-deleted')
onUserUpdated = applicationSingnals.signal('user-updated')
onUserCreated = applicationSingnals.signal('user-created')
onUserLoggedin = applicationSingnals.signal('user-loggedin')
onUserLogginAttempted = applicationSingnals.signal('user-login-attempted')

onSessionResetUsed = applicationSingnals.signal('session-reset-used')
onSessionResetLastUsed = applicationSingnals.signal('session-reset-last-used')
onSessionServiceChanged = applicationSingnals.signal('session-service-changed')

onPatientUpdated = applicationSingnals.signal('patient-updated')
onPatientDeleted = applicationSingnals.signal('patient-deleted')
onPatientCreated = applicationSingnals.signal('patient-created')


@onOrderRefunded.connect
def onOrderRefundedCallback(data, **kwargs):
    pass
Ejemplo n.º 28
0
from __future__ import unicode_literals, print_function

import six
from lazy import lazy
from abc import ABCMeta, abstractmethod, abstractproperty
from distutils.version import StrictVersion
import flask
from flask.signals import Namespace
from flask_dance.consumer.backend.session import SessionBackend
from flask_dance.utils import Dictective, getattrd


_signals = Namespace()
oauth_authorized = _signals.signal('oauth-authorized')
oauth_error = _signals.signal('oauth-error')


class BaseOAuthConsumerBlueprint(six.with_metaclass(ABCMeta, flask.Blueprint)):
    def __init__(self, name, import_name,
            static_folder=None, static_url_path=None, template_folder=None,
            url_prefix=None, subdomain=None, url_defaults=None, root_path=None,
            login_url=None, authorized_url=None, backend=None):

        bp_kwargs = dict(
            name=name,
            import_name=import_name,
            static_folder=static_folder,
            static_url_path=static_url_path,
            template_folder=template_folder,
            url_prefix=url_prefix,
            subdomain=subdomain,
Ejemplo n.º 29
0
def custom_signal():
    ns = Namespace()
    custom_sig = ns.signal("custom_signal")
    custom_sig.connect = Mock()

    return custom_sig
Ejemplo n.º 30
0
import copy
from flask import _app_ctx_stack
from flask.signals import Namespace
from sqlalchemy import orm
from sqlalchemy.event import listen
from wowhua_db.api.util import get_scoped_session as get_api_session
from wowhua_db.admin.util import get_scoped_session as get_admin_session

# migrated from flask_sqlalchemy
_signals = Namespace()
models_committed = _signals.signal('models-committed')


class SignallingSession(orm.Session):
    def __init__(self, **options):
        super(SignallingSession, self).__init__(**options)
        self._model_changes = {}


class _SessionSignalEvents(object):
    def register(self, app):
        self.app = app
        listen(SignallingSession, 'after_commit',
               self.session_signal_after_commit)

    def session_signal_after_commit(self, session):
        d = session._model_changes
        if d:
            models_committed.send(self.app, changes=d.values())
            d.clear()
Ejemplo n.º 31
0
from warnings import warn
from inspect import getargspec

from genshi.template import (NewTextTemplate, MarkupTemplate,
                             loader, TemplateLoader)
from werkzeug import cached_property
import flask
from flask import current_app

try:
    from flask import signals_available
except ImportError:
    signals_available = False
else:
    from flask.signals import Namespace
    signals = Namespace()
    template_generated = signals.signal('template-generated')


class Genshi(object):
    """Initialize extension.

    ::

        app = Flask(__name__)
        genshi = Genshi(app)

    .. versionchanged:: 0.4
        You can now initialize your application later with :meth:`init_app`.

    .. deprecated:: 0.4
Ejemplo n.º 32
0
__version__ = '0.3.5'

import sys

from functools import partial, wraps
from collections import deque

from collections import namedtuple

from flask import g, session, current_app, abort, request
from flask.signals import Namespace

PY3 = sys.version_info[0] == 3

signals = Namespace()


identity_changed = signals.signal('identity-changed', doc="""
Signal sent when the identity for a request has been changed.

Actual name: ``identity-changed``

Authentication providers should send this signal when authentication has been
successfully performed. Flask-Principal connects to this signal and
causes the identity to be saved in the session.

For example::

    from flaskext.principal import Identity, identity_changed
Ejemplo n.º 33
0
# -*- coding:utf-8 -*-
from flask.signals import Namespace

_signals = Namespace()

on_start = _signals.signal('on_start')
Ejemplo n.º 34
0
from eve.methods.post import post_internal
from eve.methods.common import oplog_push
from ext.app.eve_helper import eve_abort

from datetime import datetime

import json
from bson.objectid import ObjectId

from ext.auth.helpers import Helpers
from ext.notifications.email import Email  # , Sms

# TIME & DATE - better with arrow only?
import arrow

_signals = Namespace()

# Define signals
signal_activity_log     = _signals.signal('user-activity-logger')
signal_insert_workflow  = _signals.signal('insert-workflow')
signal_change_owner     = _signals.signal('change-owner')
signal_change_acl       = _signals.signal('change-acl')
signal_init_acl         = _signals.signal('init-acl')


@signal_insert_workflow.connect
def insert_workflow(dict_app, **extra):
    """ Inserts workflow, wathcers, owner, reporter and custom id on the current resource
    Only when method equals POST
    @todo: need resource->workflow mapping
    @todo: should hook into the given workflow (from mapping?)and retrieve schema OR schema is fixed
Ejemplo n.º 35
0
    url = factory.Faker('url')
    description = factory.Faker('text')


class HarvestJobFactory(factory.mongoengine.MongoEngineFactory):
    class Meta:
        model = HarvestJob

    created = dtfactory('-3h', '-2h')
    started = dtfactory('-2h', '-1h')
    ended = dtfactory('-1h', 'new')
    status = FuzzyChoice(HarvestJob.status.choices)
    source = factory.SubFactory(HarvestSourceFactory)


ns = Namespace()

mock_initialize = ns.signal('backend:initialize')
mock_process = ns.signal('backend:process')

DEFAULT_COUNT = 3


class FactoryBackend(backends.BaseBackend):
    name = 'factory'

    def initialize(self):
        mock_initialize.send(self)
        for i in range(self.config.get('count', DEFAULT_COUNT)):
            self.add_item(i)
Ejemplo n.º 36
0
# -*- coding: utf-8 -*-
"""
    flask_login.signals
    -------------------
    This module provides signals to get notified when Flask-Login performs
    certain actions.
"""


from flask.signals import Namespace


_signals = Namespace()


#: Sent when a user is logged in. In addition to the app (which is the
#: sender), it is passed `user`, which is the user being logged in.
user_logged_in = _signals.signal("logged-in")

#: Sent when a user is logged out. In addition to the app (which is the
#: sender), it is passed `user`, which is the user being logged out.
user_logged_out = _signals.signal("logged-out")

#: Sent when the user is loaded from the cookie. In addition to the app (which
#: is the sender), it is passed `user`, which is the user being reloaded.
user_loaded_from_cookie = _signals.signal("loaded-from-cookie")

#: Sent when the user is loaded from the header. In addition to the app (which
#: is the #: sender), it is passed `user`, which is the user being reloaded.
user_loaded_from_header = _signals.signal("loaded-from-header")
Ejemplo n.º 37
0
from __future__ import unicode_literals, print_function

from datetime import datetime, timedelta
import six
from lazy import lazy
from abc import ABCMeta, abstractmethod, abstractproperty
from werkzeug.datastructures import CallbackDict
import flask
from flask.signals import Namespace
from flask_dance.consumer.backend.session import SessionBackend
from flask_dance.utils import getattrd, timestamp_from_datetime

_signals = Namespace()
oauth_authorized = _signals.signal("oauth-authorized")
oauth_before_login = _signals.signal("oauth-before-login")
oauth_error = _signals.signal("oauth-error")


class BaseOAuthConsumerBlueprint(six.with_metaclass(ABCMeta, flask.Blueprint)):
    def __init__(
        self,
        name,
        import_name,
        static_folder=None,
        static_url_path=None,
        template_folder=None,
        url_prefix=None,
        subdomain=None,
        url_defaults=None,
        root_path=None,
        login_url=None,
Ejemplo n.º 38
0
from __future__ import with_statement

__version__ = '0.3.5'

from functools import partial, wraps
from collections import deque

try:
    from collections import namedtuple
except ImportError:
    from .backport import namedtuple

from flask import g, session, current_app, abort, request
from flask.signals import Namespace

signals = Namespace()

identity_changed = signals.signal('identity-changed',
                                  doc="""
Signal sent when the identity for a request has been changed.

Actual name: ``identity-changed``

Authentication providers should send this signal when authentication has been
successfully performed. Flask-Principal connects to this signal and
causes the identity to be saved in the session.

For example::

    from flaskext.principal import Identity, identity_changed
Ejemplo n.º 39
0
csrf(app)


# register additional template commands
def url_for_other_page(page):
    args = request.view_args.copy()
    args['page'] = page
    return url_for(request.endpoint, **args)


app.jinja_env.globals['url_for_other_page'] = url_for_other_page

#
# Blinker custom signals
#
signals = Namespace()
before_flush = signals.signal('models-before-flush')


# Add flush signalling to session, used to auto-calculate balance later on
class _CustomSessionSignalEvents(object):
    def register(self):
        sqla_event.listen(SQLA_SessionBase, 'before_flush',
                          self.session_signal_before_flush)

    @staticmethod
    def session_signal_before_flush(session, flush_context, instances):
        before_flush.send(session.app, session=session, instances=instances)


class SQLAlchemy(SQLAlchemyBase):
Ejemplo n.º 40
0
from flask.signals import Namespace

__all__ = ['request_token_fetched']

_signals = Namespace()
request_token_fetched = _signals.signal('request-token-fetched')
Ejemplo n.º 41
0
# -*- coding: utf-8 -*-

from flask.signals import Namespace
from sqlalchemy import event as sqla_event
from .models import User, Organization, Team

lastuser_signals = Namespace()

model_user_new = lastuser_signals.signal('model-user-new')
model_user_edited = lastuser_signals.signal('model-user-edited')
model_user_deleted = lastuser_signals.signal('model-user-deleted')

model_org_new = lastuser_signals.signal('model-org-new')
model_org_edited = lastuser_signals.signal('model-org-edited')
model_org_deleted = lastuser_signals.signal('model-org-deleted')

model_team_new = lastuser_signals.signal('model-team-new')
model_team_edited = lastuser_signals.signal('model-team-edited')
model_team_deleted = lastuser_signals.signal('model-team-deleted')

resource_access_granted = lastuser_signals.signal('resource-access-granted')

# Higher level signals
user_login = lastuser_signals.signal('user-login')
user_logout = lastuser_signals.signal('user-logout')
user_registered = lastuser_signals.signal('user-registered')
user_data_changed = lastuser_signals.signal('user-data-changed')
org_data_changed = lastuser_signals.signal('org-data-changed')
team_data_changed = lastuser_signals.signal('team-data-changed')

Ejemplo n.º 42
0
try:
    from flask import _app_ctx_stack
except ImportError:
    _app_ctx_stack = None


__version__ = "3.0-dev"


# Which stack should we use?  _app_ctx_stack is new in 0.9
connection_stack = _app_ctx_stack or _request_ctx_stack


_camelcase_re = re.compile(r"([A-Z]+)(?=[a-z0-9])")
_signals = Namespace()


models_committed = _signals.signal("models-committed")
before_models_committed = _signals.signal("before-models-committed")


def _make_table(db):
    def _make_table(*args, **kwargs):
        if len(args) > 1 and isinstance(args[1], db.Column):
            args = (args[0], db.metadata) + args[1:]
        info = kwargs.pop("info", None) or {}
        info.setdefault("bind_key", None)
        kwargs["info"] = info
        return sqlalchemy.Table(*args, **kwargs)
Ejemplo n.º 43
0
自定义信号:
- 将信号定义在Flask默认的命名空间内
from flask.signals import _signals
custom_signal = _signals.signal('custom-signal')

- 将信号定义在自定的命名空间内
from flask.signals import Namespace

_signals = Namespace()

#: Sent when a user is logged in. In addition to the app (which is the sender), it is passed `user`, which is the user being logged in.
user_logged_in = _signals.signal('logged-in')
'''

# 实例化命名空间
_signal = Namespace()
# 自定义一个信号
customSignal = _signal.signal('custom-signal')


# 触发信号要执行的函数
def sig(*args, **kwargs):
    # 可以接受send()函数传入的参数
    print(f'触发信号函数: {sig.__name__}, 参数:', args, kwargs)


# 设置信号触发的回调函数;
# 设置 receiver
customSignal.connect(sig)

Ejemplo n.º 44
0
:copyright: (C) 2011 by Matthew Frazier.
:license:   MIT/X11, see LICENSE for more details.
"""
import hmac
from datetime import datetime, timedelta
from flask import (current_app, session, _request_ctx_stack, redirect, url_for,
                   request, flash, abort)
from flask.signals import Namespace
from functools import wraps
from hashlib import sha1, md5
from urlparse import urlparse, urlunparse
from werkzeug.local import LocalProxy
from werkzeug.urls import url_decode, url_encode

_signals = Namespace()


def _get_user():
    return getattr(_request_ctx_stack.top, "user", None)


def _cookie_digest(payload, key=None):
    if key is None:
        key = current_app.config["SECRET_KEY"]
    payload = payload.encode("utf8")
    mac = hmac.new(key, payload, sha1)
    return mac.hexdigest()


def encode_cookie(payload):
Ejemplo n.º 45
0
# 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.
#
# 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.
"""Contain signals emitted from workflows module."""

from flask.signals import Namespace
_signals = Namespace()

workflow_halted = _signals.signal('workflow_halted')
"""
This signal is sent when a workflow engine's halt function is called.
Sender is the BibWorkflowObject that was running before the workflow
was halted.
"""

workflow_started = _signals.signal('workflow_started')
"""
This signal is sent when a workflow is started.
Sender is the workflow engine object running the workflow.
"""

workflow_finished = _signals.signal('workflow_finished')
Ejemplo n.º 46
0
class Api(object):
    """Docstring for Api. """

    MAX_PAGE_SIZE_CONFIG = 'MAX_PAGE_SIZE'
    MAX_PAGE_SIZE_DEFAULT = 100

    _signal = Namespace()

    @property
    def max_page_size(self):
        return self.app.config.get(self.MAX_PAGE_SIZE_CONFIG,
                                   self.MAX_PAGE_SIZE_DEFAULT)

    def __init__(self,
                 app,
                 version=None,
                 root='/api',
                 encode=None,
                 filter_builder=None):
        """TODO: to be defined1.

        :app: TODO
        :encode: function accepting one argument, returning tuple of 2 values -
        first is value encodable by json encoder or original object and second
        if value was encoded by function

        """
        self.version = version
        self.root = root
        self.encoder_cls = self.get_encoder_cls(encode)
        if filter_builder:
            self.filter_builder = filter_builder
        else:
            self.filter_builder = FilterBuilder()
        self.api_error_signal = self._signal.signal('api-error')
        self.before_response_encoding_signal = self._signal.signal(
            'before-response-encoding')
        self.init_app(app)

    @staticmethod
    def _str_to_type(value, value_type):
        pass

    def _filter_from_dict(self, filter_data, field_type):
        return {}

    def _catch_api_error(self, e):
        self.api_error_signal.send(self, error=e)
        details = []
        if e.messages:
            details = e.messages
        error = self.get_error(e.message, details, e.error_code)
        return self.json_response(error, e.error_code)

    def _set_page_size(self):
        page_size = flask.request.args.get('page_size')
        if page_size is None:
            page_size = self.max_page_size
        else:
            try:
                page_size = int(page_size)
            except ValueError:
                raise errors.ApiError('`page_size` should be positive integer',
                                      400)
            page_size = min(page_size, self.max_page_size)
            if page_size < 1:
                raise errors.ApiError('`page_size` should be positive integer',
                                      400)
        flask.g.api.page_size = page_size

    def _set_page(self):
        page = 0
        if 'page' in flask.request.args:
            try:
                page = int(flask.request.args['page']) - 1
            except ValueError:
                raise errors.ApiError('`page` should be positive integer', 400)
            if page < 0:
                raise errors.ApiError('`page` should be positive integer', 400)
        flask.g.api.page = page

    def _set_order_by(self, allowed_fields):
        field = flask.request.args.get('order_by')
        if not field:
            flask.g.api.order_by = None
        else:
            if field.startswith('-'):
                flask.g.api.order_by = Sorting(field[1:], True)
            else:
                flask.g.api.order_by = Sorting(field, False)
            if flask.g.api.order_by.field not in allowed_fields:
                flask.g.api.order_by = None

    def _set_filter(self, validator, filter_types):
        if not validator:
            flask.g.api.filter = None
            return
        request_filter = self.filter_builder.filter_from_request(filter_types)
        if not validator.validate(request_filter):
            validator_errors = []
            for prop, error in validator.errors.items():
                validator_errors.append({prop: error})
            raise errors.ApiError('Incorrect filter format',
                                  400,
                                  messages=validator_errors)
        flask.g.api.filter = validator.document

    def register_api_data(self):
        flask.g.api = ApiData()

    def init_app(self, app):
        app.api = self
        self.app = app
        self.app.before_request(self.register_api_data)
        self.app.register_error_handler(errors.ApiError, self._catch_api_error)

    def get_encoder_cls(self, encode):
        class CustomEncoder(json.JSONEncoder):
            def default(self, obj):
                if isinstance(obj, decimal.Decimal):
                    return float(obj)
                elif isinstance(obj, date):
                    return obj.isoformat()
                elif isinstance(obj, datetime):
                    if not obj.tzinfo:
                        obj = obj.replace(tzinfo=dateutil.tz.tzutc())
                    return obj.isoformat()
                elif isinstance(obj, set):
                    return list(obj)
                elif encode:
                    obj, ok = encode(obj)
                    if ok:
                        return obj
                return json.JSONEncoder.default(self, obj)

        return CustomEncoder

    def get_path(self, path):
        if self.version:
            return '{root}/{version}{path}'.format(root=self.root,
                                                   version=self.version,
                                                   path=path)
        else:
            return '{root}{path}'.format(root=self.root, path=path)

    def get_error(self, message, details=None, code=400):
        """TODO: Docstring for get_error.

        :message: TODO
        :details: TODO
        :returns: TODO

        """
        details = details or []
        return {'message': message, 'details': details, 'code': code}

    def json_response(self, data, code):
        data = json.dumps(data, cls=self.encoder_cls)
        response = flask.make_response(data, code)
        response.mimetype = 'application/json'
        return response

    def register_checked_json(self,
                              validator=None,
                              json_required=True,
                              json_data=None):
        if json_data is None:
            if flask.request.is_json:
                json_data = flask.request.get_json()
            elif not flask.request.is_json and json_required:
                raise errors.ApiError('JSON data expected', 400)
            else:
                json_data = {}
        if validator:
            if not validator.validate(json_data):
                validator_errors = []
                for prop, error in validator.errors.items():
                    validator_errors.append({prop: error})
                raise errors.ApiError('Incorrect data format',
                                      400,
                                      messages=validator_errors)
            json_data = validator.document
        flask.g.api.json = json_data

    def endpoint(self, path, method):
        ApiDoc.set_wrapper_endpoint(path, method)
        ApiDoc.add_wrapper_props({'method': method})

        def wrapper(f):
            @self.app.route(self.get_path(path), methods=[method])
            @wraps(f)
            def endpoint(*args, **kwargs):
                response = f(*args, **kwargs)
                self.before_response_encoding_signal.send(self)
                if not isinstance(response, flask.Response):
                    response = self.json_response(response, 200)
                return response

        return wrapper

    def get(self, path):
        ApiDoc.set_wrapper_endpoint(path, 'GET')
        ApiDoc.add_wrapper_props({'method': 'GET'})
        return self.endpoint(path, 'GET')

    def list(self, path, order_by=None, filters=None):
        """page based pagination
        """
        ApiDoc.set_wrapper_endpoint(path, 'GET')
        ApiDoc.add_wrapper_props({
            'method': 'GET',
            'list': True,
            'order_by': order_by,
            'filters': filters
        })
        filter_validator = None
        if order_by is None:
            order_by = set()
        if filters:
            filter_validator = Validator(
                self.filter_builder.get_filter_schema(filters))
        if filters is None:
            filters = {}

        def wrapper(f):
            @wraps(f)
            def f_wrapper(*args, **kwargs):
                self._set_page_size()
                self._set_page()
                self._set_order_by(order_by)
                self._set_filter(filter_validator, filters)
                result = f(*args, **kwargs)
                if isinstance(result, Page):
                    response_data = {'data': result.get_items()}
                    if result.has_count():
                        response_data['total'] = result.get_count()
                    return response_data
                else:
                    return {
                        'data': result,
                    }

            return self.get(path)(f_wrapper)

        return wrapper

    def iterate(self, path, order_by=None, filters=None):
        """cursor based pagination
        """
        ApiDoc.set_wrapper_endpoint(path, 'GET')
        ApiDoc.add_wrapper_props({
            'method': 'GET',
            'list': True,
            'order_by': order_by,
            'filters': filters
        })
        filter_validator = None
        if order_by is None:
            order_by = set()
        if filters:
            filter_validator = Validator(
                self.filter_builder.get_filter_schema(filters))
        if filters is None:
            filters = {}

        def wrapper(f):
            @wraps(f)
            def f_wrapper(*args, **kwargs):
                self._set_page_size()
                self._set_order_by(order_by)
                self._set_filter(filter_validator, filters)
                flask.g.api.cursor = flask.request.args.get('next')
                result, cursor = f(*args, **kwargs)
                if isinstance(result, Page):
                    response_data = {'data': result.get_items, 'next': cursor}
                    if result.has_count():
                        response_data['total'] = result.get_count()
                    return response_data
                else:
                    return {'data': result, 'next': cursor}

            return self.get(path)(f_wrapper)

        return wrapper

    def post(self, path, schema=None):
        ApiDoc.set_wrapper_endpoint(path, 'POST')
        ApiDoc.add_wrapper_props({'method': 'POST', 'schema': schema})
        validator = None
        if schema:
            validator = Validator(schema, purge_unknown=True)

        def wrapper(f):
            @wraps(f)
            def f_wrapper(*args, **kwargs):
                flask.g.api.schema = schema
                self.register_checked_json(validator)
                return f(*args, **kwargs)

            return self.endpoint(path, 'POST')(f_wrapper)

        return wrapper

    def upload(self, path, schema=None):
        ApiDoc.set_wrapper_endpoint(path, 'POST')
        ApiDoc.add_wrapper_props({
            'method': 'POST',
            'file_upload': True,
            'schema': schema
        })
        validator = None
        if schema:
            validator = Validator(schema, purge_unknown=True)

        def wrapper(f):
            @wraps(f)
            def f_wrapper(*args, **kwargs):
                flask.g.api.schema = schema
                if 'data' in flask.request.form:
                    json_data = json.loads(flask.request.form['data'])
                else:
                    json_data = {}
                self.register_checked_json(validator, json_data=json_data)
                return f(*args, **kwargs)

            return self.endpoint(path, 'POST')(f_wrapper)

        return wrapper

    def put(self, path, schema=None):
        ApiDoc.set_wrapper_endpoint(path, 'PUT')
        ApiDoc.add_wrapper_props({'method': 'PUT', 'schema': schema})
        validator = None
        if schema:
            validator = Validator(schema, purge_unknown=True)

        def wrapper(f):
            @wraps(f)
            def f_wrapper(*args, **kwargs):
                flask.g.api.schema = schema
                self.register_checked_json(validator, json_required=False)
                return f(*args, **kwargs)

            return self.endpoint(path, 'PUT')(f_wrapper)

        return wrapper

    def delete(self, path):
        ApiDoc.set_wrapper_endpoint(path, 'DELETE')
        ApiDoc.add_wrapper_props({
            'method': 'DELETE',
        })

        def wrapper(f):
            @wraps(f)
            def f_wrapper(*args, **kwargs):
                result = f(*args, **kwargs)
                if result is None:
                    return {}
                return result

            return self.endpoint(path, 'DELETE')(f_wrapper)

        return wrapper

    def doc(self, description):
        ApiDoc.add_wrapper_props({'description': description})

        def wrapper(f):
            return f

        return wrapper
Ejemplo n.º 47
0
#
# Flask-Airpbx
#
# Copyright (C) 2021 Airpbx Ltd
# All rights reserved
#

from flask.signals import Namespace

namespace = Namespace()

ping = namespace.signal('ping')

# EOF
from flask.signals import Namespace
from sqlalchemy import event
from sqlalchemy import inspect
from sqlalchemy import orm
from sqlalchemy.engine.url import make_url
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.declarative import DeclarativeMeta
from sqlalchemy.orm.exc import UnmappedClassError
from sqlalchemy.orm.session import Session as SessionBase

from .model import DefaultMeta
from .model import Model

__version__ = "3.0.0.dev"

_signals = Namespace()
models_committed = _signals.signal("models-committed")
before_models_committed = _signals.signal("before-models-committed")


def _make_table(db):
    def _make_table(*args, **kwargs):
        if len(args) > 1 and isinstance(args[1], db.Column):
            args = (args[0], db.metadata) + args[1:]
        info = kwargs.pop("info", None) or {}
        info.setdefault("bind_key", None)
        kwargs["info"] = info
        return sqlalchemy.Table(*args, **kwargs)

    return _make_table
Ejemplo n.º 49
0
#encoding:utf8

from flask.signals import Namespace

__all__ = [
    "request_received", "request_deserialized", "request_badrequest",
    "request_deserialize_error", "request_handle_error", "response_error",
    "response_sent", "wechat_granted", "wechat_servererror", "wechat_error"
]

signals = Namespace()

request_received = signals.signal("request_received")
request_deserialized = signals.signal("request_deserialized")
request_badrequest = signals.signal("request_badrequest")
# request_deserialize_error = signals.signal("request_deserialize_error")
request_handle_error = signals.signal("request_handle_error")

# response_error = signals.signal("response_error")
response_sent = signals.signal("response_sent")

wechat_granted = signals.signal("wechat_granted")
wechat_servererror = signals.signal("wechat_servererror")
wechat_error = signals.signal("wechat_error")
Ejemplo n.º 50
0
:copyright: (C) 2011 by Matthew Frazier.
:license:   MIT/X11, see LICENSE for more details.
"""
import hmac
from datetime import datetime, timedelta
from flask import (current_app, session, _request_ctx_stack, redirect, url_for,
                   request, flash, abort)
from flask.signals import Namespace
from functools import wraps
from hashlib import sha1, md5
from urlparse import urlparse, urlunparse
from werkzeug.local import LocalProxy
from werkzeug.urls import url_decode, url_encode

_signals = Namespace()


def _get_user():
    return getattr(_request_ctx_stack.top, "user", None)


def _cookie_digest(payload, key=None):
    if key is None:
        key = current_app.config["SECRET_KEY"]
    payload = payload.encode("utf8")
    mac = hmac.new(key, payload, sha1)
    return mac.hexdigest()


def encode_cookie(payload):
Ejemplo n.º 51
0
    string_types = str,
    from itertools import zip_longest

    def b(s):
        return s.encode("latin-1")
else:
    from cStringIO import StringIO as BytesIO
    string_types = basestring,
    from itertools import izip_longest as zip_longest

    def b(s):
        return s


# Signals
_signals = Namespace()

#: Sent when a sitemap index is generated and given page will need to be
#: generated in the future from already calculated url set.
sitemap_page_needed = _signals.signal('sitemap-page-needed')


class Sitemap(object):
    """Flask extension implementation."""

    def __init__(self, app=None):
        """Initialize login callback."""
        self.decorators = []
        self.url_generators = [self._routes_without_params]

        if app is not None:
Ejemplo n.º 52
0
from flask.signals import Namespace

# signals
signals = Namespace()
db_before_reset = signals.signal('db-before-reset')
db_reset_dropped = signals.signal('db-reset-dropped')
db_reset_created = signals.signal('db-reset-created')
db_after_reset = signals.signal('db-after-reset')
Ejemplo n.º 53
0
#encoding:utf8

from flask.signals import Namespace

__all__ = ["request_received", "request_deserialized", "request_badrequest", 
    "request_deserialize_error", "request_handle_error", "response_error", 
    "response_sent", "wechat_granted", "wechat_servererror", "wechat_error"]

signals = Namespace()

request_received = signals.signal("request_received")
request_deserialized = signals.signal("request_deserialized")
request_badrequest = signals.signal("request_badrequest")
# request_deserialize_error = signals.signal("request_deserialize_error")
request_handle_error = signals.signal("request_handle_error")

# response_error = signals.signal("response_error")
response_sent = signals.signal("response_sent")

wechat_granted = signals.signal("wechat_granted")
wechat_servererror = signals.signal("wechat_servererror")
wechat_error = signals.signal("wechat_error")
from flask.signals import Namespace

__all__ = ['request_token_fetched']

_signals = Namespace()
request_token_fetched = _signals.signal('request-token-fetched')
Ejemplo n.º 55
0
""" This file creates event notification signals for Flask-User.
    Signals are based on Flask.signals which are based on the blinker signals.

    :copyright: (c) 2013 by Ling Thio
    :author: Ling Thio ([email protected])
    :license: Simplified BSD License, see LICENSE.txt for more details."""

from flask.signals import Namespace

_signals = Namespace()  # Place Flask-User signals in our own namespace
""" *******************
** Flask Signals **
*******************
Flask signals are based on blinker.
Neither Flask nor Flask-User installs blinker
If you plan to use signals, please install blinker with 'pip install blinker'
See http://flask.pocoo.org/docs/signals/"""

# Sent when a user changed their password
user_changed_password = _signals.signal('user.user_changed_password')

# Sent when a user changed their username
user_changed_username = _signals.signal('user.user_changed_username')

# Sent when a user changed their theme
user_changed_theme = _signals.signal('user.user_changed_theme')

# Sent when a user adds a tenant
user_added_tenant = _signals.signal('user.user_added_tenant')

# Sent when a user edits a tenant
Ejemplo n.º 56
0
from sqlalchemy.orm.interfaces import MapperExtension, SessionExtension, \
     EXT_CONTINUE
from sqlalchemy.interfaces import ConnectionProxy
from sqlalchemy.engine.url import make_url
from sqlalchemy.ext.declarative import declarative_base, DeclarativeMeta
from sqlalchemy.util import to_list

# the best timer function for the platform
if sys.platform == 'win32':
    _timer = time.clock
else:
    _timer = time.time


_camelcase_re = re.compile(r'([A-Z]+)(?=[a-z0-9])')
_signals = Namespace()


models_committed = _signals.signal('models-committed')
before_models_committed = _signals.signal('before-models-committed')


def _make_table(db):
    def _make_table(*args, **kwargs):
        if len(args) > 1 and isinstance(args[1], db.Column):
            args = (args[0], db.metadata) + args[1:]
        info = kwargs.pop('info', None) or {}
        info.setdefault('bind_key', None)
        return sqlalchemy.Table(*args, **kwargs)
    return _make_table
Ejemplo n.º 57
0
# published by the Free Software Foundation; either version 2 of the
# 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.

"""Contain signals emitted from workflows module."""

from flask.signals import Namespace
_signals = Namespace()

workflow_halted = _signals.signal('workflow_halted')
"""
This signal is sent when a workflow engine's halt function is called.
Sender is the BibWorkflowObject that was running before the workflow
was halted.
"""

workflow_started = _signals.signal('workflow_started')
"""
This signal is sent when a workflow is started.
Sender is the workflow engine object running the workflow.
"""

workflow_finished = _signals.signal('workflow_finished')
Ejemplo n.º 58
0
    _timer = time.clock
else:
    _timer = time.time

try:
    from flask import _app_ctx_stack
except ImportError:
    _app_ctx_stack = None

__version__ = '2.0'

# Which stack should we use?  _app_ctx_stack is new in 0.9
connection_stack = _app_ctx_stack or _request_ctx_stack

_camelcase_re = re.compile(r'([A-Z]+)(?=[a-z0-9])')
_signals = Namespace()

models_committed = _signals.signal('models-committed')
before_models_committed = _signals.signal('before-models-committed')


def _make_table(db):
    def _make_table(*args, **kwargs):
        if len(args) > 1 and isinstance(args[1], db.Column):
            args = (args[0], db.metadata) + args[1:]
        info = kwargs.pop('info', None) or {}
        info.setdefault('bind_key', None)
        kwargs['info'] = info
        return sqlalchemy.Table(*args, **kwargs)

    return _make_table
Ejemplo n.º 59
0
from flask.signals import Namespace

import RPi.GPIO as GPIO

L1 = 14
L2 = 15
Len = 18

R1 = 23
R2 = 24
Ren = 25

namespace = Namespace()
robot_move = namespace.signal('robot_move')
robot_speed = namespace.signal('robot_speed')


def setupGPIO():
    # mode
    GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BCM)

    #L motor
    GPIO.setup(L1, GPIO.OUT)
    GPIO.output(L1, GPIO.LOW)
    GPIO.setup(L2, GPIO.OUT)
    GPIO.output(L2, GPIO.LOW)
    GPIO.setup(Len, GPIO.OUT)
    Lpwm = GPIO.PWM(Len, 1000)
    Lpwm.start(25)