Beispiel #1
0
def render(template_name, form_fill=None, form_errors={}, extra_vars=None,
           cache_key=None, cache_type=None, cache_expire=None,
           method='xhtml'):
    # Create a render callable for the cache function
    def render_template():
        # Pull in extra vars if needed
        globs = extra_vars or {}

        # Second, get the globals
        globs.update(pylons_globals())
        globs['g'] = app_globals
        globs['_form_errors'] = form_errors

        # Grab a template reference
        template = globs['app_globals'].genshi_loader.load(template_name)
        stream = template.generate(**globs)
        if form_fill is not None:
            filler = HTMLFormFiller(data=form_fill)
            stream = stream | filler

        return literal(stream.render(method=method, encoding=None))

    return cached_template(template_name, render_template, cache_key=cache_key,
                           cache_type=cache_type, cache_expire=cache_expire,
                           ns_options=('method'), method=method)
Beispiel #2
0
def render_kajiki(template_name, extra_vars=None, cache_key=None,
                  cache_type=None, cache_expire=None, method='xhtml'):
    """Render a template with Kajiki

    Accepts the cache options ``cache_key``, ``cache_type``, and
    ``cache_expire`` in addition to method which are passed to Kajiki's
    render function.

    """
    # Create a render callable for the cache function
    def render_template():
        # Pull in extra vars if needed
        globs = extra_vars or {}

        # Second, get the globals
        globs.update(templating.pylons_globals())

        # Grab a template reference
        template = globs['app_globals'].kajiki_loader.load(template_name)

        return literal(template(globs).render())

    return templating.cached_template(template_name, render_template, cache_key=cache_key,
                           cache_type=cache_type, cache_expire=cache_expire,
                           ns_options=('method'), method=method)
Beispiel #3
0
def render(template_name, extra_vars=None, *pargs, **kwargs):
    '''Render a template and return the output.

    This is CKAN's main template rendering function.

    :params template_name: relative path to template inside registered tpl_dir
    :type template_name: str
    :params extra_vars: additional variables available in template
    :type extra_vars: dict
    :params pargs: DEPRECATED
    :type pargs: tuple
    :params kwargs: DEPRECATED
    :type kwargs: dict

    '''
    if pargs or kwargs:
        tb = inspect.getframeinfo(sys._getframe(1))
        log.warning(
            'Extra arguments to `base.render` are deprecated: ' +
            '<{0.filename}:{0.lineno}>'.format(tb)
        )

    if extra_vars is None:
        extra_vars = {}

    if not is_flask_request():
        renderer = _pylons_prepare_renderer(template_name, extra_vars,
                                            *pargs, **kwargs)
        return cached_template(template_name, renderer)

    return flask_render_template(template_name, **extra_vars)
Beispiel #4
0
def render_macro(template_name, name, cache_key=None,
                cache_type=None, cache_expire=None, **kwargs):       
    """Render a template with Jinja2

    Accepts the cache options ``cache_key``, ``cache_type``, and
    ``cache_expire``.

    """    
    # Create a render callable for the cache function
    def render_template():
        # Pull in extra vars if needed
        globs = {}
        
        # Second, get the globals
        globs.update(pylons_globals())
        
        # Grab a template reference
        template = \
            getattr(globs['app_globals'].jinja2_env.get_template(template_name).make_module(vars=globs), name)(**kwargs)
        return template        

    return cached_template(template_name, render_template, cache_key=cache_key,
                           cache_type=cache_type, cache_expire=cache_expire)
    
        
Beispiel #5
0
def render(template_name, extra_vars=None, cache_key=None, cache_type=None, 
           cache_expire=None, method='xhtml', loader_class=MarkupTemplate):
    
    def render_template():
        globs = extra_vars or {}
        globs.update(pylons_globals())
        globs['actions'] = model.Action

        # Using pylons.url() or pylons.url_for() directly destroys the
        # localisation stuff so we remove it so any bad templates crash
        # and burn
        del globs['url']

        template = globs['app_globals'].genshi_loader.load(template_name,
            cls=loader_class)
        stream = template.generate(**globs)
        
        for item in PluginImplementations(IGenshiStreamFilter):
            stream = item.filter(stream)
        
        return literal(stream.render(method=method, encoding=None, strip_whitespace=False))
    
    if 'Pragma' in response.headers:
        del response.headers["Pragma"]
    if cache_key is not None or cache_type is not None:
        response.headers["Cache-Control"] = "public"  
    
    if cache_expire is not None:
        response.headers["Cache-Control"] = "max-age=%s, must-revalidate" % cache_expire
    
    return cached_template(template_name, render_template, cache_key=cache_key, 
                           cache_type=cache_type, cache_expire=cache_expire)
