コード例 #1
0
ファイル: globals.py プロジェクト: bobuss/pynba
from functools import partial, wraps
from werkzeug.local import LocalStack, LocalProxy


def _lookup_object(name, fallback=False):
    top = _CTX_STACK.top
    if top is None:
        if fallback:
            return Fallback
        raise RuntimeError('working outside of request context')
    return getattr(top, name)


_CTX_STACK = LocalStack()
pynba = LocalProxy(partial(_lookup_object, 'pynba', True))


class Fallback(object):
    """Used to define timers globally of a context.
    """
    @staticmethod
    def timer(**tags):
        def decorator(func):
            @wraps(func)
            def wrapper(*args, **kwargs):
                _pynba = _lookup_object("pynba", fallback=False)
                with _pynba.timer(**tags):
                    response = func(*args, **kwargs)
                return response
コード例 #2
0
    Flask-Security recoverable module

    :copyright: (c) 2012 by Matt Wright.
    :license: MIT, see LICENSE for more details.
"""

from flask import current_app as app
from werkzeug.local import LocalProxy

from .signals import password_reset, reset_password_instructions_sent
from .utils import config_value, get_token_status, hash_data, hash_password, \
    url_for_security, verify_hash

# Convenient references
_security = LocalProxy(lambda: app.extensions['security'])

_datastore = LocalProxy(lambda: _security.datastore)


def send_reset_password_instructions(user):
    """Sends the reset password instructions email for the specified user.

    :param user: The user to send the instructions to
    """
    token = generate_reset_password_token(user)
    reset_link = url_for_security('reset_password',
                                  token=token,
                                  _external=True)

    if config_value('SEND_PASSWORD_RESET_EMAIL'):
コード例 #3
0
ファイル: utils.py プロジェクト: AmanAgarwalX/Jobber
from functools import wraps
from werkzeug.local import LocalProxy
from werkzeug.security import safe_str_cmp
from werkzeug.urls import url_decode, url_encode

from flask import (_request_ctx_stack, current_app, request, session, url_for,
                   has_request_context)

from ._compat import text_type, urlparse, urlunparse
from .config import COOKIE_NAME, EXEMPT_METHODS
from .signals import user_logged_in, user_logged_out, user_login_confirmed


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


def encode_cookie(payload):
    '''
    This will encode a ``unicode`` value into a cookie, and sign that cookie
    with the app's secret key.

    :param payload: The value to encode, as `unicode`.
    :type payload: unicode
    '''
    return u'{0}|{1}'.format(payload, _cookie_digest(payload))


def decode_cookie(cookie):
    '''
コード例 #4
0
ファイル: gitlab.py プロジェクト: Przemoo16/flask-dance
    gitlab_bp = OAuth2ConsumerBlueprint(
        "gitlab",
        __name__,
        client_id=client_id,
        client_secret=client_secret,
        scope=scope,
        base_url=f"https://{hostname}/api/v4/",
        authorization_url=f"https://{hostname}/oauth/authorize",
        token_url=f"https://{hostname}/oauth/token",
        redirect_url=redirect_url,
        redirect_to=redirect_to,
        login_url=login_url,
        authorized_url=authorized_url,
        session_class=session_class,
        storage=storage,
        token_url_params={"verify": verify_tls_certificates},
        rule_kwargs=rule_kwargs,
    )
    gitlab_bp.from_config["client_id"] = "GITLAB_OAUTH_CLIENT_ID"
    gitlab_bp.from_config["client_secret"] = "GITLAB_OAUTH_CLIENT_SECRET"

    @gitlab_bp.before_app_request
    def set_applocal_session():
        g.flask_dance_gitlab = gitlab_bp.session

    return gitlab_bp


gitlab = LocalProxy(lambda: g.flask_dance_gitlab)
コード例 #5
0
        current_session.save()
        cookie_value = itsdangerous.Signer(settings.SECRET_KEY).sign(current_session._id)
    else:
        session_id = str(bson.objectid.ObjectId())
        new_session = Session(_id=session_id, data=data or {})
        new_session.save()
        cookie_value = itsdangerous.Signer(settings.SECRET_KEY).sign(session_id)
        set_session(new_session)
    if response is not None:
        response.set_cookie(settings.COOKIE_NAME, value=cookie_value, domain=settings.OSF_COOKIE_DOMAIN,
                            secure=settings.SESSION_COOKIE_SECURE, httponly=settings.SESSION_COOKIE_HTTPONLY)
        return response


sessions = WeakKeyDictionary()
session = LocalProxy(get_session)


# Request callbacks
# NOTE: This gets attached in website.app.init_app to ensure correct callback order
def before_request():
    # TODO: Fix circular import
    from framework.auth.core import get_user
    from framework.auth import cas
    from website.util import time as util_time
    Session = apps.get_model('osf.Session')

    # Central Authentication Server Ticket Validation and Authentication
    ticket = request.args.get('ticket')
    if ticket:
        service_url = furl.furl(request.url)
コード例 #6
0
# This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.

from flask import current_app
from itsdangerous import URLSafeTimedSerializer
from werkzeug.local import LocalProxy

#: An *itsdangerous*-based serializer that can be used to pass small
#: amounts of data through untrusted channels such as a verification
#: email.
#: :type: :class:`~itsdangerous.URLSafeTimedSerializer`
secure_serializer = LocalProxy(lambda: URLSafeTimedSerializer(
    current_app.config['SECRET_KEY'], b'indico'))
コード例 #7
0
from db_backend.utils.user import ApiUser
from flask.ext.restful import abort
from functools import wraps
from werkzeug.local import LocalProxy

debug = False

current_user = LocalProxy(lambda: _request_ctx_stack.top.user)
from flask import session, _request_ctx_stack


def require_login(func):
    """A decorator to ensure that the decorated endpoint is only called from a valid user.

    For debugging the authentication requirement can be turned off using the debug flag
    of this module.

    :param func The endpoint to decorate.
    """
    @wraps(func)
    def nufun(*args, **kwargs):
        if not (debug or current_user.authenticated()):
            abort(401, message="authentication required")
        return func(*args, **kwargs)

    return nufun


def setup_auth(app, user_lookup):
    """Set up the authenticaton module for this app.
