コード例 #1
0
 def edit(self):
     user = request.identity['user']
     user_data, user_avatar = get_user_data(user)
     user_data = Bunch(((fieldid, info[1]) for fieldid, info in user_data.items()))
     return dict(user=user, profile_css=get_profile_css(config),
                 user_avatar=user_avatar,
                 form=create_user_form(user))
コード例 #2
0
    def __init__(self):
        """Creates some configuration defaults"""

        # Create a few bunches we know we'll use
        self.paths = Bunch()
        self.render_functions = Bunch()
        # And also very often...
        self.sa_auth = Bunch()
        self.sa_auth.translations = Bunch()

        #Set individual defaults
        self.auto_reload_templates = True
        self.auth_backend = None
        self.default_renderer = 'genshi'
        self.stand_alone = True

        # this is to activate the legacy renderers
        # legacy renderers are buffet interface plugins
        self.use_legacy_renderer = False

        self.use_toscawidgets = True
        self.use_transaction_manager = True
        self.use_toscawidgets2 = False

        #Registy for functions to be called on startup/teardown
        self.call_on_startup = []
        self.call_on_shutdown = []
        # The codes TG should display an error page for. All other HTTP errors are
        # sent to the client or left for some middleware above us to handle
        self.handle_status_codes = [403, 404]

        #override this variable to customize how the tw2 middleware is set up
        self.custom_tw2_config = {}
コード例 #3
0
ファイル: app_config.py プロジェクト: clsdaniel/tg2
        def load_environment(global_conf, app_conf):
            """Configure the Pylons environment via ``pylons.configuration.config``."""
            global_conf=Bunch(global_conf)
            app_conf=Bunch(app_conf)

            self.setup_paths()
            self.init_config(global_conf, app_conf)

            #Registers functions to be called at startup and shutdown
            #from self.call_on_startup and shutdown respectively.
            self.setup_startup_and_shutdown()

            self.setup_routes()
            self.setup_helpers_and_globals()
            self.setup_mimetypes()
            self.setup_auth()

            if not 'json' in self.renderers: self.renderers.append('json')

            for renderer in self.renderers:
                setup = getattr(self, 'setup_%s_renderer'%renderer, None)
                if setup:
                    setup()
                else:
                    raise Exception('This configuration object does not support the %s renderer'%renderer)

            self.setup_persistence()
コード例 #4
0
ファイル: test_rendering.py プロジェクト: WildC/SmartMailbox
def test_genshi_nameconstant():
    from genshi.template.astutil import ASTCodeGenerator, parse
    from tg.renderers.genshi import GenshiRenderer

    # This checks genshi gets monkeypatched to fix it on Py34 if option is provided
    GenshiRenderer.create(Bunch({
        'templating.genshi.name_constant_patch': True,
        'use_dotted_templatenames': False,
        'auto_reload_templates': False,
        'paths': Bunch({'templates': '/tmp'})
    }), None)
    assert hasattr(ASTCodeGenerator, 'visit_NameConstant')

    astgen = ASTCodeGenerator(parse('range(10)', mode='eval'))
    for n in (False, True, None):
        astgen._new_line()
        astgen.visit_NameConstant(Bunch(value=n))
        line = str(astgen.line)
        assert line == str(n), line

    astgen._new_line()
    try:
        astgen.visit_NameConstant(Bunch(value='HELLO_WORLD'))
    except Exception as e:
        assert 'Unknown NameConstant' in str(e)
    else:
        assert False
コード例 #5
0
        def load_environment(global_conf, app_conf):
            """Configure the Pylons environment via ``pylons.config``."""
            global_conf = Bunch(global_conf)
            app_conf = Bunch(app_conf)
            #Regesters functions to be called at startup and shutdown
            #from self.call_on_startup and shutdown respectively.
            self.setup_startup_and_shutdown()

            self.setup_paths()
            self.init_config(global_conf, app_conf)
            self.setup_routes()
            self.setup_helpers_and_globals()
            self.setup_mimetypes()

            if self.auth_backend == "sqlalchemy":
                self.setup_sa_auth_backend()

            if 'genshi' in self.renderers:
                self.setup_genshi_renderer()

            if 'chameleon_genshi' in self.renderers:
                self.setup_chameleongenshi_renderer()

            if 'mako' in self.renderers:
                self.setup_mako_renderer()

            if 'jinja' in self.renderers:
                self.setup_jinja_renderer()

            if self.use_legacy_renderer:
                self.setup_default_renderer()

            if self.use_sqlalchemy:
                self.setup_sqlalchemy()
