How to use the ckan.lib.helpers function in ckan

To help you get started, we’ve selected a few ckan examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ckan / ckanext-issues / ckanext / issues / lib / helpers.py View on Github external
replace existing parameters with new ones

    controller action & extras (dict) are used to create the base url via
    :py:func:`~ckan.lib.helpers.url_for` controller & action default to the
    current ones

    This can be overriden providing an alternative_url, which will be used
    instead.
    '''
    params_cleaned = [(k, v) for k, v in toolkit.request.params.items()
                      if k not in new_params.keys()]
    params = set(params_cleaned)
    if new_params:
        params |= set(new_params.items())
    if alternative_url:
        return helpers._url_with_params(alternative_url, params)

    return helpers._url_with_params(toolkit.request.path, params)
github ckan / ckanext-qa / ckanext / qa / tasks.py View on Github external
'''
    Looks at the format field of a resource to determine its format and score.

    It adds strings to score_reasons list about how it came to the conclusion.

    Return values:
      * It returns a tuple: (score, format_string)
      * If it cannot work out the format then format_string is None
      * If it cannot score it, then score is None
    '''
    format_field = resource.format or ''
    if not format_field:
        score_reasons.append(_('Format field is blank.'))
        return (None, None)
    format_tuple = ckan_helpers.resource_formats().get(format_field.lower()) or \
        ckan_helpers.resource_formats().get(lib.munge_format_to_be_canonical(format_field))
    if not format_tuple:
        score_reasons.append(_('Format field "%s" does not correspond to a known format.') % format_field)
        return (None, None)
    score = lib.resource_format_scores().get(format_tuple[1])
    score_reasons.append(_('Format field "%s" receives score: %s.') %
                         (format_field, score))
    return (score, format_tuple[1])
github ckan / ckanext-dashboard / ckanext / dashboard / plugin.py View on Github external
def _get_resource_views_groupped_by_resource(self, context, current_view_ids, package):
        resource_views = {}

        for resource in package.get('resources', []):
            views = toolkit.get_action('resource_view_list')(context, resource)
            for view in views:
                if view['id'] in current_view_ids or view['view_type'] == 'dashboard':
                    continue
                view['icon'] = helpers.resource_view_icon(view)
                resource_views[resource['name']] = resource_views.get(resource['name'], [])
                resource_views[resource['name']].append(view)

        return resource_views
github datadotworld / ckanext-datadotworld / ckanext / datadotworld / controller / datadotworld.py View on Github external
context = {
            'model': model,
            'session': model.Session,
            'user': c.user or c.author,
            'auth_user_obj': c.userobj}
        data_dict = {
            'id': id
        }
        stats = {}
        extra = {
            'errors': {},
            'error_summary': None,
            'stats': stats
        }
        try:
            if not h.check_access('organization_update', data_dict):
                raise logic.NotAuthorized
            c.group_dict = logic.get_action('organization_show')(context, data_dict)
            c.group = context['group']
            c.credentials = c.group.datadotworld_credentials
            if c.credentials is None:
                c.credentials = Credentials(
                    organization=c.group
                )
                model.Session.add(c.credentials)
        except logic.NotFound:
            base.abort(404, _('Organization not found'))
        except logic.NotAuthorized:
            base.abort(401, _('User %r not authorized to edit %s') % (
                c.user, id))
        if request.method == 'POST':
            data = dict(request.POST)
github frictionlessdata / ckanext-datapackager / ckanext / datapackager / controllers / user.py View on Github external
def read(self, locale=None):
        '''Render the logged-in user's profile page.

        If no user is logged in, redirects to the login page.

        '''
        if not toolkit.c.user:
            helpers.redirect_to(locale=locale, controller='user',
                                action='login', id=None)
        user_ref = toolkit.c.userobj.get_reference_preferred_for_uri()
        helpers.redirect_to(locale=locale, controller='user', action='read',
                            id=user_ref)
github NaturalHistoryMuseum / ckanext-nhm / ckanext / nhm / lib / helpers.py View on Github external
datetime
    available from them, or None if there is no update datetime found.

    :param package_or_resource_dicts: a sequence of the package or resource dicts
    :return: a 2-tuple containing the latest datetime and the dict from which it came,
    if no times
             are found then (None, None) is returned
    '''
    # a list of fields on the resource that should contain update dates
    fields = [u'last_modified', u'revision_timestamp', u'Created']

    latest_dict = None
    latest_date = None
    for package_or_resource_dict in package_or_resource_dicts:
        for field in fields:
            date = core_helpers._datestamp_to_datetime(package_or_resource_dict.get(field, None))
            if date is not None and (latest_date is None or date > latest_date):
                latest_date = date
                latest_dict = package_or_resource_dict

    return latest_date, latest_dict