コード例 #8
0
            opportunity),
        can_view_opportunity_attachment=can(current_user).view_attachment(
            opportunity),
        can_delete_opportunity_attachment=can(current_user).delete_attachment(
            opportunity),
        can_edit_finance_checklist=can(current_user).edit_finance_checklist(
            opportunity),
        can_read_details=can(current_user).read_details(opportunity),
        can_link_lead=can(current_user).link_lead(opportunity))


opportunity_schema = OpportunitySchema()
rdr_schema = RDRPunchSchema()

mod = Blueprint("opportunityv2", __name__)
current_user = LocalProxy(get_current_user)

ROLE_ASSIGNMENT_FIELDS = {
    User.ROLE_SALES_REP: 'sales_reps',
    User.ROLE_INTERNET_SALES_REP: 'sales_reps',
    User.ROLE_CSR: 'customer_reps',
    User.ROLE_SALES_MANAGER: 'sales_managers',
    User.ROLE_BDC_REP: 'bdc_reps',
    User.ROLE_BDC_MANAGER: 'bdc_reps',
    User.ROLE_FINANCE_MANAGER: 'finance_managers',
}


@mod.errorhandler(404)
def not_found_404(message=None):
    message = message or 'Resource not found'
コード例 #9
0
        return pylons.session


local = Local()

# This a proxy to the bounded config object
local(u'config')

# Thread-local safe objects
config = local.config = CKANConfig()

# Proxies to already thread-local safe objects
request = CKANRequest(_get_request)

# Provide a `c`  alias for `g` for backwards compatibility
g = c = LocalProxy(_get_c)
session = LocalProxy(_get_session)

truthy = frozenset([u'true', u'yes', u'on', u'y', u't', u'1'])
falsy = frozenset([u'false', u'no', u'off', u'n', u'f', u'0'])


def asbool(obj):
    if isinstance(obj, six.string_types):
        obj = obj.strip().lower()
        if obj in truthy:
            return True
        elif obj in falsy:
            return False
        else:
            raise ValueError(u"String is not true/false: {}".format(obj))
コード例 #10
0
ファイル: browser.py プロジェクト: jdemon519/cfme_tests
                keys.Keys.CONTROL,
                keys.Keys.SUBTRACT if self._level < 0 else keys.Keys.ADD)
        ac.perform()

    def __exit__(self, *args, **kwargs):
        ac = ActionChains(browser())
        for _ in xrange(abs(self._level)):
            ac.send_keys(
                keys.Keys.CONTROL,
                keys.Keys.SUBTRACT if -self._level < 0 else keys.Keys.ADD)
        ac.perform()


manager = BrowserManager.from_conf(conf.env.get('browser', {}))