コード例 #6
0
 def init_database(self):
     os.chdir(self.proj_dir)
     cmd = SetupAppCommand(Bunch(options=Bunch(verbose_level=1)), Bunch())
     try:
         cmd.run(Bunch(config_file='config:test.ini', section_name=None))
     except:
         # DB already initialised, ignore it.
         pass
コード例 #7
0
ファイル: app_cfg.py プロジェクト: samsemilia7/SAUCE
    def __init__(self):
        super(SauceAppConfig, self).__init__()

        self.package = sauce

        self.default_renderer = 'mako'
        self.renderers = ['mako', 'json']

        self.use_toscawidgets = False
        self.use_toscawidgets2 = True
        self.prefer_toscawidgets2 = True

        self.use_sqlalchemy = True
        self.model = model
        self.DBSession = model.DBSession

        self.register_hook('after_config', add_sentry_middleware)

        # Handle other status codes, too
        self.handle_status_codes = [400, 403, 404, 405]

        # Only perform session.rollback(), not transaction.abort()
        self['tgext.crud.abort_transactions'] = False

        # Configure the authentication backend

        self.auth_backend = 'sqlalchemy'
        self.sa_auth.dbsession = model.DBSession

        # what is the class you want to use to search for users in the database
        self.sa_auth.user_class = model.User
        # what is the class you want to use to search for groups in the database
        self.sa_auth.group_class = model.Group
        # what is the class you want to use to search for permissions in the database
        self.sa_auth.permission_class = model.Permission

        # override this if you would like to provide a different who plugin for
        # managing login and logout of your application
        self.sa_auth.form_plugin = None

        # override this if you are using a different charset for the login form
        self.sa_auth.charset = 'utf-8'

        # You may optionally define a page where you want users to be redirected to
        # on login and logout:
        self.sa_auth.post_login_url = '/post_login'
        self.sa_auth.post_logout_url = '/post_logout'

        # External authentication support
        # uncomment and configure for your needs if needed

        # Set to True here to disable some functionality that doesn't work anyway
        #self.externalauth = True

        self.login = Bunch(url='/login', referrer_key='came_from', qualified=False)
        self.logout = Bunch(url='/logout_handler', referrer_key=None, qualified=False)
コード例 #8
0
 def setup_paths(self):
     root = os.path.dirname(os.path.abspath(self.package.__file__))
     # The default paths:
     paths = Bunch(root=root,
                  controllers=os.path.join(root, 'controllers'),
                  static_files=os.path.join(root, 'public'),
                  templates=[os.path.join(root, 'templates')])
     # If the user defined custom paths, then use them instead of the
     # default ones:
     paths.update(self.paths)
     self.paths = paths
コード例 #9
0
 def setup_paths(self):
     root = os.path.dirname(os.path.abspath(self.package.__file__))
     # The default paths:
     paths = Bunch(root=root,
                   controllers=os.path.join(root, 'controllers'),
                   static_files=os.path.join(root, 'public'),
                   templates=[os.path.join(root, 'templates')])
     # If the user defined custom paths, then use them instead of the
     # default ones:
     paths.update(self.paths)
     self.paths = paths
コード例 #10
0
ファイル: base.py プロジェクト: buxx/tracim
def _get_clean_sa_auth(config):
    """
    Return the original sa_auth parameter. Consider Original as it's content before first fill in configuration.
    :param config: tg2 app config
    :return: original sa_auth parameter
    """
    global _original_sa_auth

    if _original_sa_auth is None:
        _original_sa_auth = dict(config.get("sa_auth"))

    sa_auth = Bunch()
    sa_auth.update(_original_sa_auth)
    return sa_auth
コード例 #11
0
ファイル: base.py プロジェクト: qyqx/tracim
def _get_clean_sa_auth(config):
    """
    Return the original sa_auth parameter. Consider Original as it's content before first fill in configuration.
    :param config: tg2 app config
    :return: original sa_auth parameter
    """
    global _original_sa_auth

    if _original_sa_auth is None:
        _original_sa_auth = dict(config.get('sa_auth'))

    sa_auth = Bunch()
    sa_auth.update(_original_sa_auth)
    return sa_auth