Beispiel #6
0
def render(template_name, extra_vars=None, cache_key=None, cache_type=None, 
           cache_expire=None, method='xhtml', loader_class=MarkupTemplate):
    
    def render_template():
        globs = extra_vars or {}
        globs.update(pylons_globals())
        globs['actions'] = model.Action
        template = globs['app_globals'].genshi_loader.load(template_name,
            cls=loader_class)
        stream = template.generate(**globs)
        
        for item in PluginImplementations(IGenshiStreamFilter):
            stream = item.filter(stream)
        
        return literal(stream.render(method=method, encoding=None))
    
    if 'Pragma' in response.headers:
        del response.headers["Pragma"]
    if cache_key is not None or cache_type is not None:
        response.headers["Cache-Control"] = "public"  
    
    if cache_expire is not None:
        response.headers["Cache-Control"] = "max-age=%s, must-revalidate" % cache_expire
    
    return cached_template(template_name, render_template, cache_key=cache_key, 
                           cache_type=cache_type, cache_expire=cache_expire)
Beispiel #7
0
def render_genshi(template_name, genshi_loader, cache_key=None, cache_type=None,
                  cache_expire=None, fragment=False, format='xhtml'):
    """
    Copied out of Pylons so that we can specify the path to genshi templates.
    
    Render a template with Genshi
    
    Accepts the cache options ``cache_key``, ``cache_type``, and
    ``cache_expire`` in addition to fragment and format which are
    passed to Genshi's render function.
    
    """
    # Create a render callable for the cache function
    def render_template():
        # First, get the globals
        globs = pylons_globals()
        
        # Grab a template reference
        template = genshi_loader.load(template_name)
        
        return template.generate(**globs).render()
    
    return cached_template(template_name, render_template, cache_key=cache_key,
                           cache_type=cache_type, cache_expire=cache_expire,
                           ns_options=('fragment', 'format'),
                           fragment=fragment, format=format)
Beispiel #8
0
def render(template_name, extra_vars=None, *pargs, **kwargs):
    '''Render a template and return the output.

    This is CKAN's main template rendering function.

    :params template_name: relative path to template inside registered tpl_dir
    :type template_name: str
    :params extra_vars: additional variables available in template
    :type extra_vars: dict
    :params pargs: DEPRECATED
    :type pargs: tuple
    :params kwargs: DEPRECATED
    :type kwargs: dict

    '''
    if pargs or kwargs:
        tb = inspect.getframeinfo(sys._getframe(1))
        log.warning(
            'Extra arguments to `base.render` are deprecated: ' +
            '<{0.filename}:{0.lineno}>'.format(tb)
        )

    if extra_vars is None:
        extra_vars = {}

    if not is_flask_request():
        renderer = _pylons_prepare_renderer(template_name, extra_vars,
                                            *pargs, **kwargs)
        return cached_template(template_name, renderer)

    return flask_render_template(template_name, **extra_vars)
Beispiel #9
0
def render_kajiki(template_name,
                  extra_vars=None,
                  cache_key=None,
                  cache_type=None,
                  cache_expire=None,
                  method='xhtml'):
    """Render a template with Kajiki

    Accepts the cache options ``cache_key``, ``cache_type``, and
    ``cache_expire`` in addition to method which are passed to Kajiki's
    render function.

    """

    # Create a render callable for the cache function
    def render_template():
        # Pull in extra vars if needed
        globs = extra_vars or {}

        # Second, get the globals
        globs.update(templating.pylons_globals())

        # Grab a template reference
        template = globs['app_globals'].kajiki_loader.load(template_name)

        return literal(template(globs).render())

    return templating.cached_template(template_name,
                                      render_template,
                                      cache_key=cache_key,
                                      cache_type=cache_type,
                                      cache_expire=cache_expire,
                                      ns_options=('method'),
                                      method=method)