driver = LocalProxy(manager.ensure_open)


def browser():
    """callable that will always return the current browser instance

    If ``None``, no browser is running.

    Returns:

        The current browser instance.

    """
    return manager.browser

コード例 #11
0
ファイル: extensions.py プロジェクト: iamneha/kitchensink
# celery = Celery()
babel = Babel()
toolbar = DebugToolbarExtension()
login_manager = LoginManager()
login_manager.login_view = "user.login"

# sentry
sentry = Sentry()

# login page is now converted to redirect, this message will only be visible
# when user comes back after login.
login_manager.login_message = None


def get_fulfil():
    subdomain = Config.FULFIL_SUBDOMAIN
    offline_access_token = Config.FULFIL_OFFLINE_ACCESS_TOKEN
    try:
        return Client(
            subdomain,
            auth=BearerAuth(offline_access_token)
        )
    except ClientError, e:
        if e.code == 401:
            # unauthorized
            flask.abort(flask.redirect(flask.url_for('user.logout')))
        raise


fulfil = LocalProxy(get_fulfil)
コード例 #12
0
            self.ratelimit['storage_url'] = self.app.redis_url

    def get_flask_dict(self):
        flattened = {}
        for cpk in ['cache', 'mail', 'sendgrid', 'app', 'ratelimit']:
            if cpk in self.keys():
                for i in self[cpk]:
                    if cpk == 'app':
                        key = i.upper()
                    else:
                        key = '{}_{}'.format(cpk, i).upper()
                    flattened[key] = self[cpk][i]

        # These values are used by flask-cloudy.
        for key in [
                'provider', 'key', 'secret', 'container', 'server',
                'server_url'
        ]:
            if key in self.storage:
                flattened[f'STORAGE_{key}'.upper()] = self.storage[key]
        return flattened


def ensure_trailing_slash(d, key):
    """ Add a slash to the end of a dictionary entry if it doesn't already have one. """
    if key in d and d[key] and d[key][-1] != '/':
        d[key] = d[key] + '/'