コード例 #12
0
ファイル: __init__.py プロジェクト: norsig/tracim
def setup_app(section_name=None):
    """Setup the application."""

    engine = config['tg.app_globals'].sa_engine
    inspector = reflection.Inspector.from_engine(engine)
    metadata = MetaData()

    logger.debug(setup_app, 'Before setup...')

    cmd = SetupAppCommand(Bunch(options=Bunch(verbose_level=1)), Bunch())
    logger.debug(setup_app, 'After setup, before run...')

    cmd.run(Bunch(config_file='config:test.ini', section_name=section_name))
    logger.debug(setup_app, 'After run...')
コード例 #13
0
ファイル: paths.py プロジェクト: FelixZFB/Web_front_end_study
    def _configure_paths(self, conf, app):
        try:
            package = conf['package'].__name__
        except (KeyError, AttributeError):
            package = None

        if package is not None:
            conf['package_name'] = conf['package'].__name__
        else:
            conf['package_name'] = None

        if package is None:
            # if we don't have a specified package (ES: we are in minimal mode)
            # we are unable to get paths from the package itself.
            paths = Bunch()
        else:
            root = os.path.dirname(os.path.abspath(conf['package'].__file__))
            paths = Bunch(root=root,
                          controllers=os.path.join(root, 'controllers'),
                          static_files=os.path.join(root, 'public'),
                          templates=[os.path.join(root, 'templates')])

        # If the user defined custom paths, then use them instead of the
        # default ones:
        paths.update(conf['paths'])

        # Ensure all paths are set, load default ones otherwise
        for key, val in self.DEFAULT_PATHS.items():
            paths.setdefault(key, val)

        conf['paths'] = paths
コード例 #14
0
ファイル: submissions.py プロジェクト: sleeepyjack/SAUCE
    def judge(self, *args, **kwargs):
        self._judge_permissions()

        c.judgement_form = JudgementForm(action=url('./judge_'))
        c.pygmentize = Pygmentize(
            lexer_name=self.submission.language.lexer_name if self.submission.language else '',
            filename=self.submission.filename,
            formatter_args=dict(
                linenos='table',
                lineanchors='line',
                linespans='line',
            )
        )

        options = Bunch(submission_id=self.submission.id,
            submission=self.submission,
            assignment_id=self.assignment.id,
            assignment=self.assignment)

        if self.submission.judgement:
            if self.submission.judgement.annotations:
                options['annotations'] = [dict(line=i, comment=ann)
                    for i, ann in sorted(self.submission.judgement.annotations.iteritems(), key=lambda x: x[0])]
            else:
                options['annotations'] = []
            options['comment'] = self.submission.judgement.comment
            options['corrected_source'] = self.submission.judgement.corrected_source
            options['grade'] = self.submission.judgement.grade

        return dict(page=['submissions', 'judge'], submission=self.submission, options=options)
コード例 #15
0
def test_jinja_custom_filters():
    # Simple test filter to get a md5 hash of a string
    def codify(value):
        try:
            from hashlib import md5
        except ImportError:
            from md5 import md5
        string_hash = md5(value)
        return string_hash.hexdigest()

    base_config = TestConfig(folder = 'rendering',
                             values = {'use_sqlalchemy': False,
                                       'pylons.helpers': Bunch(),
                                       'use_legacy_renderer': False,
                                       # this is specific to mako
                                       # to make sure inheritance works
                                       'use_dotted_templatenames': False,
                                       'pylons.tmpl_context_attach_args': False,
                                       'renderers':['jinja'],
                                       'jinja_filters': {'codify': codify}
                                       }
                             )
    app = app_from_config(base_config)
    resp = app.get('/jinja_filters')
    assert '8bb23e0b574ecb147536efacc864891b' in resp, resp
コード例 #16
0
ファイル: decorators.py プロジェクト: schneems/tg2
            def cached_call_controller(controller, remainder, params):
                req = request._current_obj()
                if self.key:
                    key_dict = req.args_params
                    if self.key != NoDefault:
                        if isinstance(self.key, (list, tuple)):
                            key_dict = dict((k, key_dict[k]) for k in key_dict)
                        else:
                            key_dict = {self.key: key_dict[self.key]}
                else:
                    key_dict = {}

                namespace, cache_key = create_cache_key(
                    func, key_dict, req.controller_state.controller)
                req._fast_setattr('caching',
                                  Bunch(namespace=namespace, key=cache_key))

                return _cached_call(next_caller,
                                    (controller, remainder, params), {},
                                    namespace,
                                    cache_key,
                                    expire=self.expire,
                                    type=self.type,
                                    starttime=starttime,
                                    cache_headers=self.cache_headers,
                                    cache_response=self.cache_response,
                                    cache_extra_args=self.beaker_options)
コード例 #17
0
def test_stacked_object_common_actions():
    regobj._push_object(Bunch({'hi': 'people'}))
    try:
        regobj['hi'] = 'val'
        assert regobj['hi'] == 'val'

        keys = []
        for k in regobj:
            keys.append(k)
        assert keys == ['hi'], keys

        assert len(regobj) == 1

        assert 'hi' in regobj

        assert bool(regobj) == True

        del regobj['hi']
        assert regobj.get('hi') is None

        regobj.someattr = 'val'
        assert regobj.someattr == 'val'

        del regobj.someattr
        assert getattr(regobj, 'someattr', None) is None
    finally:
        regobj._pop_object()
コード例 #18
0
 def index(self, **kw):
     categories = DBSession.query(app_model.Category).all()
     uncategorised = DBSession.query(Extraction).filter_by(
         category_id=None).all()
     categories += [Bunch(extractions=uncategorised, name="No Category")]
     return dict(categories=categories,
                 has_validation_errors=request.validation.errors,
                 new_form=CreateExtractionForm)
コード例 #19
0
def setup_noDB():
    base_config = TestConfig(folder='rendering',
                             values={
                                 'use_sqlalchemy': False,
                                 'pylons.helpers': Bunch(),
                                 'use_legacy_renderer': False,
                                 'use_dotted_templatenames': False,
                             })
    return app_from_config(base_config)
コード例 #20
0
ファイル: __init__.py プロジェクト: bkahlerventer/tgext.menu
def menu_variable_provider():
    menu_vars = Bunch(
        url_from_menu=url_from_menu,
        render_menu=render_menu,
        render_navbar=render_navbar,
        render_sidebar=render_sidebar,
    )

    try:
        from genshi import HTML
        menu_vars['HTML'] = HTML
    except ImportError:
        pass

    if app_variable_provider:
        menu_vars.update(app_variable_provider())

    return menu_vars
コード例 #21
0
ファイル: __init__.py プロジェクト: bkahlerventer/tgext.menu
def menu_variable_provider():
    menu_vars = Bunch (
        url_from_menu = url_from_menu,
        render_menu = render_menu,
        render_navbar = render_navbar,
        render_sidebar = render_sidebar,
    )
    
    try:
        from genshi import HTML
        menu_vars['HTML'] = HTML
    except ImportError:
        pass
    
    if app_variable_provider:
        menu_vars.update(app_variable_provider())

    return menu_vars
コード例 #22
0
    def before_render(self, remainder, params, output):
        paginator = request.paginators[self.name]
        if paginator.paginate_items_per_page < 0:
            if not getattr(tmpl_context, 'paginators', None):
                tmpl_context.paginators = Bunch()
            tmpl_context.paginators[self.name] = DisabledPager()
            return

        super(optional_paginate, self).before_render(remainder, params, output)
コード例 #23
0
    def setup(self):
        locals = RequestLocals()
        locals.request = Bunch()
        locals.app_globals = Bunch()
        locals.config = Bunch({'tg.app_globals':locals.app_globals,
                               'balanced_engines': {'all':{'master':'master',
                                                            'slave1':'slave1',
                                                            'slave2':'slave2'},
                                                    'master':'master',
                                                    'slaves':{'slave1':'slave1',
                                                              'slave2':'slave2'}}})

        #Register Global objects
        request_local.config._push_object(locals.config)
        request_local.context._push_object(locals)

        self.locals = locals
        self.session = BalancedSession()
        locals.config['DBSession'] = self.session