Beispiel #10
0
    def __call__(self, template_name, template_vars, **kwargs):
        """Render the template_vars with the Genshi template."""
        template_vars.update(self.genshi_functions)

        # Gets document type from content type or from config options
        doctype = 'text/x-vcard'
        method = 'vcf'
        kwargs['doctype'] = doctype
        kwargs['method'] = method

        def render_template():
            template = self.load_template(template_name)
            return template.generate(**template_vars).render(encoding=None)

        return templating.cached_template(template_name, render_template,
                                          **kwargs)
Beispiel #11
0
    def __call__(self, template_name, template_vars, **kwargs):
        """Render the template_vars with the Genshi template."""
        template_vars.update(self.genshi_functions)

        # Gets document type from content type or from config options
        doctype = 'text/x-vcard'
        method='vcf'
        kwargs['doctype'] = doctype
        kwargs['method'] = method

        def render_template():
            template = self.load_template(template_name)
            return template.generate(**template_vars).render(encoding=None)

        return templating.cached_template(
            template_name, render_template,
            **kwargs)
Beispiel #12
0
def render_genshi(template_name, extra_vars=None, cache_key=None, 
                  cache_type=None, cache_expire=None, method='xhtml', 
                  form_data=None, form_errors=None):
    """Render a template with Genshi
   
    Taken from Pylons, augmented with the HTMLFormFiller functionality,
    use ``form_data'' option.

    Added our own HTMLFormErrors, ``form_errors'' takes a dict of form field ids
    and error messages.

    We also use genshi's DocTypeInserter

    Accepts the cache options ``cache_key``, ``cache_type``, and
    ``cache_expire`` in addition to method which are passed to Genshi's
    render function.    
    """
    # Create a render callable for the cache function
    def render_template():
        # Pull in extra vars if needed
        globs = extra_vars or {}
        
        # Second, get the globals
        globs.update(pylons_globals())

        # Grab a template reference
        template = globs['app_globals'].genshi_loader.load(template_name)

        stream = template.generate(**globs) | DocTypeInserter(DocType.HTML5)

        if form_data:
            stream = stream | HTMLFormFiller(data=form_data)

        if form_errors:
            stream = stream | HTMLFormErrors(errors=form_errors)
 
        return literal(stream.render(method=method, encoding=None))

    # if there's form data we don't cache
    if form_data or form_errors:
        return render_template()

    return cached_template(template_name, render_template, cache_key=cache_key,
                           cache_type=cache_type, cache_expire=cache_expire,
                           ns_options=('method'), method=method)
Beispiel #13
0
def render_pytiles(template_name, extra_vars=None, cache_key=None,
                    cache_type=None, cache_expire=None):
    """Render a template with Pytiles"""
    # Create a render callable for the cache function
    def render_template():
        # Pull in extra vars if needed
        globs = extra_vars or {}

        # Second, get the globals
        globs.update(pylons_globals())

        # Grab a template reference
        template = \
            globs['app_globals'].pytiles_container.get_template(template_name)

        return literal(template.render(**globs))
    
    return cached_template(template_name, render_template, cache_key=cache_key,
                            cache_type=cache_type, cache_expire=cache_expire)
Beispiel #14
0
    def __call__(self, template_name, template_vars, **kwargs):
        """Render the template_vars with the Chameleon-Genshi template."""

        # Gets template format from content type or from config options
        format = kwargs.get('format')
        if not format:
            format = self.format_for_content_type.get(response.content_type)
            if not format:
                format = config.get('templating.chameleon.genshi.format')
                if not format:
                    format = config.get('templating.genshi.method')
                    if not format or format not in ('xml', 'text'):
                        format = 'xml'

        def render_template():
            template_vars.update(my_pylons_globals())
            template = self.load_template(template_name, format=format)
            return literal(template.render(**template_vars))

        return templating.cached_template(
            template_name, render_template,
            ns_options=('doctype', 'method'), **kwargs)