config = LocalProxy(lambda: current_app.config['THROAT_CONFIG'])
コード例 #13
0
ファイル: api.py プロジェクト: weblate/sonar
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""Organisation Api."""

from functools import partial

from werkzeug.local import LocalProxy

from sonar.modules.users.api import current_user_record

from ..api import SonarIndexer, SonarRecord, SonarSearch
from ..fetchers import id_fetcher
from ..providers import Provider
from .minters import id_minter

current_organisation = LocalProxy(
    lambda: OrganisationRecord.get_organisation_by_user(current_user_record))

# provider
OrganisationProvider = type('OrganisationProvider', (Provider, ),
                            dict(pid_type='org'))
# minter
organisation_pid_minter = partial(id_minter, provider=OrganisationProvider)
# fetcher
organisation_pid_fetcher = partial(id_fetcher, provider=OrganisationProvider)


class OrganisationSearch(SonarSearch):
    """Search organisations."""
    class Meta:
        """Search only on item index."""
コード例 #14
0
from lemonade_chat.api.server.users import Users
from lemonade_chat.api.server import questions

app = Flask(__name__)
db_file = None


def get_users():

    if 'users' not in g:
        g.users = Users(db_file)

    return g.users


users = LocalProxy(get_users)


@app.route('/welcome')
def welcome():

    return response({
        'is_over':
        False,
        'text':
        'Welcome to Lemonade!\n\nWhat is your email address'
    })


@app.route('/identify', methods=['POST'])
def identify():
コード例 #15
0
ファイル: proxies.py プロジェクト: topless/flask-webpackext
# -*- coding: utf-8 -*-
#
# This file is part of Flask-WebpackExt
# Copyright (C) 2017 CERN.
#
# Flask-WebpackExt is free software; you can redistribute it and/or modify
# it under the terms of the Revised BSD License; see LICENSE file for
# more details.
"""Proxy to current extension."""

from __future__ import absolute_import, print_function

from flask import current_app
from werkzeug.local import LocalProxy

current_webpack = LocalProxy(
    lambda: current_app.extensions['flask-webpackext'])
"""Proxy to current extension."""

current_manifest = LocalProxy(
    lambda: current_app.extensions['flask-webpackext'].manifest)
"""Proxy to current manifest."""
コード例 #16
0
from invenio_db import db
from jsonpatch import apply_patch
from sqlalchemy.orm.attributes import flag_modified
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy_continuum.utils import parent_class
from werkzeug.local import LocalProxy

from .dictutils import clear_none, dict_lookup
from .dumpers import Dumper
from .errors import MissingModelError
from .models import RecordMetadata
from .signals import after_record_delete, after_record_insert, \
    after_record_revert, after_record_update, before_record_delete, \
    before_record_insert, before_record_revert, before_record_update

_records_state = LocalProxy(lambda: current_app.extensions['invenio-records'])


class RecordBase(dict):
    """Base class for Record and RecordRevision to share common features."""

    model_cls = RecordMetadata
    """SQLAlchemy model class defining which table stores the records."""

    format_checker = None
    """Class-level attribute to specify a default JSONSchema format checker."""

    validator = None
    """Class-level attribute to specify a JSONSchema validator class."""

    dumper = Dumper()
コード例 #17
0
    redis_key = user_clients_key(user) + client_id
    timeout = current_app.config["REDIS_USER_CLIENT_TIMEOUT"]
    result = redis_db.expire(redis_key, timeout)
    if result == 0:
        add_to_user_clients(user, client_id)
    return result


def get_active_clients_count(user):
    prefix = user_clients_key(user) + "*"
    return len(redis_db.keys(prefix))


def get_user_preferences(user):
    preferences = user.get("preferences")
    if preferences is None:
        preferences = {}
    return preferences


def update_user_preferences(user, new_preferences):
    preferences = get_user_preferences(user)
    preferences.update(new_preferences)
    user["preferences"] = preferences
    db.users.save(user)
    return preferences


db = LocalProxy(get_db)
redis_db = LocalProxy(get_redis_connection)
コード例 #18
0
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from flask.ext.markdown import Markdown
from mdx_linkify.mdx_linkify import LinkifyExtension

from flask import current_app
from werkzeug.local import LocalProxy
from jinja2.filters import do_truncate, do_striptags

md = LocalProxy(lambda: current_app.extensions['markdown'])

EXCERPT_TOKEN = '<!--- --- -->'


class UDataMarkdown(Markdown):
    def __call__(self, stream):
        return super(UDataMarkdown, self).__call__(stream or '')


def set_nofollow(attrs, new=False):
    '''Ensure that Markdown links are 'rel="nofollow"' '''
    attrs['rel'] = 'nofollow'
    return attrs


def init_app(app):
    linkify = LinkifyExtension(configs={'linkify_callbacks': [set_nofollow]})
    app.extensions['markdown'] = UDataMarkdown(app, extensions=[linkify])

    @app.template_filter()
コード例 #19
0
from flask import Blueprint
from flask import render_template
from flask import request
from flask import current_app as app
from werkzeug.local import LocalProxy
from modular.util import Util

DW_pipeline = []
DW_content = {}

pipelines = Blueprint('pipelines', __name__)

logger = LocalProxy(lambda: app.logger)


def DummyDWContent():
    DW_content = {}
    DW_content["colname"] = "colname"
    DW_content["newname"] = ""
    DW_content["prefix"] = "new_"
    DW_content["action"] = "toint"
    DW_content["actioname"] = "To Integer"

    DW_pipeline.append(DW_content)


@pipelines.route('/loadpipeline/<returnpage>', methods=['GET', 'POST'])
def load_pipeline(returnpage):
    pass

コード例 #20
0
import warnings

from collections import OrderedDict
from datetime import datetime, timedelta
from functools import wraps

import jwt

from flask import current_app, request, jsonify, _request_ctx_stack
from werkzeug.local import LocalProxy

__version__ = '0.3.2'

logger = logging.getLogger(__name__)

current_identity = LocalProxy(
    lambda: getattr(_request_ctx_stack.top, 'current_identity', None))

_jwt = LocalProxy(lambda: current_app.extensions['jwt'])

CONFIG_DEFAULTS = {
    'JWT_DEFAULT_REALM': 'Login Required',
    'JWT_AUTH_URL_RULE': '/auth',
    'JWT_AUTH_ENDPOINT': 'jwt',
    'JWT_AUTH_USERNAME_KEY': 'username',
    'JWT_AUTH_PASSWORD_KEY': 'password',
    'JWT_ALGORITHM': 'HS256',
    'JWT_LEEWAY': timedelta(seconds=10),
    'JWT_AUTH_HEADER_PREFIX': 'JWT',
    'JWT_EXPIRATION_DELTA': timedelta(seconds=300),
    'JWT_NOT_BEFORE_DELTA': timedelta(seconds=0),
    'JWT_VERIFY_CLAIMS': ['signature', 'exp', 'nbf', 'iat'],
コード例 #21
0
ファイル: __init__.py プロジェクト: yoophi/sample-posts-api
from flask import current_app
from werkzeug.local import LocalProxy

from app.repositories.mem import MemRepo
from app.repositories.mem.data import initial_data
from app.repositories.sqla import SqlaRepo

repo_mappings = {"MYSQL": SqlaRepo, "MEMORY": MemRepo}


def _get_repo():
    cls = repo_mappings.get(current_app.config.get("REPO_ENGINE"), MemRepo)

    if cls is MemRepo:
        if not getattr(_get_repo, "mem_repo", None):
            _get_repo.mem_repo = cls(initial_data)

        return _get_repo.mem_repo

    return cls()


current_repo = LocalProxy(_get_repo)
コード例 #22
0
ファイル: ctx.py プロジェクト: xiaomabetter/jcoco
# -*- coding: utf-8 -*-
#

from werkzeug.local import LocalProxy
from functools import partial

stack = {}


def _find(name):
    if stack.get(name):
        return stack[name]
    else:
        raise ValueError("Not found in stack: {}".format(name))


current_app = LocalProxy(partial(_find, 'app'))
app_service = LocalProxy(partial(_find, 'service'))

# current_app = []
# current_service = []
コード例 #23
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.

"""Helper proxy to the state object."""

from __future__ import absolute_import, print_function

from flask import current_app
from werkzeug.local import LocalProxy


current_workflows_ui = LocalProxy(
    lambda: current_app.extensions['invenio-workflows-ui']
)

actions = LocalProxy(
    lambda: current_app.extensions['invenio-workflows-ui'].actions
)

workflow_api_class = LocalProxy(
    lambda: current_app.extensions['invenio-workflows-ui'].workflow_api_class
)
コード例 #24
0
ファイル: globals.py プロジェクト: runz0rd/phial
from werkzeug.local import LocalStack, LocalProxy
from typing import cast, Dict
from phial.wrappers import Command


def _find_command() -> Command:
    '''Gets the command from the context stack'''
    top = _command_ctx_stack.top
    if top is None:
        raise RuntimeError('Not in a context with a command')
    return cast(Command, top)


def _get_global() -> Dict:
    top = _global_ctx_stack.top
    if top is None:
        raise RuntimeError('Working outside the app context')
    return cast(Dict, top)


_command_ctx_stack = LocalStack()  # type: ignore
_global_ctx_stack = LocalStack()  # type: ignore
command = cast(Command, LocalProxy(_find_command))  # type: Command
g = cast(Dict, LocalProxy(_get_global))  # type: Dict
コード例 #25
0
    This module contains the Flask-Social core

    :copyright: (c) 2012 by Matt Wright.
    :license: MIT, see LICENSE for more details.
"""
from importlib import import_module