コード例 #24
0
def setup_noDB():
    base_config = TestConfig(folder = 'rendering',
                     values = {'use_sqlalchemy': False,
                               'pylons.helpers': Bunch(),
                               # we want to test the new renderer functions
                               'use_legacy_renderer': False,
                               # in this test we want dotted names support
                               'use_dotted_templatenames': True,
                               }
                             )
    return app_from_config(base_config)
コード例 #25
0
ファイル: test_configuration.py プロジェクト: wukele/tg2
    def setup(self):
        self.config = AppConfig()
        # set up some required paths and config settings
        # FIXME: these seem to be needed so that
        # other tests don't suffer - but that's a nasty
        # side-effect. setup for those tests actually needs
        # fixing.
        self.config.package = self.fake_package
        self.config['paths']['root'] = 'test'
        self.config['paths']['controllers'] = 'test.controllers'
        self.config.init_config({'cache_dir': '/tmp'}, {})

        config['paths']['static_files'] = "test"
        config["tg.app_globals"] = Bunch()
        config["use_sqlalchemy"] = False
        config["global_conf"] = Bunch()
        config["package"] = "test"
        config["call_on_shutdown"] = "foo"
        config["render_functions"] = Bunch()
        config['beaker.session.secret'] = 'some_secret'
コード例 #26
0
ファイル: app_config.py プロジェクト: clsdaniel/tg2
    def __init__(self):
        """Creates some configuration defaults"""

        # Create a few bunches we know we'll use
        self.paths = Bunch()
        self.render_functions = Bunch()
        # And also very often...
        self.sa_auth = Bunch()
        self.sa_auth.translations = Bunch()

        #Set individual defaults
        self.auto_reload_templates = True
        self.auth_backend = None
        self.default_renderer = 'genshi'
        self.stand_alone = True

        self.use_ming = False
        self.use_sqlalchemy = False
        self.use_transaction_manager = True
        self.use_toscawidgets = True
        self.use_toscawidgets2 = False
        self.prefer_toscawidgets2 = False

        # Registry for functions to be called on startup/teardown
        self.call_on_startup = []
        self.call_on_shutdown = []
        self.controller_wrappers = []
        self.hooks = dict(before_validate=[],
                          before_call=[],
                          before_render=[],
                          after_render=[],
                          before_render_call=[],
                          after_render_call=[],
                          before_config=[],
                          after_config=[])
        # The codes TG should display an error page for. All other HTTP errors are
        # sent to the client or left for some middleware above us to handle
        self.handle_status_codes = [403, 404]

        #override this variable to customize how the tw2 middleware is set up
        self.custom_tw2_config = {}
コード例 #27
0
def setup_noDB():
    base_config = TestConfig(
        folder='rendering',
        values={
            'use_sqlalchemy': False,
            'pylons.helpers': Bunch(),
            'use_legacy_renderer': False,
            # this is specific to mako
            # to make sure inheritance works
            'use_dotted_templatenames': False,
        })
    return app_from_config(base_config)
コード例 #28
0
ファイル: paths.py プロジェクト: TurboGears/tg2
    def _configure_paths(self, conf, app):
        try:
            package = conf['package'].__name__
        except (KeyError, AttributeError):
            package = None

        if package is not None:
            conf['package_name'] = conf['package'].__name__
        else:
            conf['package_name'] = None

        if package is None:
            # if we don't have a specified package (ES: we are in minimal mode)
            # we are unable to get paths from the package itself.
            paths = Bunch()
        else:
            root = os.path.dirname(os.path.abspath(conf['package'].__file__))
            paths = Bunch(
                root=root,
                controllers=os.path.join(root, 'controllers'),
                static_files=os.path.join(root, 'public'),
                templates=[os.path.join(root, 'templates')]
            )

        # If the user defined custom paths, then use them instead of the
        # default ones:
        paths.update(conf['paths'])

        # Ensure all paths are set, load default ones otherwise
        for key, val in self.DEFAULT_PATHS.items():
            paths.setdefault(key, val)

        conf['paths'] = paths
コード例 #29
0
    def before_render(self, remainder, params, output):
        if not isinstance(output, dict) or not self.name in output:
            return

        paginator = request.paginators[self.name]
        collection = output[self.name]
        page = Page(collection, paginator.paginate_page, paginator.paginate_items_per_page)
        page.kwargs = paginator.paginate_params
        if self.page_param != 'name':
            page.pager = partial(page.pager, page_param=self.page_param)
        if not getattr(tmpl_context, 'paginators', None):
            tmpl_context.paginators = Bunch()
        tmpl_context.paginators[self.name] = output[self.name] = page
