Ejemplo n.º 1
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.º 2
0
class Signals(object):
    
    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.º 3
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.º 4
0
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

    def login_view(req):
        username = req.form.get('username')
        # check the credentials
        identity_changed.send(app, identity=Identity(username))
""")


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

Actual name: ``identity-loaded``
Ejemplo n.º 5
0
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

        if app is not None:
Ejemplo n.º 6
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.º 7
0
from flask.signals import Namespace

namespace = Namespace()

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

Ejemplo n.º 8
0
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.º 9
0
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

    def login_view(req):
        username = req.form.get('username')
        # check the credentials
        identity_changed.send(app, identity=Identity(username))
""")

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

Actual name: ``identity-loaded``
Ejemplo n.º 10
0
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)

    return _make_table

Ejemplo n.º 11
0
    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:
        return flask.redirect(url_for(current_app.config["WX_OAUTH2_REFUSED_ROUTE"]))
Ejemplo n.º 12
0
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
    @todo: generic means it can find what to do for each resource (mappings?)
    @TODO: Should really init the state machine in transitions to do this!
    """
Ejemplo n.º 13
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.º 14
0
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')
    >>> ext = SSO(app=app)

    or alternatively using the factory pattern:
Ejemplo n.º 15
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.º 16
0
    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_.~+/-]+=*)$")


class LastuserConfigException(Exception):
    pass
Ejemplo n.º 17
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.º 18
0
    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")

#: Sent when the user is loaded from the request. In addition to the app (which
#: is the #: sender), it is passed `user`, which is the user being reloaded.
Ejemplo n.º 19
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.º 20
0
from flask.signals import Namespace

__all__ = ['request_token_fetched']

_signals = Namespace()
request_token_fetched = _signals.signal('request-token-fetched')
Ejemplo n.º 21
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.º 22
0
    def is_active(self):
        return False

    def is_anonymous(self):
        return True

    def get_id(self):
        return None


# Signals

#: 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 a user's login is confirmed, marking it as fresh. (It is not
#: called for a normal login.)
#: It receives no additional arguments besides the app.
user_login_confirmed = _signals.signal("login-confirmed")

#: Sent when the `unauthorized` method is called on a `LoginManager`. It
#: receives no additional arguments besides the app.
user_unauthorized = _signals.signal("unauthorized")

#: Sent when the `needs_refresh` method is called on a `LoginManager`. It
Ejemplo n.º 23
0
import logging

from flask.signals import Namespace

log = logging.getLogger(__name__)

ns = Namespace()

#: Sent when a new HarvestSource is created
harvest_source_created = ns.signal('harvest:source-created')

#: Sent when a HarvestSource is updated
harvest_source_updated = ns.signal('harvest:source-updated')

#: Sent when a HarvestSource is deleted
harvest_source_deleted = ns.signal('harvest:source-deleted')

#: Run before each harvest job
before_harvest_job = ns.signal('harvest:before-job')

#: Run before each harvest job
after_harvest_job = ns.signal('harvest:after-job')

#: Sent when a new HarvestJob started
harvest_job_started = ns.signal('harvest:job-started')

#: Sent when a HarvestJob is done
harvest_job_done = ns.signal('harvest:job-done')

#: Sent when a HarvestJob failed
harvest_job_failed = ns.signal('harvest:job-failed')
Ejemplo n.º 24
0
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
        # Flask set this one explicitly
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
def _secret_key(key=None):
    if key is None:
        key = current_app.config['SECRET_KEY']

    if isinstance(key, unicode):  # pragma: no cover
        key = key.encode('latin1')  # ensure bytes

    return key


# Signals

#: 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')

#: Sent when a user's login is confirmed, marking it as fresh. (It is not
#: called for a normal login.)
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
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)
Ejemplo n.º 31
0
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
        ``app.genshi_instance`` in favor of ``app.extensions['genshi']``.
Ejemplo n.º 32
0
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})
    return map(lambda o: UserNeed(o[0]), rv)
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 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.º 35
0

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)

    def process(self, item):
        mock_process.send(self, item=item)
Ejemplo n.º 36
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.º 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
# 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')

# Sent when a user logged in
user_logged_in = _signals.signal('user.user_logged_in')

# Sent when a user logged out
user_logged_out = _signals.signal('user.user_logged_out')
Ejemplo n.º 39
0

# 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):
    def __init__(self,
Ejemplo n.º 40
0
                    'Removed connection to %(provider)s '
                    'account %(provider_user_id)s for %(user)s' % ctx)

                do_flash("Connection to %(provider)s removed" % ctx, 'info')
            except ConnectionNotFoundError:
                current_app.logger.error(
                    'Unable to remove connection to %(provider)s account '
                    '%(provider_user_id)s for %(user)s' % ctx)

                do_flash("Unabled to remove connection to %(provider)s" % ctx,
                         'error')

            return redirect(request.referrer)

        # Configure the URL handlers for each fo the configured providers
        for provider_config in provider_configs:
            _configure_provider(app, blueprint, app.oauth, provider_config)

        url_prefix = app.config[URL_PREFIX_KEY]
        app.register_blueprint(blueprint, url_prefix=url_prefix)


def do_flash(message, category):
    if current_app.config[FLASH_MESSAGES_KEY]:
        flash(message, category)


# Signals
social_connection_created = _signals.signal("connection-created")
social_login_failed = _signals.signal("login-failed")
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
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.º 43
0
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)


@app.route("/")
def index():
Ejemplo n.º 44
0
        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:
            self.init_app(app, force_domain)

    def init_app(self, app, force_domain=None):
        """Initialize a Flask application."""
Ejemplo n.º 45
0
# 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')
"""
This signal is sent when a workflow is finished.
Ejemplo n.º 46
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.º 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 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
    def is_active(self):
        return False

    def is_anonymous(self):
        return True

    def get_id(self):
        return None


# Signals

#: 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 a user's login is confirmed, marking it as fresh. (It is not
#: called for a normal login.)
#: It receives no additional arguments besides the app.
user_login_confirmed = _signals.signal("login-confirmed")

#: Sent when the `unauthorized` method is called on a `LoginManager`. It
#: receives no additional arguments besides the app.
user_unauthorized = _signals.signal("unauthorized")

#: Sent when the `needs_refresh` method is called on a `LoginManager`. It
Ejemplo n.º 51
0
    :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')

# Sent when a user logged in
user_logged_in = _signals.signal('user.user_logged_in')

# Sent when a user logged out
user_logged_out = _signals.signal('user.user_logged_out')
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
        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:
            self.init_app(app)

    def init_app(self, app):
        """Initialize a Flask application."""
from flask.signals import Namespace

__all__ = ['request_token_fetched']

_signals = Namespace()
request_token_fetched = _signals.signal('request-token-fetched')
Ejemplo n.º 55
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.º 56
0
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


def _set_default_query_class(d):
    if 'query_class' not in d:
Ejemplo n.º 57
0
    :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
user_edited_tenant = _signals.signal('user.user_edited_tenant')

# Sent when a user adds a tenant user
user_added_tenant_user = _signals.signal('user.user_added_tenant_user')
Ejemplo n.º 58
0
    _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
#
# 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')
"""
This signal is sent when a workflow is finished.