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()
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 = {}
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()
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
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
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
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)
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...')
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
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))
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()
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)
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)
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)
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)
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)
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
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
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)
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'
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 = {}
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)
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
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]
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
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()
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
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
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 "<b>Test Autoescape On</b>" in resp, resp
def before_validate(self, remainder, params): page_param = params.pop(self.page_param, None) if page_param: try: page = int(page_param) if page < 1: raise ValueError except ValueError: page = 1 else: page = 1 try: paginators_data = request.paginators except: paginators_data = request.paginators = { '_tg_paginators_params': {} } paginators_data['_tg_paginators_params'][self.page_param] = page_param paginators_data[self.name] = paginator = Bunch() paginator.paginate_page = page or 1 items_per_page = params.pop(self.items_per_page_param, None) if items_per_page: try: items_per_page = min(int(items_per_page), self.max_items_per_page) if items_per_page < 1: raise ValueError except ValueError: items_per_page = self.items_per_page else: items_per_page = self.items_per_page paginator.paginate_items_per_page = items_per_page paginator.paginate_params = params.copy() paginator.paginate_params.update( paginators_data['_tg_paginators_params']) if items_per_page != self.items_per_page: paginator.paginate_params[ self.items_per_page_param] = items_per_page