コード例 #30
0
    def __init__(self):
        """Creates some configuration defaults"""

        # Create a few bunches we know we'll use
        self.paths = Bunch()
        self.render_functions = Bunch()
        # And also very often...
        self.sa_auth = Bunch()
        self.sa_auth.translations = Bunch()

        #Set individual defaults
        self.auto_reload_templates = True
        self.auth_backend = None
        self.default_renderer = 'genshi'
        self.serve_static = True
        self.stand_alone = True

        # this is to activate the legacy renderers
        # legacy renderers are buffet interface plugins
        self.use_legacy_renderer = False
        # if this is set to True the @expose decorator will be able to
        # specify template names using a dotted name that will be searched
        # in the python path. This option is used in tg.render.render_genshi
        # TODO: we should set this to False once we implement simple names
        # support in the @expose decorator as explained in #1942
        # for the moment only the dotted names notation is supported with the
        # new generation renderer functions
        self.use_dotted_templatenames = True

        self.use_toscawidgets = True
        self.use_transaction_manager = True

        #Registy for functions to be called on startup/teardown
        self.call_on_startup = []
        self.call_on_shutdown = []
        # The codes TG should display an error page for. All other HTTP errors are
        # sent to the client or left for some middleware above us to handle
        self.handle_status_codes = [403, 404]
コード例 #31
0
def force_load(resource):
    "Force the loading the of resource from the database"

    from sqlalchemy.orm import Query
    from bq.data_service.model import Taggable
    if isinstance(resource, tuple):
        parent = getattr(tg.request.bisque, 'parent', None)
        #log.debug ("invalidate: tuple using %s", parent) #provokes logging error
        if parent:
            resource = parent
            #log.debug ("CACHE parent %s", parent)
        else:
            # The a pure form i.e. /data_service/[image] with a POST
            if resource[0] == 'resource':
                # special case for POST to /data_service.. resource type is unknown so remove all
                resource = ('', resource[1])
            resource = Bunch(resource_uniq=None,
                             resource_type=resource[0],
                             permission="published")
    if isinstance(resource, Query):
        resource = resource.first()  #pylint: disable=no-member
    if isinstance(resource, Taggable):
        resource = resource.document  #pylint: disable=no-member
    return resource
コード例 #32
0
ファイル: render.py プロジェクト: clsdaniel/tg2
def _get_tg_vars():
    """Create a Bunch of variables that should be available in all templates.

    These variables are:

    WARNING: This function should not be called from outside of the render()
    code.  Please consider this function as private.

    quote_plus
        the urllib quote_plus function
    url
        the turbogears.url function for creating flexible URLs
    identity
        the current visitor's identity information
    session
        the current beaker.session if the session_filter.on it set
        in the app.cfg configuration file. If it is not set then session
        will be None.
    locale
        the default locale
    inputs
        input values from a form
    errors
        validation errors
    request
        the WebOb Request Object
    config
        the app's config object
    auth_stack_enabled
        A boolean that determines if the auth stack is present in the environment
    predicates
        The :mod:`tg.predicates` module.

    """

    req = tg.request._current_obj()
    conf = tg.config._current_obj()
    tmpl_context = tg.tmpl_context._current_obj()
    app_globals = tg.app_globals._current_obj()
    translator = tg.translator._current_obj()
    response = tg.response._current_obj()

    try:
        h = conf['package'].lib.helpers
    except AttributeError, ImportError:
        h = Bunch()
コード例 #33
0
def test_jinja_extensions():
    base_config = TestConfig(folder = 'rendering',
                             values = {'use_sqlalchemy': False,
                                       'pylons.helpers': Bunch(),
                                       'use_legacy_renderer': False,
                                       # this is specific to mako
                                       # to make sure inheritance works
                                       'use_dotted_templatenames': False,
                                       'pylons.tmpl_context_attach_args': False,
                                       'renderers':['jinja'],
                                       'jinja_extensions': ['jinja2.ext.do', 'jinja2.ext.i18n',
                                                            'jinja2.ext.with_', 'jinja2.ext.autoescape']
                                       }
                             )
    app = app_from_config(base_config)
    resp = app.get('/jinja_extensions')
    assert "<b>Autoescape Off</b>" in resp, resp
    assert "&lt;b&gt;Test Autoescape On&lt;/b&gt;" in resp, resp