Beispiel #15
0
def render_evoque(template_name, extra_vars=None, cache_key=None,
                    cache_type=None, cache_expire=None,
                    collection=None, raw=False, quoting=None):
    """ Render a template with Evoque : http://evoque.gizmojo.org/ext/pylons/
	
    Accepts the cache options ``cache_key``, ``cache_type``, and
    ``cache_expire``. 
    
    The remaining options affect how template is located, loaded and rendered:
    - template_name: normally this is the collection-root-relative locator for
          the template; if template had been previously with location specified
          via the src option, then may be any arbitrary string identifier.
    - collection: either(None, str, Collection), an existing collection, 
          None implies the default collection
    - raw: bool, render the raw template source 
    - quoting: either(str, type), sets the Quoted-No-More string class to use, 
          None uses the collection's default, 
          "xml" uses qpy.xml, 
          "str" uses unicode
    """
    # Create a render callable for the cache function
    def render_template():
        # Get the globals
        # Note: when running in restricted mode which of these globals are
        # to be exposed should be a lot more selective. 
        pg = pylons_globals()
        
        # Update any extra vars if needed
        if extra_vars:
            pg.update(extra_vars)
        
        # Grab a template reference
        template = pg['app_globals'].evoque_domain.get_template(
            template_name, collection=collection, raw=raw, quoting=quoting)
        return template.evoque(pg, raw=raw, quoting=quoting)
    
    return cached_template(template_name, render_template, cache_key=cache_key,
                    cache_type=cache_type, cache_expire=cache_expire)
Beispiel #16
0
    def __call__(self, template_name, template_vars, **kwargs):
        """Render the template_vars with the Genshi template."""
        template_vars.update(self.genshi_functions)

        # Gets document type from content type or from config options
        doctype = kwargs.get('doctype')
        if not doctype:
            doctype = config.get('templating.genshi.doctype')
            if not doctype:
                method = kwargs.get('method') or config.get(
                    'templating.genshi.method') or 'xhtml'
                doctype = self.doctypes_for_methods.get(method)
            doctypes = self.doctypes_for_content_type.get(response.content_type)
            if doctypes and (not doctype or doctype not in doctypes):
                doctype = doctypes[0]
            kwargs['doctype'] = doctype

        # Gets rendering method from content type or from config options
        method = kwargs.get('method')
        if not method:
            method = config.get('templating.genshi.method')
            if not method:
                method = self.method_for_doctype(doctype)
            methods = self.methods_for_content_type.get(response.content_type)
            if methods and (not method or method not in methods):
                method = methods[0]
            kwargs['method'] = method

        def render_template():
            template_vars.update(my_pylons_globals())
            template = self.load_template(template_name)
            return literal(template.generate(**template_vars).render(
                    doctype=doctype, method=method, encoding=None))

        return templating.cached_template(
            template_name, render_template,
            ns_options=('doctype', 'method'), **kwargs)
Beispiel #17
0
def render(template_name, extra_vars=None, cache_key=None, cache_type=None,
           cache_expire=None, method='xhtml', loader_class=MarkupTemplate,
           cache_force=None, renderer=None):
    ''' Main template rendering function. '''

    def render_template():
        globs = extra_vars or {}
        globs.update(pylons_globals())
        globs['actions'] = model.Action

        # Using pylons.url() directly destroys the localisation stuff so
        # we remove it so any bad templates crash and burn
        del globs['url']

        try:
            template_path, template_type = lib.render.template_info(template_name)
        except lib.render.TemplateNotFound:
            template_type = 'genshi'
            template_path = ''

        # snippets should not pass the context
        # but allow for legacy genshi templates
        if renderer == 'snippet' and template_type != 'genshi':
            del globs['c']
            del globs['tmpl_context']

        log.debug('rendering %s [%s]' % (template_path, template_type))
        if config.get('debug'):
            context_vars = globs.get('c')
            if context_vars:
                context_vars = dir(context_vars)
            debug_info = {'template_name': template_name,
                          'template_path': template_path,
                          'template_type': template_type,
                          'vars': globs,
                          'c_vars': context_vars,
                          'renderer': renderer}
            if 'CKAN_DEBUG_INFO' not in request.environ:
                request.environ['CKAN_DEBUG_INFO'] = []
            request.environ['CKAN_DEBUG_INFO'].append(debug_info)

        # Jinja2 templates
        if template_type == 'jinja2':
            # We don't want to have the config in templates it should be
            # accessed via g (app_globals) as this gives us flexability such
            # as changing via database settings.
            del globs['config']
            # TODO should we raise error if genshi filters??
            return render_jinja2(template_name, globs)

        # Genshi templates
        template = globs['app_globals'].genshi_loader.load(template_name,
                                                           cls=loader_class)
        stream = template.generate(**globs)

        for item in PluginImplementations(IGenshiStreamFilter):
            stream = item.filter(stream)

        if loader_class == NewTextTemplate:
            return literal(stream.render(method="text", encoding=None))

        return literal(stream.render(method=method, encoding=None,
                                     strip_whitespace=True))

    if 'Pragma' in response.headers:
        del response.headers["Pragma"]

    ## Caching Logic
    allow_cache = True
    # Force cache or not if explicit.
    if cache_force is not None:
        allow_cache = cache_force
    # Do not allow caching of pages for logged in users/flash messages etc.
    elif session.last_accessed:
        allow_cache = False
    # Tests etc.
    elif 'REMOTE_USER' in request.environ:
        allow_cache = False
    # Don't cache if based on a non-cachable template used in this.
    elif request.environ.get('__no_cache__'):
        allow_cache = False
    # Don't cache if we have set the __no_cache__ param in the query string.
    elif request.params.get('__no_cache__'):
        allow_cache = False
    # Don't cache if we have extra vars containing data.
    elif extra_vars:
        for k, v in extra_vars.iteritems():
            allow_cache = False
            break
    # Record cachability for the page cache if enabled
    request.environ['CKAN_PAGE_CACHABLE'] = allow_cache

    if allow_cache:
        response.headers["Cache-Control"] = "public"
        try:
            cache_expire = int(config.get('ckan.cache_expires', 0))
            response.headers["Cache-Control"] += \
                ", max-age=%s, must-revalidate" % cache_expire
        except ValueError:
            pass
    else:
        # We do not want caching.
        response.headers["Cache-Control"] = "private"
        # Prevent any further rendering from being cached.
        request.environ['__no_cache__'] = True
    log.debug('Template cache-control: %s' % response.headers["Cache-Control"])

    # Render Time :)
    try:
        return cached_template(template_name, render_template,
                               loader_class=loader_class)
    except ckan.exceptions.CkanUrlException, e:
        raise ckan.exceptions.CkanUrlException(
            '\nAn Exception has been raised for template %s\n%s' %
            (template_name, e.message))
