def setup_translator(language='en', registry=None): mediacore_i18n_path = os.path.join(os.path.dirname(mediacore.__file__), 'i18n') translator = Translator(language, dict(mediacore=mediacore_i18n_path)) # not sure why but sometimes pylons.translator is not a StackedObjectProxy # but just a regular Translator. if not hasattr(pylons.translator, '_push_object'): pylons.translator = StackedObjectProxy() if registry is None: registry = pylons.request.environ['paste.registry'] registry.replace(pylons.translator, translator)
def setup_translator(language='en', registry=None, locale_dirs=None): if not locale_dirs: locale_dirs = get_locale_dirs(pylons.config) translator = Translator(language, locale_dirs=locale_dirs) # not sure why but sometimes pylons.translator is not a StackedObjectProxy # but just a regular Translator. if not hasattr(pylons.translator, '_push_object'): pylons.translator = StackedObjectProxy() if registry is None: registry = pylons.request.environ['paste.registry'] register_instance(registry, 'translator', translator)
def fake_request(pylons_config, server_name='mediadrop.example', language='en', method='GET', request_uri='/', post_vars=None): app_globals = pylons_config['pylons.app_globals'] pylons.app_globals._push_object(app_globals) if post_vars and method.upper() != 'POST': raise ValueError('You must not specify post_vars for request method %r' % method) wsgi_environ = create_wsgi_environ('http://%s%s' % (server_name, request_uri), method.upper(), request_body=post_vars) request = Request(wsgi_environ, charset='utf-8') request.language = language request.settings = app_globals.settings pylons.request._push_object(request) response = Response(content_type='application/xml', charset='utf-8') pylons.response._push_object(response) session = SessionObject(wsgi_environ) pylons.session._push_object(session) routes_url = URLGenerator(pylons_config['routes.map'], wsgi_environ) pylons.url._push_object(routes_url) # TODO: Use ContextObj() for Pylons 0.10 tmpl_context = AttribSafeContextObj() tmpl_context.paginators = Bunch() pylons.tmpl_context._push_object(tmpl_context) # some parts of Pylons (e.g. Pylons.controllers.core.WSGIController) # use the '.c' alias instead. pylons.c = pylons.tmpl_context paste_registry = Registry() paste_registry.prepare() engines = create_tw_engine_manager(app_globals) host_framework = PylonsHostFramework(engines=engines) paste_registry.register(tw.framework, host_framework) mediacore_i18n_path = os.path.join(os.path.dirname(mediacore.__file__), 'i18n') translator = Translator(language, dict(mediacore=mediacore_i18n_path)) # not sure why but sometimes pylons.translator is not a StackedObjectProxy # but just a regular Translator. if not hasattr(pylons.translator, '_push_object'): pylons.translator = StackedObjectProxy() paste_registry.replace(pylons.translator, translator) wsgi_environ.update({ 'pylons.pylons': pylons, 'paste.registry': paste_registry, }) return request
class WSGIRequest(object): """WSGI Request API Object This object represents a WSGI request with a more friendly interface. This does not expose every detail of the WSGI environment, and attempts to express nothing beyond what is available in the environment dictionary. The only state maintained in this object is the desired ``charset``, its associated ``errors`` handler, and the ``decode_param_names`` option. The incoming parameter values will be automatically coerced to unicode objects of the ``charset`` encoding when ``charset`` is set. The incoming parameter names are not decoded to unicode unless the ``decode_param_names`` option is enabled. When unicode is expected, ``charset`` will overridden by the the value of the ``Content-Type`` header's charset parameter if one was specified by the client. The class variable ``defaults`` specifies default values for ``charset``, ``errors``, and ``langauge``. These can be overridden for the current request via the registry. The ``language`` default value is considered the fallback during i18n translations to ensure in odd cases that mixed languages don't occur should the ``language`` file contain the string but not another language in the accepted languages list. The ``language`` value only applies when getting a list of accepted languages from the HTTP Accept header. This behavior is duplicated from Aquarium, and may seem strange but is very useful. Normally, everything in the code is in "en-us". However, the "en-us" translation catalog is usually empty. If the user requests ``["en-us", "zh-cn"]`` and a translation isn't found for a string in "en-us", you don't want gettext to fallback to "zh-cn". You want it to just use the string itself. Hence, if a string isn't found in the ``language`` catalog, the string in the source code will be used. *All* other state is kept in the environment dictionary; this is essential for interoperability. You are free to subclass this object. """ defaults = StackedObjectProxy(default=dict(charset=None, errors='replace', decode_param_names=False, language='en-us')) def __init__(self, environ): self.environ = environ # This isn't "state" really, since the object is derivative: self.headers = EnvironHeaders(environ) defaults = self.defaults._current_obj() self.charset = defaults.get('charset') if self.charset: # There's a charset: params will be coerced to unicode. In that # case, attempt to use the charset specified by the browser browser_charset = self.determine_browser_charset() if browser_charset: self.charset = browser_charset self.errors = defaults.get('errors', 'strict') self.decode_param_names = defaults.get('decode_param_names', False) self._languages = None body = environ_getter('wsgi.input') scheme = environ_getter('wsgi.url_scheme') method = environ_getter('REQUEST_METHOD') script_name = environ_getter('SCRIPT_NAME') path_info = environ_getter('PATH_INFO') def urlvars(self): """ Return any variables matched in the URL (e.g., ``wsgiorg.routing_args``). """ if 'paste.urlvars' in self.environ: return self.environ['paste.urlvars'] elif 'wsgiorg.routing_args' in self.environ: return self.environ['wsgiorg.routing_args'][1] else: return {} urlvars = property(urlvars, doc=urlvars.__doc__) def is_xhr(self): """Returns a boolean if X-Requested-With is present and a XMLHttpRequest""" return self.environ.get('HTTP_X_REQUESTED_WITH', '') == 'XMLHttpRequest' is_xhr = property(is_xhr, doc=is_xhr.__doc__) def host(self): """Host name provided in HTTP_HOST, with fall-back to SERVER_NAME""" return self.environ.get('HTTP_HOST', self.environ.get('SERVER_NAME')) host = property(host, doc=host.__doc__) def languages(self): """Return a list of preferred languages, most preferred first. The list may be empty. """ if self._languages is not None: return self._languages acceptLanguage = self.environ.get('HTTP_ACCEPT_LANGUAGE') langs = ACCEPT_LANGUAGE.parse(self.environ) fallback = self.defaults.get('language', 'en-us') if not fallback: return langs if fallback not in langs: langs.append(fallback) index = langs.index(fallback) langs[index + 1:] = [] self._languages = langs return self._languages languages = property(languages, doc=languages.__doc__) def _GET(self): return parse_dict_querystring(self.environ) def GET(self): """ Dictionary-like object representing the QUERY_STRING parameters. Always present, if possibly empty. If the same key is present in the query string multiple times, a list of its values can be retrieved from the ``MultiDict`` via the ``getall`` method. Returns a ``MultiDict`` container or a ``UnicodeMultiDict`` when ``charset`` is set. """ params = self._GET() if self.charset: params = UnicodeMultiDict(params, encoding=self.charset, errors=self.errors, decode_keys=self.decode_param_names) return params GET = property(GET, doc=GET.__doc__) def _POST(self): return parse_formvars(self.environ, include_get_vars=False) def POST(self): """Dictionary-like object representing the POST body. Most values are encoded strings, or unicode strings when ``charset`` is set. There may also be FieldStorage objects representing file uploads. If this is not a POST request, or the body is not encoded fields (e.g., an XMLRPC request) then this will be empty. This will consume wsgi.input when first accessed if applicable, but the raw version will be put in environ['paste.parsed_formvars']. Returns a ``MultiDict`` container or a ``UnicodeMultiDict`` when ``charset`` is set. """ params = self._POST() if self.charset: params = UnicodeMultiDict(params, encoding=self.charset, errors=self.errors, decode_keys=self.decode_param_names) return params POST = property(POST, doc=POST.__doc__) def params(self): """Dictionary-like object of keys from POST, GET, URL dicts Return a key value from the parameters, they are checked in the following order: POST, GET, URL Additional methods supported: ``getlist(key)`` Returns a list of all the values by that key, collected from POST, GET, URL dicts Returns a ``MultiDict`` container or a ``UnicodeMultiDict`` when ``charset`` is set. """ params = MultiDict() params.update(self._POST()) params.update(self._GET()) if self.charset: params = UnicodeMultiDict(params, encoding=self.charset, errors=self.errors, decode_keys=self.decode_param_names) return params params = property(params, doc=params.__doc__) def cookies(self): """Dictionary of cookies keyed by cookie name. Just a plain dictionary, may be empty but not None. """ return get_cookie_dict(self.environ) cookies = property(cookies, doc=cookies.__doc__) def determine_browser_charset(self): """ Determine the encoding as specified by the browser via the Content-Type's charset parameter, if one is set """ charset_match = _CHARSET_RE.search(self.headers.get( 'Content-Type', '')) if charset_match: return charset_match.group(1) def match_accept(self, mimetypes): """Return a list of specified mime-types that the browser's HTTP Accept header allows in the order provided.""" return desired_matches(mimetypes, self.environ.get('HTTP_ACCEPT', '*/*')) def __repr__(self): """Show important attributes of the WSGIRequest""" pf = pformat msg = '<%s.%s object at 0x%x method=%s,' % \ (self.__class__.__module__, self.__class__.__name__, id(self), pf(self.method)) msg += '\nscheme=%s, host=%s, script_name=%s, path_info=%s,' % \ (pf(self.scheme), pf(self.host), pf(self.script_name), pf(self.path_info)) msg += '\nlanguages=%s,' % pf(self.languages) if self.charset: msg += ' charset=%s, errors=%s,' % (pf( self.charset), pf(self.errors)) msg += '\nGET=%s,' % pf(self.GET) msg += '\nPOST=%s,' % pf(self.POST) msg += '\ncookies=%s>' % pf(self.cookies) return msg
class WSGIResponse(object): """A basic HTTP response with content, headers, and out-bound cookies The class variable ``defaults`` specifies default values for ``content_type``, ``charset`` and ``errors``. These can be overridden for the current request via the registry. """ defaults = StackedObjectProxy( default=dict(content_type='text/html', charset='utf-8', errors='strict', headers={'Cache-Control': 'no-cache'})) def __init__(self, content=b'', mimetype=None, code=200): self._iter = None self._is_str_iter = True self.content = content self.headers = HeaderDict() self.cookies = SimpleCookie() self.status_code = code defaults = self.defaults._current_obj() if not mimetype: mimetype = defaults.get('content_type', 'text/html') charset = defaults.get('charset') if charset: mimetype = '%s; charset=%s' % (mimetype, charset) self.headers.update(defaults.get('headers', {})) self.headers['Content-Type'] = mimetype self.errors = defaults.get('errors', 'strict') def __str__(self): """Returns a rendition of the full HTTP message, including headers. When the content is an iterator, the actual content is replaced with the output of str(iterator) (to avoid exhausting the iterator). """ if self._is_str_iter: content = ''.join(self.get_content()) else: content = str(self.content) return '\n'.join(['%s: %s' % (key, value) for key, value in self.headers.headeritems()]) \ + '\n\n' + content def __call__(self, environ, start_response): """Convenience call to return output and set status information Conforms to the WSGI interface for calling purposes only. Example usage: .. code-block:: python def wsgi_app(environ, start_response): response = WSGIResponse() response.write("Hello world") response.headers['Content-Type'] = 'latin1' return response(environ, start_response) """ status_text = STATUS_CODE_TEXT[self.status_code] status = '%s %s' % (self.status_code, status_text) response_headers = self.headers.headeritems() for c in self.cookies.values(): response_headers.append(('Set-Cookie', c.output(header=''))) start_response(status, response_headers) is_file = isinstance(self.content, file) if 'wsgi.file_wrapper' in environ and is_file: return environ['wsgi.file_wrapper'](self.content) elif is_file: return iter(lambda: self.content.read(), '') return self.get_content() def determine_charset(self): """ Determine the encoding as specified by the Content-Type's charset parameter, if one is set """ charset_match = _CHARSET_RE.search(self.headers.get( 'Content-Type', '')) if charset_match: return charset_match.group(1) def has_header(self, header): """ Case-insensitive check for a header """ warnings.warn( 'WSGIResponse.has_header is deprecated, use ' 'WSGIResponse.headers.has_key instead', DeprecationWarning, 2) return self.headers.has_key(header) def set_cookie(self, key, value='', max_age=None, expires=None, path='/', domain=None, secure=None, httponly=None): """ Define a cookie to be sent via the outgoing HTTP headers """ self.cookies[key] = value for var_name, var_value in [('max_age', max_age), ('path', path), ('domain', domain), ('secure', secure), ('expires', expires), ('httponly', httponly)]: if var_value is not None and var_value is not False: self.cookies[key][var_name.replace('_', '-')] = var_value def delete_cookie(self, key, path='/', domain=None): """ Notify the browser the specified cookie has expired and should be deleted (via the outgoing HTTP headers) """ self.cookies[key] = '' if path is not None: self.cookies[key]['path'] = path if domain is not None: self.cookies[key]['domain'] = domain self.cookies[key]['expires'] = 0 self.cookies[key]['max-age'] = 0 def _set_content(self, content): if not isinstance(content, (six.binary_type, six.text_type)): self._iter = content if isinstance(content, list): self._is_str_iter = True else: self._is_str_iter = False else: self._iter = [content] self._is_str_iter = True content = property(lambda self: self._iter, _set_content, doc='Get/set the specified content, where content can ' 'be: a string, a list of strings, a generator function ' 'that yields strings, or an iterable object that ' 'produces strings.') def get_content(self): """ Returns the content as an iterable of strings, encoding each element of the iterator from a Unicode object if necessary. """ charset = self.determine_charset() if charset: return encode_unicode_app_iter(self.content, charset, self.errors) else: return self.content def wsgi_response(self): """ Return this WSGIResponse as a tuple of WSGI formatted data, including: (status, headers, iterable) """ status_text = STATUS_CODE_TEXT[self.status_code] status = '%s %s' % (self.status_code, status_text) response_headers = self.headers.headeritems() for c in self.cookies.values(): response_headers.append(('Set-Cookie', c.output(header=''))) return status, response_headers, self.get_content() # The remaining methods partially implement the file-like object interface. # See http://docs.python.org/lib/bltin-file-objects.html def write(self, content): if not self._is_str_iter: raise IOError( "This %s instance's content is not writable: (content " 'is an iterator)' % self.__class__.__name__) self.content.append(content) def flush(self): pass def tell(self): if not self._is_str_iter: raise IOError( 'This %s instance cannot tell its position: (content ' 'is an iterator)' % self.__class__.__name__) return sum([len(chunk) for chunk in self._iter]) ######################################## ## Content-type and charset def charset__get(self): """ Get/set the charset (in the Content-Type) """ header = self.headers.get('content-type') if not header: return None match = _CHARSET_RE.search(header) if match: return match.group(1) return None def charset__set(self, charset): if charset is None: del self.charset return try: header = self.headers.pop('content-type') except KeyError: raise AttributeError( "You cannot set the charset when no content-type is defined") match = _CHARSET_RE.search(header) if match: header = header[:match.start()] + header[match.end():] header += '; charset=%s' % charset self.headers['content-type'] = header def charset__del(self): try: header = self.headers.pop('content-type') except KeyError: # Don't need to remove anything return match = _CHARSET_RE.search(header) if match: header = header[:match.start()] + header[match.end():] self.headers['content-type'] = header charset = property(charset__get, charset__set, charset__del, doc=charset__get.__doc__) def content_type__get(self): """ Get/set the Content-Type header (or None), *without* the charset or any parameters. If you include parameters (or ``;`` at all) when setting the content_type, any existing parameters will be deleted; otherwise they will be preserved. """ header = self.headers.get('content-type') if not header: return None return header.split(';', 1)[0] def content_type__set(self, value): if ';' not in value: header = self.headers.get('content-type', '') if ';' in header: params = header.split(';', 1)[1] value += ';' + params self.headers['content-type'] = value def content_type__del(self): try: del self.headers['content-type'] except KeyError: pass content_type = property(content_type__get, content_type__set, content_type__del, doc=content_type__get.__doc__)
from pyramid.events import NewRequest from pyramid.exceptions import NotFound from pyramid.url import route_url from pyramid.session import UnencryptedCookieSessionFactoryConfig from pyramid.threadlocal import get_current_request from pyramid.view import AppendSlashNotFoundViewFactory from pyramid import httpexceptions # API from pyramid_jinja2 import renderer_factory as j2_renderer_factory class Namespace(object): pass request = StackedObjectProxy() application = StackedObjectProxy() g = StackedObjectProxy() class Groundhog(object): def __init__(self, package, session_key=None, authn_policy=None, authz_policy=None, **settings): self.package = package self.session_key = session_key self.g = Namespace() session_factory = UnencryptedCookieSessionFactoryConfig(session_key, )
import warnings import beaker.container as container from beaker.exceptions import InvalidCacheBackendError from beaker.util import coerce_cache_params import beaker.util as util try: from paste.registry import StackedObjectProxy beaker_cache = StackedObjectProxy(name="Cache Manager") except: beaker_cache = None clsmap = { 'memory':container.MemoryContainer, 'dbm':container.DBMContainer, 'file':container.FileContainer, } try: import beaker.ext.memcached as memcached clsmap['ext:memcached'] = memcached.MemcachedContainer except InvalidCacheBackendError: pass try: import beaker.ext.database as database clsmap['ext:database'] = database.DatabaseContainer except InvalidCacheBackendError: pass class Cache(object):
# Setup Paste, if available. This needs to stay in the same module as # FacebookWSGIMiddleware below. try: from paste.registry import StackedObjectProxy from webob.exc import _HTTPMove try: from string import Template except ImportError: from webob.util.stringtemplate import Template from webob import html_escape except ImportError: pass else: facebook = StackedObjectProxy(name="PyFacebook Facebook Connection") class CanvasRedirect(_HTTPMove): """This is for canvas redirects.""" title = "See Other" code = 200 html_template_obj = Template('<fb:redirect url="${location}" />') def html_body(self, environ): return self.html_template_obj.substitute(location=self.detail) class FacebookWSGIMiddleware(object): """This is WSGI middleware for Facebook."""
import Cookie from datetime import datetime, timedelta import hmac import md5 import os import random import re import sys import time import UserDict import warnings try: from paste.registry import StackedObjectProxy beaker_session = StackedObjectProxy(name="Beaker Session") except: beaker_session = None from beaker.container import namespace_registry from beaker.util import coerce_session_params __all__ = ['SignedCookie', 'Session'] class SignedCookie(Cookie.BaseCookie): "extends python cookie to give digital signature support" def __init__(self, secret, input=None): self.secret = secret Cookie.BaseCookie.__init__(self, input)
# -*- coding: UTF-8 -*- ############################################# ## (C)opyright by Dirk Holtwick, 2008 ## ## All rights reserved ## ############################################# from webob import Request, Response from paste.registry import StackedObjectProxy import logging log = logging.getLogger(__name__) c = StackedObjectProxy(name="C") g = StackedObjectProxy(name="G") h = StackedObjectProxy(name="H") # cache = StackedObjectProxy(name="Cache") request = req = StackedObjectProxy(name="Request") response = resp = StackedObjectProxy(name="Response") session = StackedObjectProxy(name="Session") config = StackedObjectProxy(name="Config") class Decorator(object): """ A helper for creating decorators. It can be called these ways: @Decorator @Decorator() @Decorator(some=1, args=2)
] def __figure_version(): try: from pkg_resources import require import os # NOTE: this only works when the package is either installed, # or has an .egg-info directory present (i.e. wont work with raw SVN checkout) info = require('pylons')[0] if os.path.dirname(os.path.dirname(__file__)) == info.location: return info.version else: return '(not installed)' except: return '(not installed)' __version__ = __figure_version() c = StackedObjectProxy(name="C") g = StackedObjectProxy(name="G") cache = StackedObjectProxy(name="Cache") request = StackedObjectProxy(name="Request") response = StackedObjectProxy(name="Response") session = StackedObjectProxy(name="Session") buffet = StackedObjectProxy(name="Buffet") translator = StackedObjectProxy(name="Translator")
# -*- coding: utf-8 -*- # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """The allura package""" from paste.registry import StackedObjectProxy credentials = StackedObjectProxy(name='credentials')
http://www.bootstrappy.org/ You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies. """ import pkg_resources from paste.registry import StackedObjectProxy from paste.config import DispatchingConfig __all__ = [ 'app_globals', 'cache', 'config', 'request', 'response', 'session', 'tmpl_context', 'url' ] app_globals = StackedObjectProxy(name="app_globals") cache = StackedObjectProxy(name="cache") request = StackedObjectProxy(name="request") response = StackedObjectProxy(name="response") session = StackedObjectProxy(name="session") tmpl_context = StackedObjectProxy(name="tmpl_context") url = StackedObjectProxy(name="url") template = StackedObjectProxy(name="template") permissions = StackedObjectProxy(name="permissions") auth_id = StackedObjectProxy(name="auth_id") config = DispatchingConfig()
from paste.registry import RegistryManager, StackedObjectProxy from webob.dec import wsgify from webob.exc import HTTPNotFound from gargant.context import context_builder, NotFound from gargant.dispatch import NotMatched from gargant.respondent import respondent condition = StackedObjectProxy() def make_gargant(usercondition, route, tree): @wsgify def _gargant(request): request.environ['paste.registry'].register(condition, usercondition) condition['request'] = request condition['route'] = route condition['tree'] = tree try: node = tree(request.environ) except NotMatched: raise HTTPNotFound('condition did not matched any cases.') case = route[node.case] renderer_name, contexter = case[0] sideeffects = case[1:] tree_path = reversed(list(node))
# Create a render callable for the cache function def render_template(): # Pull in extra vars if needed globs = extra_vars or {} # Grab a template reference template = _LOOKUP.get_template(template_name) return literal(template.render_unicode(**globs)) return _cached_template(template_name, render_template, cache_key=cache_key, cache_type=cache_type, cache_expire=cache_expire) _CACHE = StackedObjectProxy(name="cache") def build_url(url, **params): return '%s?%s' % (url, urlencode(params)) config = DispatchingConfig() def setup_config(appconfig): config.push_process_config(appconfig) def _cached_template(template_name, render_func, ns_options=(), cache_key=None, cache_type=None, cache_expire=None,
from linotp.lib.ext.pbkdf2 import PBKDF2 from Crypto.Hash import HMAC from Crypto.Hash import SHA as SHA1 from Crypto.Hash import SHA256 as SHA256 from linotp.lib.ocra import OcraSuite from linotp.lib.crypt import kdf2, createActivationCode, check from linotp.lib.crypt import geturandom from linotp.lib.crypt import encrypt, decrypt from linotp.lib.crypt import check from paste.registry import RegistryManager, StackedObjectProxy myglobal = StackedObjectProxy() from linotp.tests import * from linotp.lib.selftest import isSelfTest from simplejson import loads from datetime import datetime from datetime import timedelta import time import os try: import json except ImportError: import simplejson as json
# This file is part of Moksha. # Copyright (C) 2008-2010 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from paste.registry import StackedObjectProxy # Per-request topic callbacks registered by rendered live widgets livewidgets = StackedObjectProxy(name="livewidgets")
] def __figure_version(): try: from pkg_resources import require import os # NOTE: this only works when the package is either installed, # or has an .egg-info directory present (i.e. wont work with raw # SVN checkout) info = require('pylons')[0] if os.path.dirname(os.path.dirname(__file__)) == info.location: return info.version else: return '(not installed)' except: return '(not installed)' __version__ = __figure_version() app_globals = StackedObjectProxy(name="app_globals") cache = StackedObjectProxy(name="cache") request = StackedObjectProxy(name="request") response = StackedObjectProxy(name="response") session = StackedObjectProxy(name="session") tmpl_context = StackedObjectProxy(name="tmpl_context") url = StackedObjectProxy(name="url") translator = StackedObjectProxy(name="translator")
try: from paste.registry import StackedObjectProxy beaker_session = StackedObjectProxy(name="Beaker Session") beaker_cache = StackedObjectProxy(name="Cache Manager") except: beaker_cache = None beaker_session = None from beaker.cache import CacheMiddleware as DeprecatedCacheMiddleware from beaker.session import SessionMiddleware as DeprecatedSessionMiddleware class CacheMiddleware(DeprecatedCacheMiddleware): deprecated = False cache = beaker_cache class SessionMiddleware(DeprecatedSessionMiddleware): deprecated = False session = beaker_session def session_filter_factory(global_conf, **kwargs): def filter(app): return SessionMiddleware(app, global_conf, **kwargs) return filter def session_filter_app_factory(app, global_conf, **kwargs): return SessionMiddleware(app, global_conf, **kwargs)
from blazeweb.globals import settings, rg from blazeweb.hierarchy import visitmods from blazeweb.utils import registry_has_object from paste.registry import StackedObjectProxy from sqlalchemy import engine_from_config, MetaData from sqlalchemy.orm import sessionmaker, scoped_session, Session db = StackedObjectProxy(name="db") class DebugSession(Session): """ This was helpful in troubleshooting a deadlock condition that occured during testing. """ def __init__(self, *args, **kwargs): self.dbg_label = kwargs.pop('dbg_label') Session.__init__(self, *args, **kwargs) def execute(self, clause, params=None, mapper=None, **kw): try: print('E>>> ' + self.dbg_label) return Session.execute(self, clause, params, mapper, **kw) finally: print('<<<E') def _flush(self, objects=None): try: print('>>>F ' + self.dbg_label) return Session._flush(self, objects) finally: