Ejemplo n.º 1
0
class GlobalsModule(types.ModuleType):
    __all__ = ('_dataset_ctx_stack', 'dataset', 'data', 'aggregation',
               'resource')
    __package__ = __package__
    __loader__ = __loader__
    __name__ = __name__
    __path__ = __file__
    if '__initializing__' in locals():
        __initializing__ = __initializing__
    _dataset_ctx_stack = LocalStack()
    _resource_ctx_stack = LocalStack()

    def __init__(self, *args, **kwargs):
        super(GlobalsModule, self).__init__(*args, **kwargs)
        self.dataset = LocalProxy(self._lookup_dataset)
        self.data = LocalProxy(self._lookup_data_mapping)
        self.aggregation = LocalProxy(self._lookup_data_aggregation)
        self.resource = LocalProxy(self._lookup_resource_stack)

    def _lookup_resource_stack(self):
        top = self._resource_ctx_stack.top
        if top is None:
            raise RuntimeError('working outside of resource context')
        return top

    def _lookup_dataset(self):
        top = self._dataset_ctx_stack.top
        if top is None:
            raise RuntimeError('working outside of dataset context')
        return top

    def _lookup_data_mapping(self):
        return self.dataset.g

    def _lookup_data_aggregation(self):
        return self.data.aggregation

    def _lookup_named_graph(self, name):
        return self.data[name]

    def __getattr__(self, name):
        from werkzeug.local import LocalProxy
        from functools import partial
        if name not in self.__dict__:
            self.__dict__[name] = LocalProxy(
                partial(self._lookup_named_graph, name))

        return self.__dict__[name]
Ejemplo n.º 2
0
 def declare(self, token):
     self.guard.acquire()
     try:
         if token not in self.locals:
             self.locals[token] = LocalStack()
         return StackProxy(self, token)
     finally:
         self.guard.release()
Ejemplo n.º 3
0
def localstack_demo():
    ls = LocalStack()
    a = ls.push(100)
    # a.pop()
    b = ls.push(120)
    print(a, b)
    print(ls.pop())
    print(ls.pop())
Ejemplo n.º 4
0
def test_local():
    """測試線程"""
    def get_item():
        return test_stack.pop()

    test_stack = LocalStack()
    test_stack.push({'abc': '123'})
    test_stack.push({'abc': '1234'})

    item = get_item()
    print(item['abc'])
    print(item['abc'])

    test_stack = LocalStack()
    test_stack.push({'abc': '123'})
    test_stack.push({'abc': '1234'})
    item = LocalProxy(get_item)
    print(item['abc'])
    print(item['abc'])
Ejemplo n.º 5
0
 def __init__(self):
     self.__url_map = Map([
         Rule('/', endpoint='hello')
         # Rule('/<short_id>', endpoint='follow_short_link'),
         # Rule('/<short_id>+', endpoint='short_link_details')
     ])
     self.logger = loadLogging(self.logger)
     self.is_run = False
     self.__view_functions = dict()
     self.__localstack = LocalStack()
     self.__read_config()
Ejemplo n.º 6
0
def test_local_stack():
    """ 函数的代理 """
    ls = LocalStack()
    for i in range(10):
        ls.push(i)

    def get_num():
        return ls.pop()

    # LocalProxy 每次调用get_num函数, 并返回
    lp = LocalProxy(get_num)
    for _ in range(10):
        print(lp)
Ejemplo n.º 7
0
def local_proxy_test1():
    from werkzeug.local import LocalStack
    user_stack = LocalStack()
    user_stack.push({'name': 'Bob'})
    user_stack.push({'name': 'John'})

    def get_user():
        # do something to get User object and return it
        return user_stack.pop()

    # 直接调用函数获取user对象
    user = get_user()
    print user['name']
    print user['name']
Ejemplo n.º 8
0
def local_proxy_test2():
    from werkzeug.local import LocalStack, LocalProxy
    user_stack = LocalStack()
    user_stack.push({'name': 'Bob'})
    user_stack.push({'name': 'John'})

    def get_user():
        # do something to get User object and return it
        return user_stack.pop()

    # 通过LocalProxy使用user对象
    user = LocalProxy(get_user)
    print user['name']
    print user['name']