Beispiel #18
0
def render(template_name,
           extra_vars=None,
           cache_key=None,
           cache_type=None,
           cache_expire=None,
           method='xhtml',
           loader_class=MarkupTemplate,
           cache_force=None,
           renderer=None):
    ''' Main template rendering function. '''
    def render_template():
        globs = extra_vars or {}
        globs.update(pylons_globals())
        globs['actions'] = model.Action

        # Using pylons.url() directly destroys the localisation stuff so
        # we remove it so any bad templates crash and burn
        del globs['url']

        try:
            template_path, template_type = lib.render.template_info(
                template_name)
        except lib.render.TemplateNotFound:
            template_type = 'genshi'
            template_path = ''

        # snippets should not pass the context
        # but allow for legacy genshi templates
        if renderer == 'snippet' and template_type != 'genshi':
            del globs['c']
            del globs['tmpl_context']

        log.debug('rendering %s [%s]' % (template_path, template_type))
        if config.get('debug'):
            context_vars = globs.get('c')
            if context_vars:
                context_vars = dir(context_vars)
            debug_info = {
                'template_name': template_name,
                'template_path': template_path,
                'template_type': template_type,
                'vars': globs,
                'c_vars': context_vars,
                'renderer': renderer
            }
            if 'CKAN_DEBUG_INFO' not in request.environ:
                request.environ['CKAN_DEBUG_INFO'] = []
            request.environ['CKAN_DEBUG_INFO'].append(debug_info)

        # Jinja2 templates
        if template_type == 'jinja2':
            # We don't want to have the config in templates it should be
            # accessed via g (app_globals) as this gives us flexability such
            # as changing via database settings.
            del globs['config']
            # TODO should we raise error if genshi filters??
            return render_jinja2(template_name, globs)

        # Genshi templates
        template = globs['app_globals'].genshi_loader.load(template_name,
                                                           cls=loader_class)
        stream = template.generate(**globs)

        for item in PluginImplementations(IGenshiStreamFilter):
            stream = item.filter(stream)

        if loader_class == NewTextTemplate:
            return literal(stream.render(method="text", encoding=None))

        return literal(
            stream.render(method=method, encoding=None, strip_whitespace=True))

    if 'Pragma' in response.headers:
        del response.headers["Pragma"]

    ## Caching Logic
    allow_cache = True
    # Force cache or not if explicit.
    if cache_force is not None:
        allow_cache = cache_force
    # Do not allow caching of pages for logged in users/flash messages etc.
    elif session.last_accessed:
        allow_cache = False
    # Tests etc.
    elif 'REMOTE_USER' in request.environ:
        allow_cache = False
    # Don't cache if based on a non-cachable template used in this.
    elif request.environ.get('__no_cache__'):
        allow_cache = False
    # Don't cache if we have set the __no_cache__ param in the query string.
    elif request.params.get('__no_cache__'):
        allow_cache = False
    # Don't cache if we have extra vars containing data.
    elif extra_vars:
        for k, v in extra_vars.iteritems():
            allow_cache = False
            break
    # Record cachability for the page cache if enabled
    request.environ['CKAN_PAGE_CACHABLE'] = allow_cache

    if allow_cache:
        response.headers["Cache-Control"] = "public"
        try:
            cache_expire = int(config.get('ckan.cache_expires', 0))
            response.headers["Cache-Control"] += \
                ", max-age=%s, must-revalidate" % cache_expire
        except ValueError:
            pass
    else:
        # We do not want caching.
        response.headers["Cache-Control"] = "private"
        # Prevent any further rendering from being cached.
        request.environ['__no_cache__'] = True
    log.debug('Template cache-control: %s' % response.headers["Cache-Control"])

    # Render Time :)
    try:
        return cached_template(template_name,
                               render_template,
                               loader_class=loader_class)
    except ckan.exceptions.CkanUrlException, e:
        raise ckan.exceptions.CkanUrlException(
            '\nAn Exception has been raised for template %s\n%s' %
            (template_name, e.message))
