Example #1
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)
Example #2
0
File: base.py Project: mattcen/ckan
def abort(status_code=None, detail='', headers=None, comment=None):
    '''Abort the current request immediately by returning an HTTP exception.

    This is a wrapper for :py:func:`pylons.controllers.util.abort` that adds
    some CKAN custom behavior, including allowing
    :py:class:`~ckan.plugins.interfaces.IAuthenticator` plugins to alter the
    abort response, and showing flash messages in the web interface.

    '''
    if status_code == 403:
        # Allow IAuthenticator plugins to alter the abort
        for item in p.PluginImplementations(p.IAuthenticator):
            result = item.abort(status_code, detail, headers, comment)
            (status_code, detail, headers, comment) = result

    if detail and status_code != 503:
        h.flash_error(detail)

    if is_flask_request():
        flask_abort(status_code, detail)

    # #1267 Convert detail to plain text, since WebOb 0.9.7.1 (which comes
    # with Lucid) causes an exception when unicode is received.
    detail = detail.encode('utf8')

    return _abort(status_code=status_code,
                  detail=detail,
                  headers=headers,
                  comment=comment)
Example #3
0
def abort(status_code=None, detail='', headers=None, comment=None):
    '''Abort the current request immediately by returning an HTTP exception.

    This is a wrapper for :py:func:`pylons.controllers.util.abort` that adds
    some CKAN custom behavior, including allowing
    :py:class:`~ckan.plugins.interfaces.IAuthenticator` plugins to alter the
    abort response, and showing flash messages in the web interface.

    '''
    if status_code == 403:
        # Allow IAuthenticator plugins to alter the abort
        for item in p.PluginImplementations(p.IAuthenticator):
            result = item.abort(status_code, detail, headers, comment)
            (status_code, detail, headers, comment) = result

    if detail and status_code != 503:
        h.flash_error(detail)
    # #1267 Convert detail to plain text, since WebOb 0.9.7.1 (which comes
    # with Lucid) causes an exception when unicode is received.
    detail = detail.encode('utf8')
    if is_flask_request():
        flask_abort(status_code, detail)

    return _abort(status_code=status_code,
                  detail=detail,
                  headers=headers,
                  comment=comment)
Example #4
0
def get_lang():
    ''' Returns the current language. Based on babel.i18n.get_lang but
    works when set_lang has not been run (i.e. still in English). '''
    if is_flask_request():
        from ckan.config.middleware.flask_app import get_locale
        return get_locale()
    return 'en'
Example #5
0
File: base.py Project: mattcen/ckan
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)
Example #6
0
def get_lang():
    ''' Returns the current language. Based on babel.i18n.get_lang but
    works when set_lang has not been run (i.e. still in English). '''
    if is_flask_request():
        from ckan.config.middleware.flask_app import get_locale
        return get_locale()
    else:
        langs = i18n.get_lang()
        if langs:
            return langs[0]
    return 'en'
Example #7
0
def _upload_authority_file(data_dict, is_required=False):
    if is_required and data_dict.get('authority_file_url') == '':
        raise ValidationError({_('authority'): [_('Missing value')]})

    if is_flask_request():
        authority_file_upload = request.files.get('authority_file_upload')
        is_upload = authority_file_upload
    else:
        authority_file_upload = data_dict.get('authority_file_upload')
        is_upload = isinstance(authority_file_upload, cgi.FieldStorage)

    if is_upload:
        max_authority_size =\
            int(config.get('ckanext.datagovmk.authority_file_max_size', 10))
        data_dict['authority_file_upload'] =\
            authority_file_upload
        upload = uploader.get_uploader(
            'authorities',
            data_dict['authority_file_url']
        )
        upload.update_data_dict(
            data_dict,
            'authority_file_url',
            'authority_file_upload',
            'clear_upload'
        )
        try:
            upload.upload(max_size=max_authority_size)
        except toolkit.ValidationError:
            data_dict['authority_file_url'] =\
                authority_file_upload.filename
            raise ValidationError({_('authority'): [_('Uploaded authority file is too large. Maximum allowed size is {size}MB.').format(size=max_authority_size)]})

        authority_file = upload.filename

        data_dict['authority_file_url'] = authority_file
    else:
        authority_file = data_dict.get('authority_file_url')

    return authority_file
def activity_list_to_html(context, activity_stream, extra_vars):
    '''Return the given activity stream as a snippet of HTML.

    :param activity_stream: the activity stream to render
    :type activity_stream: list of activity dictionaries
    :param extra_vars: extra variables to pass to the activity stream items
        template when rendering it
    :type extra_vars: dictionary

    :rtype: HTML-formatted string

    '''
    activity_list = [] # These are the activity stream messages.
    for activity in activity_stream:
        detail = None
        activity_type = activity['activity_type']
        # Some activity types may have details.
        if activity_type in activity_stream_actions_with_detail:
            details = logic.get_action('activity_detail_list')(context=context,
                data_dict={'id': activity['id']})
            # If an activity has just one activity detail then render the
            # detail instead of the activity.
            if len(details) == 1:
                detail = details[0]
                object_type = detail['object_type']

                if object_type == 'PackageExtra':
                    object_type = 'package_extra'

                new_activity_type = '%s %s' % (detail['activity_type'],
                                            object_type.lower())
                if new_activity_type in activity_stream_string_functions:
                    activity_type = new_activity_type

        if not activity_type in activity_stream_string_functions:
            raise NotImplementedError("No activity renderer for activity "
                "type '%s'" % activity_type)

        if activity_type in activity_stream_string_icons:
            activity_icon = activity_stream_string_icons[activity_type]
        else:
            activity_icon = activity_stream_string_icons['undefined']

        activity_msg = activity_stream_string_functions[activity_type](context,
                activity)

        # Get the data needed to render the message.
        matches = re.findall('\{([^}]*)\}', activity_msg)
        data = {}
        for match in matches:
            snippet = activity_snippet_functions[match](activity, detail)
            data[str(match)] = snippet

        activity_list.append({'msg': activity_msg,
                              'type': activity_type.replace(' ', '-').lower(),
                              'icon': activity_icon,
                              'data': data,
                              'timestamp': activity['timestamp'],
                              'is_new': activity.get('is_new', False)})
    extra_vars['activities'] = activity_list

    # TODO: Do this properly without having to check if it's Flask or not
    if is_flask_request():
        return base.render('activity_streams/activity_stream_items.html',
                           extra_vars=extra_vars)
    else:
        return literal(base.render('activity_streams/activity_stream_items.html',
                       extra_vars=extra_vars))
Example #9
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)

    def set_pylons_response_headers(allow_cache):
        if 'Pragma' in response.headers:
            del response.headers["Pragma"]
        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"

    # 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

    # TODO: replicate this logic in Flask once we start looking at the
    # rendering for the frontend controllers
    if not is_flask_request():
        set_pylons_response_headers(allow_cache)

    if not allow_cache:
        # Prevent any further rendering from being cached.
        request.environ['__no_cache__'] = True

    # Render Time :)
    try:
        # TODO: investigate and test this properly
        if is_flask_request():
            return flask_render_template(template_name, **extra_vars)
        else:
            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))
Example #10
0
 def identify(self):
     from ckan.common import is_flask_request
     if not is_flask_request():
         h.check_user_profile_preferences()
     return super(KnowledgehubPlugin, self).identify()