from flask import current_app
from flask_oauth import OAuthRemoteApp as BaseRemoteApp
from flask_security import current_user
from werkzeug.local import LocalProxy

from .utils import get_config, update_recursive
from .views import create_blueprint

_security = LocalProxy(lambda: current_app.extensions['security'])

_social = LocalProxy(lambda: current_app.extensions['social'])

_datastore = LocalProxy(lambda: _social.datastore)

_logger = LocalProxy(lambda: current_app.logger)

default_config = {
    'SOCIAL_BLUEPRINT_NAME': 'social',
    'SOCIAL_URL_PREFIX': None,
    'SOCIAL_CONNECT_ALLOW_VIEW': '/',
    'SOCIAL_CONNECT_DENY_VIEW': '/',
    'SOCIAL_POST_OAUTH_CONNECT_SESSION_KEY': 'post_oauth_connect_url',
    'SOCIAL_POST_OAUTH_LOGIN_SESSION_KEY': 'post_oauth_login_url',
    'SOCIAL_APP_URL': 'http://localhost'
コード例 #26
0
ファイル: webfaf2_main.py プロジェクト: AlphaStaxLLC/faf
                    else:
                        menu_public.append(menu_item)
        except Exception as ex:
            logging.exception("Error importing {0} blueprint.".format(filename))

    # This is the official Flask way to store extra data to the app
    if not hasattr(app, "extensions"):
        app.extensions = {}
    app.extensions["menu"] = {
        "public": menu_public,
        "admin": menu_admin
    }

# Add current_menu to teplates. Need some fiddling with app context.
app.context_processor(lambda: dict(
    current_menu=LocalProxy(lambda: current_app.extensions.get(
        "menu", {"public": [], "admin": []}))))

from filters import problem_label, fancydate, timestamp, memory_address
app.jinja_env.filters['problem_label'] = problem_label
app.jinja_env.filters['fancydate'] = fancydate
app.jinja_env.filters['timestamp'] = timestamp
app.jinja_env.filters['memory_address'] = memory_address

from utils import cache, fed_raw_name, WebfafJSONEncoder
app.json_encoder = WebfafJSONEncoder


@app.route('/')
def root():
    return flask.redirect(flask.url_for("summary.index"), code=302)
コード例 #27
0
from bson.json_util import dumps, ObjectId
from flask import current_app
from pymongo import MongoClient, DESCENDING
from werkzeug.local import LocalProxy


# Este método se encarga de configurar la conexión con la base de datos
def get_db():
    platzi_db = current_app.config['PLATZI_DB_URI']
    client = MongoClient(platzi_db)
    return client.platzi


# Use LocalProxy to read the global db instance with just `db`
db = LocalProxy(get_db)


def test_connection():
    return dumps(db.collection_names())


def collection_stats(collection_nombre):
    return dumps(db.command('collstats', collection_nombre))


# -----------------Carreras-------------------------


def crear_carrera(json):
    return str(db.carreras.insert_one(json).inserted_id)
コード例 #28
0
from app.notify_client.support_api_client import support_api_client
from app.notify_client.template_statistics_api_client import template_statistics_client
from app.notify_client.user_api_client import user_api_client
from app.commands import setup_commands
from app.utils import requires_auth
from app.utils import get_cdn_domain
from app.utils import gmt_timezones

login_manager = LoginManager()
csrf = CSRFProtect()

statsd_client = StatsdClient()
deskpro_client = DeskproClient()

# The current service attached to the request stack.
current_service = LocalProxy(partial(_lookup_req_object, 'service'))

# The current organisation attached to the request stack.
current_organisation = LocalProxy(partial(_lookup_req_object, 'organisation'))


def create_app(application):
    setup_commands(application)

    notify_environment = os.environ['NOTIFY_ENVIRONMENT']

    application.config.from_object(configs[notify_environment])

    init_app(application)

    for client in (
コード例 #29
0
from flask_admin.form.fields import DateTimeField
from flask_admin.model.fields import AjaxSelectMultipleField
from flask_babelex import gettext as _
from flask_security.recoverable import send_reset_password_instructions
from flask_security.utils import hash_password
from invenio_db import db
from passlib import pwd
from werkzeug.local import LocalProxy
from wtforms.fields import BooleanField
from wtforms.validators import DataRequired

from .cli import commit
from .models import Role, SessionActivity, User, UserIdentity
from .sessions import delete_session

_datastore = LocalProxy(lambda: current_app.extensions["security"].datastore)


class UserView(ModelView):
    """Flask-Admin view to manage users."""

    can_view_details = True
    can_delete = False

    list_all = ("id", "email", "active", "confirmed_at")

    column_list = (column_searchable_list
                   ) = column_sortable_list = column_details_list = list_all

    form_columns = ("email", "password", "active", "roles", "notification")
コード例 #30
0
ファイル: core.py プロジェクト: clearnote01/i-am-a-pokemon
def find_ask():
    """Find our instance of Ask, navigating Local's and possible blueprints.

    Note: This only supports returning a reference to the first instance of Ask found.
    """
    if hasattr(current_app, 'ask'):
        return getattr(current_app, 'ask')
    else:
        if hasattr(current_app, 'blueprints'):
            blueprints = getattr(current_app, 'blueprints')
            for blueprint_name in blueprints:
                if hasattr(blueprints[blueprint_name], 'ask'):
                    return getattr(blueprints[blueprint_name], 'ask')


request = LocalProxy(lambda: find_ask().request)
session = LocalProxy(lambda: find_ask().session)
version = LocalProxy(lambda: find_ask().version)
context = LocalProxy(lambda: find_ask().context)
convert_errors = LocalProxy(lambda: find_ask().convert_errors)
current_stream = LocalProxy(lambda: find_ask().current_stream)
_stream_buffer = LocalStack()

from . import models

_converters = {'date': to_date, 'time': to_time, 'timedelta': to_timedelta}


class Ask(object):
    """The Ask object provides the central interface for interacting with the Alexa service.