Beispiel #19
0
def render(template_name,
           extra_vars=None,
           cache_key=None,
           cache_type=None,
           cache_expire=None,
           cache_force=None,
           renderer=None):
    '''Render a template and return the output.

    This is CKAN's main template rendering function.

    .. todo::

       Document the parameters of :py:func:`ckan.plugins.toolkit.render`.

    '''
    def render_template():
        globs = extra_vars or {}
        globs.update(pylons_globals())

        # Using pylons.url() directly destroys the localisation stuff so
        # we remove it so any bad templates crash and burn
        del globs['url']

        try:
            template_path, template_type = render_.template_info(template_name)
        except render_.TemplateNotFound:
            raise

        log.debug('rendering %s [%s]' % (template_path, template_type))
        if config.get('debug'):
            context_vars = globs.get('c')
            if context_vars:
                context_vars = dir(context_vars)
            debug_info = {
                'template_name': template_name,
                'template_path': template_path,
                'template_type': template_type,
                'vars': globs,
                'c_vars': context_vars,
                'renderer': renderer
            }
            if 'CKAN_DEBUG_INFO' not in request.environ:
                request.environ['CKAN_DEBUG_INFO'] = []
            request.environ['CKAN_DEBUG_INFO'].append(debug_info)

        del globs['config']
        return render_jinja2(template_name, globs)

    if 'Pragma' in response.headers:
        del response.headers["Pragma"]

    ## Caching Logic
    allow_cache = True
    # Force cache or not if explicit.
    if cache_force is not None:
        allow_cache = cache_force
    # Do not allow caching of pages for logged in users/flash messages etc.
    elif session.last_accessed:
        allow_cache = False
    # Tests etc.
    elif 'REMOTE_USER' in request.environ:
        allow_cache = False
    # Don't cache if based on a non-cachable template used in this.
    elif request.environ.get('__no_cache__'):
        allow_cache = False
    # Don't cache if we have set the __no_cache__ param in the query string.
    elif request.params.get('__no_cache__'):
        allow_cache = False

# Don't cache if we have extra vars containing data.
    elif extra_vars:
        for k, v in extra_vars.iteritems():
            allow_cache = False
            break
    # Record cachability for the page cache if enabled
    request.environ['CKAN_PAGE_CACHABLE'] = allow_cache

    if allow_cache:
        response.headers["Cache-Control"] = "public"
        try:
            cache_expire = int(config.get('ckan.cache_expires', 0))
            response.headers["Cache-Control"] += \
                ", max-age=%s, must-revalidate" % cache_expire
        except ValueError:
            pass
    else:
        # We do not want caching.
        response.headers["Cache-Control"] = "private"
        # Prevent any further rendering from being cached.
        request.environ['__no_cache__'] = True

    # Render Time :)
    try:
        return cached_template(template_name, render_template)
    except ckan.exceptions.CkanUrlException, e:
        raise ckan.exceptions.CkanUrlException(
            '\nAn Exception has been raised for template %s\n%s' %
            (template_name, e.message))