コード例 #34
0
    def test_decoration_run_hooks_backward_compatibility(self):
        # TODO: Remove test when Decoration.run_hooks gets removed

        def func(*args, **kw):
            pass

        def hook(*args, **kw):
            hook.did_run = True

        hook.did_run = False

        milestones.renderers_ready.reach()
        tg.hooks.register('before_call', hook, controller=func)

        deco = Decoration.get_decoration(func)
        deco.run_hooks(Bunch(config=None), 'before_call')

        assert hook.did_run is True
コード例 #35
0
ファイル: render.py プロジェクト: Shamefox/tg2
def _get_tg_vars():
    """Create a Bunch of variables that should be available in all templates.

    These variables are:

    WARNING: This function should not be called from outside of the render()
    code.  Please consider this function as private.

    quote_plus
        the urllib quote_plus function
    url
        the turbogears.url function for creating flexible URLs
    identity
        the current visitor's identity information
    session
        the current beaker.session if the session_filter.on it set
        in the app.cfg configuration file. If it is not set then session
        will be None.
    locale
        the default locale
    inputs
        input values from a form
    errors
        validation errors
    request
        the WebOb Request Object
    config
        the app's config object
    auth_stack_enabled
        A boolean that determines if the auth stack is present in the environment
    predicates
        The :mod:`tg.predicates` module.

    """

    tgl = tg.request_local.context._current_obj()
    req = tgl.request
    conf = tgl.config
    tmpl_context = tgl.tmpl_context
    app_globals = tgl.app_globals
    translator = tgl.translator
    response = tgl.response
    session = tgl.session

    try:
        h = conf['package'].lib.helpers
    except (AttributeError, ImportError):
        h = Bunch()

    # TODO: Implement user_agent and other missing features.
    tg_vars = Bunch(
        config=tg.config,
        flash_obj=tg.flash,
        quote_plus=quote_plus,
        url=tg.url,
        # this will be None if no identity
        identity = req.environ.get('repoze.who.identity'),
        session = session,
        locale = req.plain_languages,
        errors = req.validation['errors'],
        inputs = req.validation['values'],
        request = req,
        auth_stack_enabled = 'repoze.who.plugins' in req.environ,
        predicates = predicates)

    root_vars = Bunch(
        c=tmpl_context,
        tmpl_context=tmpl_context,
        response=response,
        request=req,
        config=conf,
        app_globals=app_globals,
        g=app_globals,
        session=session,
        url=tg.url,
        helpers=h,
        h=h,
        tg=tg_vars,
        translator=translator,
        ungettext=tg.i18n.ungettext,
        _=tg.i18n.ugettext,
        N_=tg.i18n.gettext_noop)

    # Allow users to provide a callable that defines extra vars to be
    # added to the template namespace
    variable_provider = conf.get('variable_provider', None)
    if variable_provider:
        root_vars.update(variable_provider())
    return root_vars
コード例 #36
0
ファイル: render.py プロジェクト: lmacken/tg2
        errors=getattr(tmpl_context, "form_errors", {}),
        inputs=getattr(tmpl_context, "form_values", {}),
        request=req,
        auth_stack_enabled="repoze.who.plugins" in req.environ,
        predicates=predicates,
    )

    root_vars = Bunch(
        c=tmpl_context,
        tmpl_context=tmpl_context,
        response=response,
        request=req,
        config=conf,
        app_globals=app_globals,
        g=app_globals,
        url=tg.url,
        helpers=h,
        h=h,
        tg=tg_vars,
        translator=translator,
        ungettext=tg.i18n.ungettext,
        _=tg.i18n.ugettext,
        N_=tg.i18n.gettext_noop,
    )

    econf = conf["pylons.environ_config"]
    if "beaker.session" in req.environ or ("session" in econf and econf["session"] in req.environ):
        root_vars["session"] = tg.session._current_obj()

    # Allow users to provide a callable that defines extra vars to be
    # added to the template namespace