Example #1
0
def test_basic_local():
    """Basic local object support"""
    l = Local()
    l.foo = 0
    values = []

    def value_setter(idx):
        time.sleep(0.01 * idx)
        l.foo = idx
        time.sleep(0.02)
        values.append(l.foo)

    threads = [Thread(target=value_setter, args=(x,)) for x in [1, 2, 3]]
    for thread in threads:
        thread.start()
    time.sleep(0.2)
    assert sorted(values) == [1, 2, 3]

    def delfoo():
        del l.foo

    delfoo()
    assert_raises(AttributeError, lambda: l.foo)
    assert_raises(AttributeError, delfoo)

    release_local(l)
Example #2
0
def test_basic_local():
    """Basic local object support"""
    l = Local()
    l.foo = 0
    values = []

    def value_setter(idx):
        time.sleep(0.01 * idx)
        l.foo = idx
        time.sleep(0.02)
        values.append(l.foo)

    threads = [Thread(target=value_setter, args=(x, )) for x in [1, 2, 3]]
    for thread in threads:
        thread.start()
    time.sleep(0.2)
    assert sorted(values) == [1, 2, 3]

    def delfoo():
        del l.foo

    delfoo()
    assert_raises(AttributeError, lambda: l.foo)
    assert_raises(AttributeError, delfoo)

    release_local(l)
Example #3
0
def test_local_release():
    """Locals work without manager"""
    loc = Local()
    loc.foo = 42
    release_local(loc)
    assert not hasattr(loc, 'foo')

    ls = LocalStack()
    ls.push(42)
    release_local(ls)
    assert ls.top is None
Example #4
0
def test_local_release():
    """Locals work without manager"""
    loc = Local()
    loc.foo = 42
    release_local(loc)
    assert not hasattr(loc, "foo")

    ls = LocalStack()
    ls.push(42)
    release_local(ls)
    assert ls.top is None
Example #5
0
 def __init__(self, *providers, name: str = None):
     self.name = name
     self._providers = providers
     self.importer = Importer()  # Can't inject it, obviously.
     self.service_conf = {}
     self.app_conf = {}
     self.service_instances = {}
     self.service_classes = {}
     self.factory_classes = {}
     self._namespaces = {}
     self._service_names = []
     self._local = Local()
Example #6
0
def test_custom_idents():
    """Local manager supports custom ident functions"""
    ident = 0
    local = Local()
    stack = LocalStack()
    mgr = LocalManager([local, stack], ident_func=lambda: ident)

    local.foo = 42
    stack.push({"foo": 42})
    ident = 1
    local.foo = 23
    stack.push({"foo": 23})
    ident = 0
    assert local.foo == 42
    assert stack.top["foo"] == 42
    stack.pop()
    assert stack.top is None
    ident = 1
    assert local.foo == 23
    assert stack.top["foo"] == 23
    stack.pop()
    assert stack.top is None
Example #7
0
class Context(object):
    locals = Local()
    local_manager = LocalManager([locals])
    current_context = locals('context')

    def __init__(self, app, environ=None, request=None, args=None):
        self.app = app
        self.environ = environ
        self.request = request
        self.args = args
        self.response = None

    def __enter__(self):
        self.locals.context = self
        for fn in self.app.get_hook_functions('context-start'):
            fn(self)
        return self

    def __exit__(self, type, value, traceback):
        for fn in self.app.get_hook_functions('context-end'):
            fn(self)
        del self.locals.context
Example #8
0
# -*- coding: utf-8 -*-
from werkzeug import Local, LocalManager
from werkzeug.routing import Map, Rule
from os import path
from urlparse import urlparse
from werkzeug import Response
from jinja2 import Environment, FileSystemLoader
from json import dumps

local = Local()
local_manager = LocalManager([local])
application = local('application')

url_map = Map([Rule('/static/<file>', endpoint='static', build_only=True)])


def expose(rule, **kw):
    def decorate(f):
        kw['endpoint'] = f.__name__ + " " + f.__module__
        url_map.add(Rule(rule, **kw))
        return f

    return decorate


def url_for(endpoint, _external=False, **values):
    return local.url_adapter.build(endpoint, values, force_external=_external)