Beispiel #20
0
def render(
    template_name, extra_vars=None, cache_key=None, cache_type=None, cache_expire=None, cache_force=None, renderer=None
):
    """Render a template and return the output.

    This is CKAN's main template rendering function.

    .. todo::

       Document the parameters of :py:func:`ckan.plugins.toolkit.render`.

    """

    def render_template():
        globs = extra_vars or {}
        globs.update(pylons_globals())

        # Using pylons.url() directly destroys the localisation stuff so
        # we remove it so any bad templates crash and burn
        del globs["url"]

        try:
            template_path, template_type = render_.template_info(template_name)
        except render_.TemplateNotFound:
            raise

        log.debug("rendering %s [%s]" % (template_path, template_type))
        if config.get("debug"):
            context_vars = globs.get("c")
            if context_vars:
                context_vars = dir(context_vars)
            debug_info = {
                "template_name": template_name,
                "template_path": template_path,
                "template_type": template_type,
                "vars": globs,
                "c_vars": context_vars,
                "renderer": renderer,
            }
            if "CKAN_DEBUG_INFO" not in request.environ:
                request.environ["CKAN_DEBUG_INFO"] = []
            request.environ["CKAN_DEBUG_INFO"].append(debug_info)

        del globs["config"]
        return render_jinja2(template_name, globs)

    if "Pragma" in response.headers:
        del response.headers["Pragma"]

    ## Caching Logic
    allow_cache = True
    # Force cache or not if explicit.
    if cache_force is not None:
        allow_cache = cache_force
    # Do not allow caching of pages for logged in users/flash messages etc.
    elif session.last_accessed:
        allow_cache = False
    # Tests etc.
    elif "REMOTE_USER" in request.environ:
        allow_cache = False
    # Don't cache if based on a non-cachable template used in this.
    elif request.environ.get("__no_cache__"):
        allow_cache = False
    # Don't cache if we have set the __no_cache__ param in the query string.
    elif request.params.get("__no_cache__"):
        allow_cache = False
    # Don't cache if we have extra vars containing data.
    elif extra_vars:
        for k, v in extra_vars.iteritems():
            allow_cache = False
            break
    # Record cachability for the page cache if enabled
    request.environ["CKAN_PAGE_CACHABLE"] = allow_cache

    if allow_cache:
        response.headers["Cache-Control"] = "public"
        try:
            cache_expire = int(config.get("ckan.cache_expires", 0))
            response.headers["Cache-Control"] += ", max-age=%s, must-revalidate" % cache_expire
        except ValueError:
            pass
    else:
        # We do not want caching.
        response.headers["Cache-Control"] = "private"
        # Prevent any further rendering from being cached.
        request.environ["__no_cache__"] = True

    # Render Time :)
    try:
        return cached_template(template_name, render_template)
    except ckan.exceptions.CkanUrlException, e:
        raise ckan.exceptions.CkanUrlException(
            "\nAn Exception has been raised for template %s\n%s" % (template_name, e.message)
        )