Ejemplo n.º 9
0
    def test_coroutine_localstack(self):

        ctx = LocalStack()
        patch_local(ctx)

        @coroutine
        def other_context():
            ctx.push(45)
            return ctx.top

        ctx.push(40)

        fut = asyncio.ensure_future(other_context())
        yield from fut
        self.assertEqual(ctx.top, 40)
        self.assertNotEqual(ctx.top, fut.result())
        self.assertEqual(fut.result(), 45)
Ejemplo n.º 10
0
def test1():

    stack = LocalStack()

    stack.push(1)
    stack.push(2)
    stack.push(3)
    stack.push(4)
    stack.push(5)

    print(stack.pop())
    print(stack.pop())
    print(stack.pop())
    print(stack.pop())
    print(stack.pop())
    print(stack.pop())
    print(stack.pop())
Ejemplo n.º 11
0
class Connection(object):

    __ctx = LocalStack()

    def __getattr__(self, name):
        if self.__ctx.top is None:
            self.connect()
        return getattr(self.__ctx.top, name)

    def connect(self):
        if self.__ctx.top is None:
            db = Database(
                    name=settings.DATABASE_NAME,
                    host=settings.DATABASE_HOST,
                    port=settings.DATABASE_PORT,
                    user=settings.DATABASE_USER,
                    password=settings.DATABASE_PASSWORD)
            self.__ctx.push(db)
        self.__ctx.top.connect()

    def close(self):
        if self.__ctx.top is not None:
            self.__ctx.top.close()
            self.__ctx.pop()
Ejemplo n.º 12
0
# This file is part of Flask-PluginEngine.
# Copyright (C) 2014-2017 CERN
#
# Flask-PluginEngine is free software; you can redistribute it
# and/or modify it under the terms of the Revised BSD License.

from werkzeug.local import LocalStack, LocalProxy

_plugin_ctx_stack = LocalStack()

#: Proxy to the currently active plugin
current_plugin = LocalProxy(lambda: _plugin_ctx_stack.top)
Ejemplo n.º 13
0
    top = _request_ctx_stack.top
    if top is None:
        raise RuntimeError(_request_ctx_err_msg)
    return getattr(top, name)


def _lookup_app_object(name):
    top = _app_ctx_stack.top
    if top is None:
        raise RuntimeError(_app_ctx_err_msg)
    return getattr(top, name)


def _find_app():
    top = _app_ctx_stack.top
    if top is None:
        raise RuntimeError(_app_ctx_err_msg)
    return top.app


# context locals
_request_ctx_stack = LocalStack()  # 请求上下文的数据结构
_app_ctx_stack = LocalStack()  # 应用上下文的数据结构
current_app = LocalProxy(_find_app)  # 从这个开始的4个,都是全局变量,他们其实通过代理上下文来实现的

# request = LocalProxy(_request_ctx_stack.top.request) = LocalProxy (_request_ctx_stack._local[stack][-1].request)
request = LocalProxy(partial(_lookup_req_object, 'request'))

session = LocalProxy(partial(_lookup_req_object, 'session'))

g = LocalProxy(partial(_lookup_app_object, 'g'))
Ejemplo n.º 14
0
from wsgiref.simple_server import make_server
from werkzeug.wrappers import Request as RequestBase, Response as ResponseBase
from werkzeug.local import LocalStack, LocalProxy
import re
import logging as log
import json

_request_context_stack = LocalStack()
request = LocalProxy(lambda: _request_context_stack.top.request)


class Request(RequestBase):
    def __init__(self, environ):
        RequestBase.__init__(self, environ)


class Response(ResponseBase):
    default_mimetype = 'text/html'


class RequestContext(object):
    def __init__(self, environ):
        self.request = Request(environ)
        self.response = Response()

    def __enter__(self):
        _request_context_stack.push(self)

    def __exit__(self, exc_type, exc_val, exc_tb):
        _request_context_stack.pop()
Ejemplo n.º 15
0
""":mod:`kinsumer.globals` --- Defines all the global contexts
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

"""
from functools import partial

from werkzeug.local import LocalProxy, LocalStack