github ckan / ckanext-scheming / ckanext / scheming / validation.py View on Github external
def validator(key, data, errors, context):
        value = data[key]
        date = None

        if value:
            if isinstance(value, datetime.datetime):
                return value
            else:
                try:
                    date = h.date_str_to_datetime(value)
                except (TypeError, ValueError), e:
                    raise Invalid(_('Date format incorrect'))
        else:
            extras = data.get(('__extras',))
            if not extras or (key[0] + '_date' not in extras and
                              key[0] + '_time' not in extras):
                if field.get('required'):
                    not_empty(key, data, errors, context)
            else:
                date = validate_date_inputs(
                    field, key, data, extras, errors, context)

        data[key] = date
github ckan / ckanext-issues / ckanext / issues / lib / helpers.py View on Github external
controller action & extras (dict) are used to create the base url via
    :py:func:`~ckan.lib.helpers.url_for` controller & action default to the
    current ones

    This can be overriden providing an alternative_url, which will be used
    instead.
    '''
    params_cleaned = [(k, v) for k, v in toolkit.request.params.items()
                      if k not in new_params.keys()]
    params = set(params_cleaned)
    if new_params:
        params |= set(new_params.items())
    if alternative_url:
        return helpers._url_with_params(alternative_url, params)

    return helpers._url_with_params(toolkit.request.path, params)
github NaturalHistoryMuseum / ckanext-nhm / ckanext / nhm / controllers / page.py View on Github external
# We're re-writing it as we don't want all their content, and they haven't made it easy to override
        stats = stats_lib.Stats()

        rev_stats = stats_lib.RevisionStats()

        c.num_packages_by_week = rev_stats.get_num_packages_by_week()
        c.package_revisions_by_week = rev_stats.get_by_week('package_revisions')
        c.new_packages_by_week = rev_stats.get_by_week('new_packages')

        c.raw_packages_by_week = []
        for week_date, num_packages, cumulative_num_packages in c.num_packages_by_week:
            c.raw_packages_by_week.append({'date': h.date_str_to_datetime(week_date), 'total_packages': cumulative_num_packages})

        c.raw_all_package_revisions = []
        for week_date, revs, num_revisions, cumulative_num_revisions in c.package_revisions_by_week:
            c.raw_all_package_revisions.append({'date': h.date_str_to_datetime(week_date), 'total_revisions': num_revisions})

        c.raw_new_datasets = []
        for week_date, pkgs, num_packages, cumulative_num_packages in c.new_packages_by_week:
            c.raw_new_datasets.append({'date': h.date_str_to_datetime(week_date), 'new_packages': num_packages})

        return p.toolkit.render('about/statistics.html', {'title': 'Statistics'})
github ckan / ckanext-qa / ckanext / qa / controllers.py View on Github external
parsed_url = urlparse.urlparse(url)
        path = parsed_url.path
        base, extension = posixpath.splitext(path)
        while extension:
            formats.append(extension[1:].upper())  # strip leading '.' from extension
            base, extension = posixpath.splitext(base)
        if formats:
            extension = '.'.join(formats[::-1]).lower()
            format_tuple = ckan_helpers.resource_formats().get(extension)
            if format_tuple:
                return format_tuple[1]
            return ' / '.join(formats[::-1])

        # No file extension found, attempt to extract format using the mimetype
        stripped_mimetype = self._extract_mimetype(headers)  # stripped of charset
        format_tuple = ckan_helpers.resource_formats().get(stripped_mimetype)
        if format_tuple:
            return format_tuple[1]

        extension = mimetypes.guess_extension(stripped_mimetype)
        if extension:
            return extension[1:].upper()