Beispiel #21
0
def render(template_name,
           extra_vars=None,
           cache_key=None,
           cache_type=None,
           cache_expire=None,
           method='xhtml',
           loader_class=MarkupTemplate,
           cache_force=None):
    ''' Main genshi template rendering function. '''
    def render_template():
        globs = extra_vars or {}
        globs.update(pylons_globals())
        globs['actions'] = model.Action
        # add the template name to the context to help us know where we are
        # used in depreciating functions etc
        c.__template_name = template_name

        # Using pylons.url() directly destroys the localisation stuff so
        # we remove it so any bad templates crash and burn
        del globs['url']

        template = globs['app_globals'].genshi_loader.load(template_name,
                                                           cls=loader_class)
        stream = template.generate(**globs)

        for item in PluginImplementations(IGenshiStreamFilter):
            stream = item.filter(stream)

        if loader_class == NewTextTemplate:
            return literal(stream.render(method="text", encoding=None))

        return literal(
            stream.render(method=method, encoding=None, strip_whitespace=True))

    if 'Pragma' in response.headers:
        del response.headers["Pragma"]

    ## Caching Logic
    allow_cache = True
    # Force cache or not if explicit.
    if cache_force is not None:
        allow_cache = cache_force
    # Do not allow caching of pages for logged in users/flash messages etc.
    elif session.last_accessed:
        allow_cache = False
    # Tests etc.
    elif 'REMOTE_USER' in request.environ:
        allow_cache = False
    # Don't cache if based on a non-cachable template used in this.
    elif request.environ.get('__no_cache__'):
        allow_cache = False
    # Don't cache if we have set the __no_cache__ param in the query string.
    elif request.params.get('__no_cache__'):
        allow_cache = False
    # Don't cache if we have extra vars containing data.
    elif extra_vars:
        for k, v in extra_vars.iteritems():
            allow_cache = False
            break
    # Record cachability for the page cache if enabled
    request.environ['CKAN_PAGE_CACHABLE'] = allow_cache

    if allow_cache:
        response.headers["Cache-Control"] = "public"
        try:
            cache_expire = int(config.get('ckan.cache_expires', 0))
            response.headers[
                "Cache-Control"] += ", max-age=%s, must-revalidate" % cache_expire
        except ValueError:
            pass
    else:
        # We do not want caching.
        response.headers["Cache-Control"] = "private"
        # Prevent any further rendering from being cached.
        request.environ['__no_cache__'] = True
    log.debug('Template cache-control: %s' % response.headers["Cache-Control"])

    # Render Time :)
    try:
        return cached_template(template_name,
                               render_template,
                               loader_class=loader_class)
    except ckan.exceptions.CkanUrlException, e:
        raise ckan.exceptions.CkanUrlException(
            '\nAn Exception has been raised for template %s\n%s' %
            (template_name, e.message))
Beispiel #22
0
def render(template_name, extra_vars=None, cache_key=None, cache_type=None,
           cache_expire=None, method='xhtml', loader_class=MarkupTemplate,
           cache_force=None):
    ''' Main genshi template rendering function. '''

    def render_template():
        globs = extra_vars or {}
        globs.update(pylons_globals())
        globs['actions'] = model.Action
        # add the template name to the context to help us know where we are
        # used in depreciating functions etc
        c.__template_name = template_name

        # Using pylons.url() directly destroys the localisation stuff so
        # we remove it so any bad templates crash and burn
        del globs['url']

        template = globs['app_globals'].genshi_loader.load(template_name,
                                                           cls=loader_class)
        stream = template.generate(**globs)

        for item in PluginImplementations(IGenshiStreamFilter):
            stream = item.filter(stream)

        if loader_class == NewTextTemplate:
            return literal(stream.render(method="text", encoding=None))

        return literal(stream.render(method=method, encoding=None,
                                     strip_whitespace=True))

    if 'Pragma' in response.headers:
        del response.headers["Pragma"]

    ## Caching Logic
    allow_cache = True
    # Force cache or not if explicit.
    if cache_force is not None:
        allow_cache = cache_force
    # Do not allow caching of pages for logged in users/flash messages etc.
    elif session.last_accessed:
        allow_cache = False
    # Tests etc.
    elif 'REMOTE_USER' in request.environ:
        allow_cache = False
    # Don't cache if based on a non-cachable template used in this.
    elif request.environ.get('__no_cache__'):
        allow_cache = False
    # Don't cache if we have set the __no_cache__ param in the query string.
    elif request.params.get('__no_cache__'):
        allow_cache = False
    # Don't cache if we have extra vars containing data.
    elif extra_vars:
        for k, v in extra_vars.iteritems():
            allow_cache = False
            break
    # Record cachability for the page cache if enabled
    request.environ['CKAN_PAGE_CACHABLE'] = allow_cache

    if allow_cache:
        response.headers["Cache-Control"] = "public"
        try:
            cache_expire = int(config.get('ckan.cache_expires', 0))
            response.headers["Cache-Control"] += \
                ", max-age=%s, must-revalidate" % cache_expire
        except ValueError:
            pass
    else:
        # We do not want caching.
        response.headers["Cache-Control"] = "private"
        # Prevent any further rendering from being cached.
        request.environ['__no_cache__'] = True
    log.debug('Template cache-control: %s' % response.headers["Cache-Control"])

    # Render Time :)
    try:
        return cached_template(template_name, render_template,
                               loader_class=loader_class)
    except ckan.exceptions.CkanUrlException, e:
        raise ckan.exceptions.CkanUrlException(
            '\nAn Exception has been raised for template %s\n%s' %
            (template_name, e.message))