def __lookup_shard_object(name):
    top = _shard_ctx_stack.top
    if top is None:
        raise RuntimeError('Working outside of shard context.')
    return getattr(top, name)


def __find_consumer():
    top = _consumer_ctx_stack.top
    if top is None:
        raise RuntimeError('Working outside of consumer context.')
    return top.consumer


_shard_ctx_stack = LocalStack()
_consumer_ctx_stack = LocalStack()
current_consumer = LocalProxy(__find_consumer)
shard = LocalProxy(partial(__lookup_shard_object, 'shard'))
Ejemplo n.º 16
0
class Context(LocalStack):
    pass


def _lookup_context():
    top = _context_stack.top
    if top is None:
        raise RuntimeError('Working outside of browser context.')
    return top


def _copy_or_create_context():
    if _context_stack.top:
        return copy(_context_stack.top)
    else:
        return Context()


@contextmanager
def browser_context():
    context = _copy_or_create_context()
    _context_stack.push(context)
    try:
        yield
    finally:
        _context_stack.pop()


_context_stack = LocalStack()
context = LocalProxy(_lookup_context)
Ejemplo n.º 17
0
from flask.signals import template_rendered, request_started, request_finished
from webtest import (TestApp as BaseTestApp, TestRequest as BaseTestRequest,
                     TestResponse as BaseTestResponse)

try:
    from flask_sqlalchemy import connection_stack
except ImportError:
    connection_stack = None

try:
    # Available starting with Flask 0.10
    from flask.signals import message_flashed
except ImportError:
    message_flashed = None

_session_scope_stack = LocalStack()


class SessionScope(object):
    """Session scope, being pushed, changes the value of
    :func:`.scopefunc` and, as a result, calls to `db.session`
    are proxied to the new underlying session.
    When popped, removes the current session and swap the value of
    :func:`.scopefunc` to the one that was before.

    :param db: :class:`flask_sqlalchemy.SQLAlchemy` instance
    """
    def __init__(self, db):
        self.db = db

    def push(self):
Ejemplo n.º 18
0
        if self in r:
            self._handle_request_noblock()
        当有请求进来后触发处理当前请求的逻辑,这是调用__call__的第一步
        但其绑定是在run方法中的run_simple中
        """
        print("environ:", environ)
        print("start_response:", start_response)
        return self.wsgi_app(environ, start_response)


###################################################################
#                     全局上下文变量定义(context locals)
# 说明:
#   - 此处全局的 g, session, 需要深入理解
#   - 需要深入去看 werkzeug.LocalStack() 的实现 Local-->LocalStack-->LocalProxy 这三个的关系参考下面的链接
#   https://www.jianshu.com/p/3f38b777a621,https://blog.csdn.net/barrysj/article/details/51519254
#   python中有threading local处理方式,在多线程环境中将变量按照线程id区分,由于协程在Python web中广泛使用,所以threading local不再满足需要
#   local中优先使用greenlet协程,其次是线程id。localstack相当于在本协程(线程)中将数据以stack的形式存储(通过封装local来实现)。
#   LocalProxy就是local的代理。重载了很多运算符,方便变量值得动态更新和获取,
#
###################################################################

_request_ctx_stack = LocalStack()  # 依赖 werkzeug.LocalStack 模块-->`Local`堆栈
current_app = LocalProxy(lambda: _request_ctx_stack.top.app)
request = LocalProxy(lambda: _request_ctx_stack.top.request)

#   - g: 请求上下文 栈对象
#   - session: 请求上下文 栈对象
session = LocalProxy(lambda: _request_ctx_stack.top.session)  # flash()函数中引用
g = LocalProxy(lambda: _request_ctx_stack.top.g)
Ejemplo n.º 19
0
"""
    Created by ZZXUN on 2018/8/6
