def test_local_proxies_with_callables(): """Use a callable with a local proxy""" foo = 42 ls = LocalProxy(lambda: foo) assert ls == 42 foo = [23] ls.append(42) assert ls == [23, 42] assert foo == [23, 42]
def test_local_proxy(): """Tests some proxy operations""" foo = [] ls = LocalProxy(lambda: foo) ls.append(42) ls.append(23) ls[1:] = [1, 2, 3] assert foo == [42, 1, 2, 3] assert repr(foo) == repr(ls) assert foo[0] == 42 foo += [1] assert list(foo) == [42, 1, 2, 3, 1]
def match_stats(timespan): """ Return all match victories/losses that match timespan. Return all matches that match timespan. Then checks the match's victory conditions in checkModeVictory. Parameters: timespan(tuple): Three-part tuple. First part is "monthly" or "all". Second part is a datetime with month and year as the starting month. Returns: array: Array of MatchTypeVictory. """ db = LocalProxy(lambda: current_app.db.session) q = models.Match.query timespan_criteria = None count_query = db.query(models.Match.modes_string, func.count(models.Match.id)) if timespan[0] != "all": query_start = timespan[1] query_end = add_months(query_start, 1) print(query_start, query_end) timespan_criteria = and_( models.Match.start_datetime is not None, models.Match.start_datetime.between(query_start, query_end)) q = q.filter(timespan_criteria) count_query = count_query.filter(timespan_criteria) # completion-agnostic playrate first counts = count_query.group_by(models.Match.modes_string).all() formattedCounts = [list(a) for a in (zip(*counts))] q = q.filter(~models.Match.modes_string.contains('|'), ~models.Match.mastermode.contains('mixed')) q = q.all() matches = [] for match in q: if match.is_mixed(): continue victory = checkModeVictory(match) if victory is None: continue s = True if match.mastermode == "secret" else False t = match.modes_string m = MatchTypeVictory(victory, s, t) matches.append(m) return matches, formattedCounts
def _run_rpc(self): #logger.info("Starting RPC server (agent mode)") logger.info("Starting Crediator agent.. (agent mode)") if 'PSDASH_REGISTER_TO' in self.app.config: self._register_agent() service = self.get_local_node().get_service() self.server = zerorpc.Server(service) self.server.bind( 'tcp://%s:%s' % (self.app.config.get('PSDASH_BIND_HOST', self.DEFAULT_BIND_HOST), self.app.config.get('PSDASH_PORT', self.DEFAULT_PORT))) logger.info("This is spartan...") current_node = LocalProxy(self.get_local_node) current_service = LocalProxy(service) # <<Here for watchdog code>> # # class MyHandler(FileSystemEventHandler): # # def on_modified(self, event): # # print(f'event type: {event.event_type} path : {event.src_path}') # # # event_handler = FileSystemEventHandler() # # def on_modified(self, event): # print "hello" # self.process(event) # # def on_created(self, event): # # self.process(event) # # observer = Observer() # observer.schedule(event_handler, path='/opt/stack', recursive=False) # observer.start() # # # try: # while True: # time.sleep(1) # # except KeyboardInterrupt: # observer.stop() # observer.join() # print "This is service info=>", service.get_sysinfo() self.server.run()
def __init__(self, *args, **kws): super(CustomFlask,self).__init__(*args, **kws) self.app = self from flask.globals import _request_ctx_stack _request_ctx_stack.push(self) self.ssl_required_endpoints = set() from werkzeug import LocalStack, LocalProxy def get_current_user(): from myojin.auth import UserModelBase return UserModelBase.current_user() self.current_user = LocalProxy(get_current_user) @self.before_request def check_request(): app = self if not app.config.get('SSL_REQUIRED_REDIRECT'): return from flask import request, jsonify, session from flask import Module, abort, redirect environ = request.environ if not app.is_ssl_request() and request.endpoint in app.ssl_required_endpoints: server_name = ( app.config.get('SSL_HOST', None) or app.config['SERVER_NAME'] or environ.get('HTTP_HOST') or environ.get('SERVER_NAME') ).split(":")[0] query_string = environ.get('QUERY_STRING', '') query_splitter = "?" if query_string else "" path_info = request.environ['PATH_INFO'] return redirect("https://%s%s%s%s" % (server_name, path_info, query_splitter, query_string)) return
def renderable(self): """the macro held but not called""" try: return self.get_template_attribute(self.mwhere, self.mname) except RuntimeError: return LocalProxy( lambda: self.get_template_attribute(self.mwhere, self.mname))
def schemas(self): from werkzeug import LocalProxy def get_schemas(): if not getattr(self, '_schemas', None): self.connect() try: from .schemas import Schemas self._schemas = Schemas(self._sqlalchemy_metadata) except ImportError: logger.warning( 'cannot import Schemas, perhaps sqlalchemy is not up to date' ) return self._schemas return LocalProxy(get_schemas)
def schemas(self): """ object: An object with attributes corresponding to the names of the schemas in this database. """ from werkzeug import LocalProxy def get_schemas(): if not getattr(self, '_schemas', None): assert getattr( self, '_sqlalchemy_metadata', None ) is not None, ( "`{class_name}` instances do not provide the required sqlalchemy metadata " "for schema exploration.".format(self.__class__.__name__)) self._schemas = Schemas(self._sqlalchemy_metadata) return self._schemas return LocalProxy(get_schemas)
def schemas(self): """ This object has as attributes the schemas on the current catalog. These schema objects in turn have the tables as SQLAlchemy `Table` objects. This allows tab completion and exploration of Databases. """ from werkzeug import LocalProxy def get_schemas(): if not getattr(self, '_schemas', None): self.connect() assert getattr( self, '_sqlalchemy_metadata', None ) is not None, ( "`{class_name}` instances do not provide the required sqlalchemy metadata " "for schema exploration.".format(self.__class__.__name__)) self._schemas = Schemas(self._sqlalchemy_metadata) return self._schemas return LocalProxy(get_schemas)
def decorator(f): @wraps(f) def allower(*args, **kwargs): if self.fulfill(requirements): return f(*args, **kwargs) else: raise throws return allower return decorator def identity_loader(self, f): "Provides an identity loader for the instance" self._identity_loader = f return f def fulfill(self, requirements, identity=None): "Runs each requirement until one is not fulfilled" identity = identity or self._identity_loader() return all(r(identity, request) for r in requirements) def __get_allows(): "Internal helper" try: return current_app.extensions['allows'] except (AttributeError, KeyError): raise RuntimeError("Flask-Allows not configured against current app") _allows = LocalProxy(__get_allows, name="flask-allows")
user = User(name=name, email=email, date_joined=now) if (not password): password = generate_password() user.set_password(password) if (not email_verified): user.mark_email_for_activation() else: user.is_email_activated = True user.save() return user def authenticate(email=None, password=None): user = User.objects(email=email).first() if user: if password and user.check_password(password): return user return None from werkzeug import import_string, LocalProxy from flask import current_app User = LocalProxy(lambda: import_string( current_app.config.get("USER_MODEL_CLASS", "flask_mongo_auth.default_models.User")))
import httpagentparser import os import json import datetime from werkzeug import LocalStack, LocalProxy def get_current_user(): from ..models import User return User.current_user() #global current_user current_user = LocalProxy(get_current_user) from .app import app as current_app current_app.current_user = current_user def normalize(text): from unicodedata import normalize as n return n("NFKC", text) def init(): global allow_ip_address allow_ip_address = None global maintenance_data path = current_app.config.get('MAINTENANCE_FILE_PATH') maintenance_data = None if path and os.path.exists(path): with open(path) as f: data = json.loads(f.read()) data['mainte_date'] = \ datetime.datetime.strptime(data['year'] + data['month'] + data['day'] + data['hour'] + data['minute'], '%Y%m%d%H%M') maintenance_data = data
""" fm.ext ====== Flask Application Extension Instantiation. """ # Third Party Libs from flask.ext.via import Via from werkzeug import LocalProxy # First Party Libs from fm.config import ConfigProxy from fm.db.nosql import Redis from fm.db.sqla import FMSQLAlchemy from fm.tasks import Celery # Celery celery = Celery() # Flask-Via for Routing Modules via = Via() # Redis - Stores application state redis = Redis() # Easier config access config = LocalProxy(lambda: ConfigProxy()) # SQLAlchemy db = FMSQLAlchemy()
# Context Locals # ------------- # # Use these context locals with caution and only where # you don't have access to the current request/application # object at all. If there are easy ways of *not* using # context locals, you should not use them. _request_ctx_stack = LocalStack() local = Local() local_manager = LocalManager(local) # Proxy definitions of commonly used objects. ctx = local('ctx') request = LocalProxy(partial(_lookup_object, 'request')) class LocalProperty(object): """Class/Instance property that returns something from the local stack. Note that if some value is not present in the current thread local it does *not* raise an `RuntimeError` but returns `None`. """ def __init__(self, name): self.__name__ = name def __get__(self, obj, type=None): try: object = _lookup_object(self.__name__) except RuntimeError:
] LEGACY_WEBINTERFACE_EXCLUDE = [ 'invenio.legacy.websubmit', ] _cfg_prefix = distutils.sysconfig.get_config_var("prefix") @deprecated('Use a more specific variable from invenio/base/config.py instead', RemovedInInvenio22Warning) def _cfg_prefix_for_proxy(): return _cfg_prefix CFG_PREFIX = LocalProxy(_cfg_prefix_for_proxy) CFG_DATADIR = join(_cfg_prefix, 'var', 'data') CFG_BATCHUPLOADER_DAEMON_DIR = join(_cfg_prefix, "var", "batchupload") CFG_BATCHUPLOADER_DAEMON_DIR = CFG_BATCHUPLOADER_DAEMON_DIR[0] == '/' and CFG_BATCHUPLOADER_DAEMON_DIR \ or _cfg_prefix + '/' + CFG_BATCHUPLOADER_DAEMON_DIR CFG_BIBDOCFILE_FILEDIR = join(CFG_DATADIR, "files") CFG_BINDIR = join(_cfg_prefix, "bin") CFG_ETCDIR = join(_cfg_prefix, "etc") CFG_CACHEDIR = join(_cfg_prefix, "var", "cache") CFG_LOGDIR = join(_cfg_prefix, "var", "log") CFG_RUNDIR = join(_cfg_prefix, "var", "run") CFG_TMPDIR = join(_cfg_prefix, "var", "tmp") CFG_WEBDIR = join(_cfg_prefix, "var", "www") CFG_PYLIBDIR = join(_cfg_prefix, "lib", "python") CFG_LOCALEDIR = join(_cfg_prefix, "share", "locale") CFG_TMPSHAREDDIR = join(_cfg_prefix, "var", "tmp-shared")
'test': { 'name': 'Test User', 'id': '1337-0', 'uid': 'test', 'password': '******', 'address': "Keller, Wundtstr. 5", 'mail': '*****@*****.**', 'mac': 'aa:bb:cc:dd:ee:ff', 'ip': '141.30.228.39', 'hostname': 'My_Server', 'hostalias': 'leethax0r', } } config = LocalProxy(lambda: current_app.extensions['sample_users']) # noinspection PyMethodMayBeStatic class User(BaseUser): datasource = 'sample' def __init__(self, uid): super(User, self).__init__(uid) self.config = config self.name = config[uid]['name'] self.old_mail = config[uid]['mail'] self._ip = "127.0.0.1" def __repr__(self): return "{}.{}({})".format(
return reductor(RadiusLogEntry(*e) for e in self.wait_for_task(task)) def wait_for_task(self, task): self.logger.info("Waiting for task: %s", task) try: return task.apply_async().wait(timeout=self.timeout) except CeleryTimeoutError as e: raise HadesTimeout("The Hades lookup task has timed out") from e except OSError as e: # In newer versions of celery, this is encapsuled by # `kombu.exc.OperationalError`. It is thrown when e.g. the # broker is down if "timeout" in str(e).lower(): raise HadesTimeout( "The Hades lookup task has timed out") from e else: raise HadesOperationalError( "OSError when fetching hades logs") from e def _get_extension(): try: return current_app.extensions['hades_logs'] except KeyError: raise HadesConfigError( "No HadesLogs instance registered to current Flask app") hades_logs = LocalProxy(_get_extension)
from __future__ import with_statement from flask import (Blueprint, send_from_directory, render_template, _app_ctx_stack, abort, url_for, current_app) from jinja2 import contextfunction from jinja2.loaders import TemplateNotFound from werkzeug import LocalProxy from .theme import Theme, ThemeTemplateLoader from .theme_manager import ThemeManager _containable = lambda i: i if hasattr(i, '__contains__') else tuple(i) _fleem = LocalProxy(lambda: current_app.extensions['fleem_manager']) def get_theme(ident): """ Gets the theme with the given identifier from the current app's theme manager. :param ident: The theme identifier. """ return _fleem.themes[ident] def get_themes_list(): """ Returns a list of all the themes in the current app's theme manager sorted
If the timezone is associated with a country that uses only a single timezone, just the localized country name is returned: .. code-block:: python >>> tz = timezone('Europe/Berlin') >>> get_timezone_name(tz, locale='de_DE') u'Deutschland' :param dt_or_tzinfo: The ``datetime`` or ``tzinfo`` object that determines the timezone; if None, the current date and time in UTC is assumed. :param locale: A locale code. If not set, uses the currently loaded locale. :returns: The localized timezone name using location format. """ locale = locale or get_locale() return dates.get_timezone_name(dt_or_tzinfo, locale=locale) # Common alias to gettext. _ = gettext # Current translations. translations = LocalProxy(lambda: get_translations()) # Old names. get_tzinfo = get_timezone
""" :copyright: (c) 2011 Local Projects, all rights reserved :license: Affero GNU GPL v3, see LEGAL/LICENSE for more details. """ import mongoengine from flask import current_app from werkzeug import LocalProxy database = LocalProxy(lambda: current_app.database) def connect_database(db, username=None, password=None, host=None, port=27017, **kwargs): """Connect to MongoDB """ username = None if username == 'None' else username password = None if password == 'None' else password mongoengine.connect(db, username=username, password=password, host=host, port=port) def init(app): """Initialize the database connection
"""Multimedia IIIF Image API.""" from io import BytesIO from flask import current_app, jsonify, redirect, request, send_file, url_for from flask_restful import Resource from flask_restful.utils import cors from werkzeug import LocalProxy from werkzeug.utils import secure_filename from .api import IIIFImageAPIWrapper from .decorators import api_decorator, error_handler from .signals import iiif_after_info_request, iiif_after_process_request, \ iiif_before_info_request, iiif_before_process_request current_iiif = LocalProxy(lambda: current_app.extensions['iiif']) class IIIFImageBase(Resource): """IIIF Image Base.""" def get(self, version, uuid): """Get IIIF Image Base. .. note:: It will redirect to ``iiifimageinfo`` endpoint with status code 303. """ return redirect(url_for('iiifimageinfo', version=version, uuid=uuid), code=303)
import re from operator import attrgetter from types import FunctionType from functools import partial from collections import OrderedDict from werkzeug import LocalProxy from flask import Blueprint, g, _request_ctx_stack, current_app fs = LocalProxy(lambda: current_app.extensions['flarf'].filters) class FlarfFilter(object): """ A class used to instance a filter result on application request :param filter_tag: The name of the filter :param filter_precedence: If you need to order your filters in some way, set this as an integer, defaults to 100. Filters will be ordered from smallest number to largest :param filter_params: A list of paramaters used by the filter on request. May be either string or function: - a function that takes request as an argument - a string 'request_x', indicating x is to be returned from request, e.g. 'request_path' to have the filter get request.path - a string 'get_var' referencing a method on the filter where 'var' is the variable you'd like the filter to capture e.g. 'get_var' will do self.get_var(request) to set self.var - a string for a var found in request.values,
current context for the duration of the `with` block. Example usage:: with app.request_context(environ): do_something_with(request) :params environ: a WSGI environment """ return _RequestContext(self, environ) def test_request_context(self, *args, **kwargs): """Creates a WSGI environment from the given values (see :func:`werkzeug.create_environ` for more information, this function accepts the same arguments). """ return self.request_context(create_environ(*args, **kwargs)) def __call__(self, environ, start_response): """Shortcut for :attr:`wsgi_app`""" return self.wsgi_app(environ, start_response) # context locals _request_ctx_stack = LocalStack() # 看起来同一时间只处理一个请求, current_app = LocalProxy(lambda: _request_ctx_stack.top.app) request = LocalProxy(lambda: _request_ctx_stack.top.request) session = LocalProxy(lambda: _request_ctx_stack.top.session) g = LocalProxy(lambda: _request_ctx_stack.top.g)
# -*- coding: utf-8 -*- """ flask.globals ~~~~~~~~~~~~~ Defines all the global objects that are proxies to the current active context. :copyright: (c) 2010 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ from functools import partial from werkzeug import LocalStack, LocalProxy def _lookup_object(name): top = _request_ctx_stack.top if top is None: raise RuntimeError('working outside of request context') return getattr(top, name) # context locals _request_ctx_stack = LocalStack() current_app = LocalProxy(partial(_lookup_object, 'app')) request = LocalProxy(partial(_lookup_object, 'request')) session = LocalProxy(partial(_lookup_object, 'session')) g = LocalProxy(partial(_lookup_object, 'g'))
import re from flask import current_app, Blueprint, _app_ctx_stack from werkzeug import LocalProxy, MultiDict, CombinedMultiDict from .compat import with_metaclass from collections import defaultdict import weakref _flacro_jinja = LocalProxy(lambda: current_app.jinja_env) _glo = LocalProxy(lambda: current_app.jinja_env.globals) ATTR_BLACKLIST = re.compile("mwhere|mname|mattr|macros|^_") class FlacroForMeta(type): def __new__(cls, name, bases, dct): new_class = super(FlacroForMeta, cls).__new__(cls, name, bases, dct) if not hasattr(cls, '_instances'): new_class._instances = defaultdict(weakref.WeakSet) if not hasattr(cls, '_manager'): cls._manager = {} cls._manager[new_class.__name__] = new_class return new_class def __init__(cls, name, bases, dct): if not hasattr(cls, '_registry'): cls._registry = {} else: cls._registry[name] = cls._instances super(FlacroForMeta, cls).__init__(name, bases, dct)
from functools import wraps # Third Party Libs from flask import g, has_request_context, request from itsdangerous import URLSafeTimedSerializer from werkzeug import LocalProxy # First Party Libs from fm.ext import config, redis from fm.http import Unauthorized from fm.models.user import User SESSION_KEY = 'fm:api:session:{0}' USER_SESSION_KEY = 'fm:api:user:session:{0}' current_user = LocalProxy(lambda: user_from_session()) def session_only_required(function): """ Decorator which requires that the view is accessable only to users with a valid session. """ @wraps(function) def wrapper(*args, **kwargs): user = user_from_session() if user is None: return Unauthorized() return function(*args, **kwargs) return wrapper
def ctx_prc(macro): return LocalProxy(lambda: getattr(macro, 'render', None))
def _dsres_list(self, name, offset=None, limit=None): query = querybuilder.select_paged(name, offset=offset, limit=limit) with self.db, self.db.cursor() as cur: cur.execute(query) for row in cur.fetchall(): yield self._row_to_obj(row) def _dsres_from_row(self, row): obj = row['configuration'] obj['_id'] = row['id'] obj['_ctime'] = row['ctime'] obj['_mtime'] = row['mtime'] return obj def _dsres_delete(self, name, obj_id): query = querybuilder.delete(name) with self.db, self.db.cursor() as cur: cur.execute(query, dict(id=obj_id)) def get_current_datacat(): """Get the "current" instance of the datacat app""" datacat = getattr(g, '_datacat', None) if datacat is None: datacat = g._datacat = DatacatCore(current_app.config) return datacat datacat_core = LocalProxy(get_current_datacat)
# -*- coding: utf-8 -*- """ lodgeit.utils ~~~~~~~~~~~~~ Serveral utilities used by LodgeIt. :copyright: 2008 by Christopher Grebs. :license: BSD """ from werkzeug import Local, LocalManager, LocalProxy #: context locals ctx = Local() _local_manager = LocalManager(ctx) #: local objects request = LocalProxy(ctx, 'request') application = LocalProxy(ctx, 'application')
from invenio.base.globals import cfg from invenio.base.i18n import _ from invenio.ext.sqlalchemy import db from invenio.modules.accounts.models import User from invenio.modules.collections.models import Collection from invenio.modules.records.models import Record as Bibrec from invenio.modules.search.views.search import response_formated_records from werkzeug import LocalProxy from .forms import AttachTagForm, CreateTagForm, DetachTagForm, EditTagForm, \ TagAnnotationForm, validate_tag_exists, validate_user_owns_tag, validators from .models import WtgTAG, WtgTAGRecord, wash_tag # Uset settings user_settings = LocalProxy(lambda: current_user['settings'].get( 'webtag', cfg['CFG_WEBTAG_DEFAULT_USER_SETTINGS'])) blueprint = Blueprint('webtag', __name__, url_prefix='/yourtags', template_folder='templates', static_folder='static') default_breadcrumb_root(blueprint, '.webaccount.tags') @blueprint.route('/', methods=['GET', 'POST']) @blueprint.route('/display', methods=['GET', 'POST']) @blueprint.route('/display/cloud', methods=['GET', 'POST']) @login_required @templated('tags/display_cloud.html')