ALLOWED_SCHEMES = frozenset(['http'])
TEMPLATE_PATH = 'template'
Example #9
0
from uliweb.utils.common import (pkg, log, import_attr, 
    myimport, wraps, norm_path)
import uliweb.utils.pyini as pyini
from uliweb.i18n import gettext_lazy, i18n_ini_convertor
from uliweb.utils.localproxy import LocalProxy, Global
from uliweb import UliwebError

#from rules import Mapping, add_rule
import rules

try:
    set
except:
    from sets import Set as set

local = Local()
__global__ = Global()
local_manager = LocalManager([local])
url_map = Map()
static_views = []
use_urls = False
url_adapters = {}
__app_dirs__ = {}
__app_alias__ = {}
_xhr_redirect_json = True

r_callback = re.compile(r'^[\w_]+$')
#Initialize pyini env
pyini.set_env({
    'env':{'_':gettext_lazy, 'gettext_lazy':gettext_lazy},
    'convertors':i18n_ini_convertor,
Example #10
0
from uliweb.utils.common import (pkg, log, import_attr, 
    myimport, wraps, norm_path)
import uliweb.utils.pyini as pyini
from uliweb.i18n import gettext_lazy, i18n_ini_convertor
from uliweb.utils.localproxy import LocalProxy, Global
from uliweb import UliwebError

#from rules import Mapping, add_rule
import rules

try:
    set
except:
    from sets import Set as set

local = Local()
__global__ = Global()
local_manager = LocalManager([local])
url_map = Map()
static_views = []
use_urls = False
url_adapters = {}
__app_dirs__ = {}
__app_alias__ = {}
_xhr_redirect_json = True

r_callback = re.compile(r'^[\w_]+$')
#Initialize pyini env
pyini.set_env({
    'env':{'_':gettext_lazy, 'gettext_lazy':gettext_lazy},
    'convertors':i18n_ini_convertor,
Example #11
0
                                 norm_path)
from uliweb.utils._compat import string_types
import uliweb.utils.pyini as pyini
from uliweb.i18n import gettext_lazy, i18n_ini_convertor
from uliweb.utils.localproxy import LocalProxy, Global
from uliweb import UliwebError

#from rules import Mapping, add_rule
from . import rules

try:
    set
except:
    from sets import Set as set

local = Local()
local.request = None
local.response = None
__global__ = Global()
local_manager = LocalManager([local])
url_map = Map(strict_slashes=False)
static_views = []
use_urls = False
url_adapters = {}
__app_dirs__ = {}
__app_alias__ = {}
_xhr_redirect_json = True

r_callback = re.compile(r'^[\w_]+$')
#Initialize pyini env
pyini.set_env({
Example #12
0
File: app.py Project: peper/tipfy
# Werkzeug Swiss knife.
# Need to import werkzeug first otherwise py_zipimport fails.
import werkzeug
from werkzeug import (
    Local,
    Request as BaseRequest,
    Response as BaseResponse,
    cached_property,
    import_string,
    redirect as base_redirect,
)
from werkzeug.exceptions import HTTPException, InternalServerError, abort

#: Context-local.
local = Local()
#: A proxy to the active handler for a request. This is intended to be used by
#: functions called out of a handler context. Usage is generally discouraged:
#: it is preferable to pass the handler as argument when possible and only use
#: this as last alternative -- when a proxy is really needed.
#:
#: For example, the :func:`tipfy.utils.url_for` function requires the current
#: request to generate a URL. As its purpose is to be assigned to a template
#: context or other objects shared between requests, we use `current_handler`
#: there to dynamically get the currently active handler.
current_handler = local("current_handler")

from . import default_config
from .config import Config, REQUIRED_VALUE
from .routing import Router, Rule
from .utils import json_decode
Example #13
0
from uliweb.utils.common import (pkg, log, import_attr, 
    myimport, wraps, norm_path)
import uliweb.utils.pyini as pyini
from uliweb.i18n import gettext_lazy, i18n_ini_convertor
from uliweb.utils.localproxy import LocalProxy, Global
from uliweb import UliwebError

#from rules import Mapping, add_rule
import rules

try:
    set
except:
    from sets import Set as set

local = Local()
local.request = None
local.response = None
__global__ = Global()
local_manager = LocalManager([local])
url_map = Map()
static_views = []
use_urls = False
url_adapters = {}
__app_dirs__ = {}
__app_alias__ = {}
_xhr_redirect_json = True

r_callback = re.compile(r'^[\w_]+$')
#Initialize pyini env
pyini.set_env({
Example #14
0
File: repo.py Project: dpq/spooce
from sqlalchemy.dialects import mysql
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.types import String, Boolean, DateTime, Text, Integer
from sqlalchemy import Table, Column, MetaData, ForeignKey, Index, desc, create_engine
from simplejson import dumps as tojson, loads as fromjson

import hashlib, hmac, secret, gzip, cStringIO, StringIO, zlib

import secret, default
from werkzeug import Local, LocalManager

configfile = ""
engine = None
local = Local()
local_manager = LocalManager([local])
Session = local('Session')
Package = local('Package')
local.Session = []
local.Package = []

def __Package_init__(self, lang, appcode, versioncode, key, body):
    self.lang = lang
    self.appcode = appcode
    self.versioncode = versioncode
    mac = hmac.new(secret.PackageSecret, None, hashlib.md5)
    mac.update(key)
    self.key = mac.digest().encode('base64').strip()
    self.body = body
Example #15
0
File: warden.py Project: dpq/spooce
from sqlalchemy.dialects import mysql
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.types import String, Boolean, DateTime, Text, Integer
from sqlalchemy import Table, Column, MetaData, Index, desc, create_engine
from urllib2 import urlopen
import secret, default
from geventmemcache.client import Memcache
from werkzeug import Local, LocalManager

import smtplib
from email.mime.text import MIMEText
from simplejson import dumps as tojson, loads as fromjson

local = Local()
local_manager = LocalManager([local])
Session = local('Session')
User = local('User')
MethodEmail = local('MethodEmail')
local.Session = []
local.User = []
local.MethodEmail = []

configfile = ""
engine = None

def __Invite_init__(self, pin):
    self.pin = pin
    self.uid = 0
Example #16
0
from uliweb.utils.common import (pkg, log, import_attr, myimport, wraps,
                                 norm_path)
import uliweb.utils.pyini as pyini
from uliweb.i18n import gettext_lazy, i18n_ini_convertor
from uliweb.utils.localproxy import LocalProxy, Global
from uliweb import UliwebError

#from rules import Mapping, add_rule
import rules

try:
    set
except:
    from sets import Set as set

local = Local()
__global__ = Global()
local_manager = LocalManager([local])
url_map = Map()
static_views = []
use_urls = False
url_adapters = {}
__app_dirs__ = {}
__app_alias__ = {}
_xhr_redirect_json = True

r_callback = re.compile(r'^[\w_]+$')
#Initialize pyini env
pyini.set_env({
    'env': {
        '_': gettext_lazy,
Example #17
0
from rest_framework import serializers
from rest_framework.utils.model_meta import get_field_info
from rest_framework.serializers import raise_errors_on_nested_writes
from rest_framework.utils import model_meta

from api_basebone.core import drf_field, gmeta
from api_basebone.core.fields import JSONField
from jsonfield import JSONField as OriginJSONField
from rest_framework.fields import JSONField as DrfJSONField
from api_basebone.restful.const import CLIENT_END_SLUG, MANAGE_END_SLUG
from api_basebone.utils import module
from api_basebone.utils.gmeta import get_gmeta_config_by_key
from werkzeug import Local

rfu_modes = Local()

compare_funcs = {
    '=': lambda a, b: a == b,
    '==': lambda a, b: a == b,
    '===': lambda a, b: a == b,
    '>': lambda a, b: a > b,
    '<': lambda a, b: a < b,
    'in': lambda a, b: a in b,
    'include': lambda a, b: b in a,
}

class BulkCreateListSerializer(serializers.ListSerializer):
    def create(self, validated_data):
        result = [self.child.create(attrs) for attrs in validated_data]        
        # self.child.Meta.model.objects.bulk_create(result, ignore_conflicts=False)
Example #18
0
    myimport, wraps, norm_path)
from uliweb.utils._compat import string_types
import uliweb.utils.pyini as pyini
from uliweb.i18n import gettext_lazy, i18n_ini_convertor
from uliweb.utils.localproxy import LocalProxy, Global
from uliweb import UliwebError

#from rules import Mapping, add_rule
from . import rules

try:
    set
except:
    from sets import Set as set

local = Local()
local.request = None
local.response = None
__global__ = Global()
local_manager = LocalManager([local])
url_map = Map()
static_views = []
use_urls = False
url_adapters = {}
__app_dirs__ = {}
__app_alias__ = {}
_xhr_redirect_json = True

r_callback = re.compile(r'^[\w_]+$')
#Initialize pyini env
pyini.set_env({
Example #19
0
    :license: BSD, see LICENSE.txt for more details.
"""
import logging
import os
import urlparse
from wsgiref.handlers import CGIHandler

# Werkzeug Swiss knife.
# Need to import werkzeug first otherwise py_zipimport fails.
import werkzeug
from werkzeug import (Local, Request as BaseRequest, Response as BaseResponse,
    cached_property, import_string, redirect as base_redirect)
from werkzeug.exceptions import HTTPException, InternalServerError, abort

#: Context-local.
local = Local()
#: A proxy to the active handler for a request. This is intended to be used by
#: functions called out of a handler context. Usage is generally discouraged:
#: it is preferable to pass the handler as argument when possible and only use
#: this as last alternative -- when a proxy is really needed.
#:
#: For example, the :func:`tipfy.utils.url_for` function requires the current
#: request to generate a URL. As its purpose is to be assigned to a template
#: context or other objects shared between requests, we use `current_handler`
#: there to dynamically get the currently active handler.
current_handler = local('current_handler')
#: Same as current_handler, only for the active WSGI app.
current_app = local('current_app')

from . import default_config
from .config import Config, REQUIRED_VALUE
Example #20
0
File: blob.py Project: dpq/spooce
from gevent.wsgi import WSGIServer
from ConfigParser import ConfigParser

from werkzeug import Request, Response
import logging, os, new, re, getopt, sys

from sqlalchemy.dialects import mysql
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.types import String, Boolean, DateTime, Text, Integer
from sqlalchemy import Table, Column, MetaData, ForeignKey, Index, desc, create_engine
from simplejson import dumps as tojson, loads as fromjson
from werkzeug import Local, LocalManager

import magic, default, secret
local = Local()
local_manager = LocalManager([local])

configfile = ""
engine = None
Session = local('Session')
FileEntry = local('FileEntry')
local.Session = []
local.FileEntry = []

def __FileEntry_init__(self, id, filename, filetype):
    self.id = id
    self.filename = filename
    self.filename = filetype

Example #21
0
from flask import Flask
from werkzeug import Local, LocalProxy

import os
if 'SERVER_SOFTWARE' in os.environ:
    from app.conf import baidu as conf
    from bae.api import logging
else:
    from app.conf import mysql as conf
    import logging

    
app = Flask(__name__)
app.debug = True
app.config.from_object(conf)
l = Local()
baelogger = logging.getLogger(__name__)
from models.database import db_session, Base

l.session = db_session

if 'SERVER_SOFTWARE' in os.environ:
    from app import views
   
else:
    from app.views.api import *
    



Example #22
0
# -*- 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')
Example #23
0
import logging
import sys
import time
from collections import defaultdict
from werkzeug import Local, LocalManager
from werkzeug.exceptions import HTTPException, InternalServerError, NotFound, _ProxyException

# fragment taken from timeit module
if sys.platform == "win32":
    # On Windows, the best timer is time.clock()
    timer = time.clock
else:
    # On most other platforms the best timer is time.time()
    timer = time.time

local = Local()
local_manager = LocalManager([local])
logging.basicConfig(stream=local('error_stream'))
local.error_stream = sys.stderr

# prevent the werkzeug logger from propagating messages because it has its own output scheme
#logging.getLogger('werkzeug').propagate = False

from modulo.actions import all_of, any_of, opt
from modulo.wrappers import Request, Response

def run_everything(tree, request):
    t0 = timer()
    handler = tree.handle(request, defaultdict(dict)) # This is where the parameter list gets constructed
    if handler is None:
        raise NotFound()