"""
import threading
import time

from werkzeug.local import Local, LocalStack

__author__ = "ZZXUN"


class A:
    b = 1


my_job = LocalStack()
my_job.push(1)

# 两个线程实例化两个栈,彼此数据不干扰


def worker():
    print("in new thread before push, value is :" + str(my_job.top))
    my_job.push(2)
    print("in new thread after push, value is :" + str(my_job.top))


new_t = threading.Thread(target=worker, name="zzx")
new_t.start()

time.sleep(1)
Ejemplo n.º 20
0
from werkzeug.local import LocalProxy, LocalStack
from jinja2 import BaseLoader, ChoiceLoader, TemplateNotFound
from flask import current_app, json, request as flask_request, _app_ctx_stack

from . import verifier
from . import logger
from .convert import to_date, to_time, to_timedelta
import collections
import random

request = LocalProxy(lambda: current_app.ask.request)
session = LocalProxy(lambda: current_app.ask.session)
version = LocalProxy(lambda: current_app.ask.version)
context = LocalProxy(lambda: current_app.ask.context)
convert_errors = LocalProxy(lambda: current_app.ask.convert_errors)
current_stream = LocalStack()

_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.

    Ask object maps Alexa Requests to flask view functions and handles Alexa sessions.
    The constructor is passed a Flask App instance, and URL endpoint.
    The Flask instance allows the convienient API of endpoints and their view functions,
    so that Alexa requests may be mapped with syntax similar to a typical Flask server.
    Route provides the entry point for the skill, and must be provided if an app is given.

    Keyword Arguments:
            app {Flask object} -- App instance - created with Flask(__name__) (default: {None})
Ejemplo n.º 21
0
print(f'In {current_thread().name} {obj.__ident_func__()} obj.a is', obj.a)


def manipulate():
    obj.a = 2
    print(f'In {current_thread().name} {obj.__ident_func__()} obj.a is', obj.a)


newThread = Thread(name='newThread', target=manipulate)
newThread.start()
time.sleep(1)

print(f'In {current_thread().name} {obj.__ident_func__()} obj.a is', obj.a)

# 线程隔离栈的试验
stk = LocalStack()
stk.push(1)
print(f'In {current_thread().name} {stk._local.__ident_func__()} stk.top is',
      stk.top)


def manipulateStack():
    print(
        f'In {current_thread().name} {stk._local.__ident_func__()} stk.top is',
        stk.top)


newTread2 = Thread(name='newThread2', target=manipulateStack)
newTread2.start()
time.sleep(1)
Ejemplo n.º 22
0
# coding=utf-8

import random

from flask import Flask, g, render_template
from chapter3.section3.ext import db
from chapter3.section3.users import User
from werkzeug.local import LocalProxy, LocalStack

app = Flask(__name__, template_folder='../../templates')
app.config.from_object('chapter3.section3.config')
db.init_app(app)

_user_stack = LocalStack()


def get_current_user():
    top = _user_stack.top
    if top is None:
        raise RuntimeError()
    return top

current_user = LocalProxy(get_current_user)

@app.before_first_request
def setup():
    db.drop_all()
    db.create_all()
    fake_users = [
        User('xiaoming'),
        User('dongqihong'),
Ejemplo n.º 23
0
# -*- coding: utf-8 -*-
"""
  Created by Cphayim at 2018/6/27 23:20
"""
import threading
import time

from werkzeug.local import LocalStack

__author__ = 'Cphayim'

my_stack = LocalStack()
my_stack.push(1)
print('in main thread after push, value is: ' + str(my_stack.top))


def worker():
    # 新线程
    print('in new thread before push, value is: ' + str(my_stack.top))
    my_stack.push(2)
    print('in new thread after push, value is: ' + str(my_stack.top))


new_t = threading.Thread(target=worker, name='q')
new_t.start()
time.sleep(1)
# 主线程
print('finally, in main thread value is: ' + str(my_stack.top))
Ejemplo n.º 24
0
from contextlib import contextmanager
from functools import wraps

from werkzeug.local import LocalProxy, LocalStack

_additional_ctx_stack = LocalStack()

__all__ = ("current_additions", "Additional", "AdditionalManager")


@LocalProxy
def current_additions():
    """
    Proxy to the currently added requirements
    """
    rv = _additional_ctx_stack.top
    if rv is None:
        return None
    return rv[1]


def _isinstance(f):
    @wraps(f)
    def check(self, other):
        if not isinstance(other, Additional):
            return NotImplemented
        return f(self, other)

    return check

Ejemplo n.º 25
0
        return self.__dict__.pop(name, default)

    def setdefault(self, name, default=None):
        return self.__dict__.setdefault(name, default)

    def __contains__(self, item):
        return item in self.__dict__

    def __iter__(self):
        return iter(self.__dict__)


#####################################################################
# application context

_app_ctx_stack = LocalStack()


def _lookup_app_object(name):
    top = _app_ctx_stack.top
    if top is None:
        raise RuntimeError("Working outside of application context.")
    return getattr(top, name)


class AppContext(object):
    def __init__(self, app):
        self.app = app
        self.g = _AppCtxGlobals()

    def __enter__(self):
Ejemplo n.º 26
0
import time
import traceback
from contextlib import contextmanager

import click
from click import style
from werkzeug.local import LocalProxy
from werkzeug.local import LocalStack

_reporter_stack = LocalStack()
_build_buffer_stack = LocalStack()


def describe_build_func(func):
    self = getattr(func, "__self__", None)
    if self is not None and any(x.__name__ == "BuildProgram"
                                for x in self.__class__.__mro__):
        return self.__class__.__module__ + "." + self.__class__.__name__
    return func.__module__ + "." + func.__name__


class Reporter(object):
    def __init__(self, env, verbosity=0):
        self.env = env
        self.verbosity = verbosity

        self.builder_stack = []
        self.artifact_stack = []
        self.source_stack = []

    def push(self):
Ejemplo n.º 27
0
from contextlib import contextmanager
from jinja2 import Undefined
from werkzeug.local import LocalStack, LocalProxy

from lektor.reporter import reporter

_ctx_stack = LocalStack()


def url_to(*args, **kwargs):
    """Calculates a URL to another record."""
    ctx = get_ctx()
    if ctx is None:
        raise RuntimeError('No context found')
    return ctx.url_to(*args, **kwargs)


def get_asset_url(asset):
    """Calculates the asset URL relative to the current record."""
    ctx = get_ctx()
    if ctx is None:
        raise RuntimeError('No context found')
    asset = site_proxy.get_asset(asset)
    if asset is None:
        return Undefined('Asset not found')
    info = ctx.build_state.get_file_info(asset.source_filename)
    return '%s?h=%s' % (
        ctx.source.url_to('!' + asset.url_path),
        info.checksum[:8],
    )
Ejemplo n.º 28
0

def get_app_ctx_obj(name):
    top = _app_ctx_content.top
    if top is None:
        raise RuntimeError(app_ctx_error_msg)
    return getattr(top, name)


def get_current_app():
    top = _app_ctx_content.top
    if top is None:
        raise RuntimeError(app_ctx_error_msg)
    return top.app


def has_app_ctx():
    return _app_ctx_content.top is not None


def has_request_ctx():
    return _request_ctx_content.top is not None


_request_ctx_content = LocalStack()
_app_ctx_content = LocalStack()
request = LocalProxy(partial(get_request_obj, 'request'))
session = LocalProxy(partial(get_request_obj, 'session'))
g = LocalProxy(partial(get_app_ctx_obj, 'g'))
current_app = LocalProxy(get_current_app)
Ejemplo n.º 29
0
from werkzeug.local import LocalStack

l = LocalStack()
l.push(42)
l.push(23)

l.pop()
Ejemplo n.º 30
0
===============================
"""
from functools import partial
from werkzeug.local import LocalProxy, LocalStack


class _SharedRequestClass(object):
    pass


def _lookUpObjectInRequestContext(name):
    top = _requestContextStack.top
    if top is None:
        raise RuntimeError('ahixi...')
    return getattr(top, name)


def findApp():
    top = _appContextStack.top
    if top is None:
        raise RuntimeError('AppContext is none...')
    return top.app


_requestContextStack = LocalStack()
_appContextStack = LocalStack()
currentApp = LocalProxy(findApp)
request = LocalProxy(partial(_lookUpObjectInRequestContext, 'request'))
session = LocalProxy(partial(_lookUpObjectInRequestContext, 'session'))
shared = LocalProxy(partial(_lookUpObjectInRequestContext, 'shared'))