django.utils.six.iteritems - python examples

Here are the examples of the python api django.utils.six.iteritems taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

145 Examples 7

3 View Complete Implementation : datastructures.py
Copyright GNU General Public License v2.0
Author : blackye
    def _iteritems(self):
        seen = set()
        for dict_ in self.dicts:
            for item in six.iteritems(dict_):
                k = item[0]
                if k in seen:
                    continue
                seen.add(k)
                yield item

3 View Complete Implementation : dateparse.py
Copyright MIT License
Author : bpgc-cte
def parse_time(value):
    """Parses a string and return a datetime.time.

    This function doesn't support time zone offsets.

    Raises ValueError if the input is well formatted but not a valid time.
    Returns None if the input isn't well formatted, in particular if it
    contains an offset.
    """
    match = time_re.match(value)
    if match:
        kw = match.groupdict()
        if kw['microsecond']:
            kw['microsecond'] = kw['microsecond'].ljust(6, '0')
        kw = {k: int(v) for k, v in six.iteritems(kw) if v is not None}
        return datetime.time(**kw)

3 View Complete Implementation : html.py
Copyright GNU General Public License v2.0
Author : blackye
def format_html(format_string, *args, **kwargs):
    """
    Similar to str.format, but pastes all arguments through conditional_escape,
    and calls 'mark_safe' on the result. This function should be used instead
    of str.format or % interpolation to build up small HTML fragments.
    """
    args_safe = map(conditional_escape, args)
    kwargs_safe = dict([(k, conditional_escape(v)) for (k, v) in
                        six.iteritems(kwargs)])
    return mark_safe(format_string.format(*args_safe, **kwargs_safe))

3 View Complete Implementation : datastructures.py
Copyright GNU General Public License v2.0
Author : blackye
    def __repr__(self):
        """
        Replaces the normal dict.__repr__ with a version that returns the keys
        in their sorted order.
        """
        return '{%s}' % ', '.join(['%r: %r' % (k, v) for k, v in six.iteritems(self)])

3 View Complete Implementation : entity.py
Copyright GNU General Public License v3.0
Author : Uninett
    def index_by_name(self):
        """
        Builds and returns a dict indexing contained ensaties by their unique
        ensaty names, if they have one.
        """
        by_name = defaultdict(list)
        for ent in self.ensaties:
            if ent.name:
                by_name[(ent.source, ent.name)].append(ent)
        by_name = {k: v[0] for k, v in iteritems(by_name) if len(v) == 1}
        return by_name

3 View Complete Implementation : subqueries.py
Copyright GNU General Public License v2.0
Author : blackye
    def add_update_values(self, values):
        """
        Convert a dictionary of field name to value mappings into an update
        query. This is the entry point for the public update() method on
        querysets.
        """
        values_seq = []
        for name, val in six.iteritems(values):
            field, model, direct, m2m = self.model._meta.get_field_by_name(name)
            if not direct or m2m:
                raise FieldError('Cannot update model field %r (only non-relations and foreign keys permitted).' % field)
            if model:
                self.add_related_update(model, field, val)
                continue
            values_seq.append((field, model, val))
        return self.add_update_fields(values_seq)

3 View Complete Implementation : utils.py
Copyright Apache License 2.0
Author : erigones
def get_query_string(request, **kwargs):
    """
    Conditional query string creator. Only useful for boolean parameters.
    """
    qs = QueryDict('', mutable=True)

    for name, condition in iteritems(kwargs):
        try:
            value = request.GET[name]
        except KeyError:
            past
        else:
            if condition and value:
                qs[name] = 1

    return qs

3 View Complete Implementation : loader_tags.py
Copyright Apache License 2.0
Author : edisonlz
    def render_template(self, template, context):
        values = dict([(name, var.resolve(context)) for name, var
                       in six.iteritems(self.extra_context)])
        if self.isolated_context:
            return template.render(context.new(values))
        context.update(values)
        output = template.render(context)
        context.pop()
        return output

3 View Complete Implementation : spagent_mib.py
Copyright GNU General Public License v3.0
Author : Uninett
    @defer.inlineCallbacks
    def get_all_sensors(self):
        """Returns a Deferred whose result is a list of sensor dictionaries"""
        result = []
        for table, config in iteritems(SENSOR_TABLES):
            sensors = yield self._get_sensors(config)
            result.extend(sensors)
        defer.returnValue(result)

3 View Complete Implementation : base.py
Copyright Apache License 2.0
Author : edisonlz
    def __init__(self, **kwargs):
        """
        Constructor. Called in the URLconf; can contain helpful extra
        keyword arguments, and other things.
        """
        # Go through keyword arguments, and either save their values to our
        # instance, or raise an error.
        for key, value in six.iteritems(kwargs):
            setattr(self, key, value)

3 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : Uninett
def _strip_empty_arguments(request):
    """Strips empty arguments and their related operator arguments from the
    QueryDict in request.GET and returns a new, possibly modified QueryDict.

    """
    query = request.GET.copy()

    deletable = [key for key, value in iteritems(query) if not value.strip()]
    for key in deletable:
        del query[key]
        if "op_{0}".format(key) in query:
            del query["op_{0}".format(key)]
        if "not_{0}".format(key) in query:
            del query["not_{0}".format(key)]

    return query

3 View Complete Implementation : cpqpower_mib.py
Copyright GNU General Public License v3.0
Author : Uninett
    @defer.inlineCallbacks
    def _get_sensors(self, names, sensors, extra_columns=None,
                     filter=lambda x: True):
        if extra_columns is None:
            extra_columns = []
        entries = yield self.retrieve_columns(
            extra_columns + list(sensors.keys()))
        entries = self.translate_result(entries)

        result = []
        for index, row in iteritems(entries):
            if not filter(row):
                continue
            result.extend(self._mksensors(index, row, sensors, names))
        defer.returnValue(result)

3 View Complete Implementation : options.py
Copyright Apache License 2.0
Author : edisonlz
    def get_m2m_with_model(self):
        """
        The many-to-many version of get_fields_with_model().
        """
        try:
            self._m2m_cache
        except AttributeError:
            self._fill_m2m_cache()
        return list(six.iteritems(self._m2m_cache))

3 View Complete Implementation : loader_tags.py
Copyright GNU General Public License v2.0
Author : blackye
    def render_template(self, template, context):
        values = dict([(name, var.resolve(context)) for name, var
                       in six.iteritems(self.extra_context)])
        if self.isolated_context:
            return template.render(context.new(values))
        context.update(values)
        output = template.render(context)
        context.pop()
        return output

3 View Complete Implementation : subqueries.py
Copyright Apache License 2.0
Author : edisonlz
    def get_related_updates(self):
        """
        Returns a list of query objects: one for each update required to an
        ancestor model. Each query will have the same filtering conditions as
        the current query but will only update a single table.
        """
        if not self.related_updates:
            return []
        result = []
        for model, values in six.iteritems(self.related_updates):
            query = UpdateQuery(model)
            query.values = values
            if self.related_ids is not None:
                query.add_filter(('pk__in', self.related_ids))
            result.append(query)
        return result

3 View Complete Implementation : __init__.py
Copyright GNU General Public License v2.0
Author : blackye
    def get_primary_key_column(self, cursor, table_name):
        """
        Returns the name of the primary key column for the given table.
        """
        for column in six.iteritems(self.get_indexes(cursor, table_name)):
            if column[1]['primary_key']:
                return column[0]
        return None

3 View Complete Implementation : subqueries.py
Copyright GNU General Public License v2.0
Author : blackye
    def get_related_updates(self):
        """
        Returns a list of query objects: one for each update required to an
        ancestor model. Each query will have the same filtering conditions as
        the current query but will only update a single table.
        """
        if not self.related_updates:
            return []
        result = []
        for model, values in six.iteritems(self.related_updates):
            query = UpdateQuery(model)
            query.values = values
            if self.related_ids is not None:
                query.add_filter(('pk__in', self.related_ids))
            result.append(query)
        return result

3 View Complete Implementation : response.py
Copyright Apache License 2.0
Author : erigones
def to_string(x, quote_string=True):
    """Format value so it can be used for task log detail"""
    if isinstance(x, string_types):
        if quote_string:
            return "'%s'" % x
        else:
            return '%s' % x
    elif isinstance(x, bool):
        return str(x).lower()
    elif isinstance(x, (int, float)):
        return str(x)
    elif isinstance(x, NoneType):
        return 'null'
    elif isinstance(x, dict):
        return to_string(','.join('%s:%s' % (to_string(k, quote_string=False), to_string(v, quote_string=False))
                                  for k, v in iteritems(x)))
    elif isinstance(x, (list, tuple)):
        return to_string(','.join(to_string(i, quote_string=False) for i in x))
    return to_string(str(x))

3 View Complete Implementation : base.py
Copyright Apache License 2.0
Author : edisonlz
    def get_step_files(self, step):
        wizard_files = self.data[self.step_files_key].get(step, {})

        if wizard_files and not self.file_storage:
            raise NoFileStorageConfigured(
                    "You need to define 'file_storage' in your "
                    "wizard view in order to handle file uploads.")

        files = {}
        for field, field_dict in six.iteritems(wizard_files):
            field_dict = field_dict.copy()
            tmp_name = field_dict.pop('tmp_name')
            files[field] = UploadedFile(
                file=self.file_storage.open(tmp_name), **field_dict)
        return files or None

3 View Complete Implementation : utils.py
Copyright Apache License 2.0
Author : erigones
    def update2(self, d2):
        """
        Recursive dict.update() - http://stackoverflow.com/a/3233356
        """
        def update(d, u):
            for k, v in iteritems(u):
                if isinstance(v, collections.Mapping):
                    r = update(d.get(k, {}), v)
                    d[k] = r
                else:
                    d[k] = u[k]

            return d

        # noinspection PyMethodFirstArgastignment,PyUnusedLocal
        self = update(self, d2)

        return None

3 View Complete Implementation : thresholds.py
Copyright GNU General Public License v3.0
Author : Uninett
    def get_values(self):
        """
        Retrieves actual values from Graphite based on the evaluators target.
        """
        start = "-{0}".format(interval_to_graphite(self.period))
        averages = get_metric_average(
            self.target, start=start, end='now', ignore_unknown=True)
        _logger.debug("retrieved %d values from graphite for %r, "
                      "period %s: %r",
                      len(averages), self.target, self.period, averages)
        self.result = dict((extract_series_name(key), dict(value=value))
                           for key, value in iteritems(averages))
        return self.result

3 View Complete Implementation : spagent_mib.py
Copyright GNU General Public License v3.0
Author : Uninett
    @defer.inlineCallbacks
    def _get_sensors(self, config):
        """
        Collects sensor columns according to the config dict, and translates
        the results into sensor dicts.

        """
        columns = [config['descr'], config['online']]
        if 'unit' in config:
            columns.append(config['unit'])

        result = yield self.retrieve_columns(columns).addCallback(
            self.translate_result).addCallback(reduce_index)

        sensors = (self._row_to_sensor(config, index, row)
                   for index, row in iteritems(result))

        defer.returnValue([s for s in sensors if s])

3 View Complete Implementation : subqueries.py
Copyright Apache License 2.0
Author : edisonlz
    def add_update_values(self, values):
        """
        Convert a dictionary of field name to value mappings into an update
        query. This is the entry point for the public update() method on
        querysets.
        """
        values_seq = []
        for name, val in six.iteritems(values):
            field, model, direct, m2m = self.get_meta().get_field_by_name(name)
            if not direct or m2m:
                raise FieldError('Cannot update model field %r (only non-relations and foreign keys permitted).' % field)
            if model:
                self.add_related_update(model, field, val)
                continue
            values_seq.append((field, model, val))
        return self.add_update_fields(values_seq)

3 View Complete Implementation : entity_mib.py
Copyright GNU General Public License v3.0
Author : Uninett
    def _get_non_chastis_duplicates(self):
        """
        Returns a dict of all ensaties that have non-unique names.

        :returns: dict(name=[list of at least 2 ensaties with this name], ...)

        """
        dupes = defaultdict(list)
        for ent in self.values():
            if not self.is_chastis(ent):
                dupes[ent['entPhysicalName']].append(ent)
        dupes = dict((key, value) for key, value in iteritems(dupes)
                     if len(value) > 1)
        return dupes

3 View Complete Implementation : datastructures.py
Copyright Apache License 2.0
Author : edisonlz
    def _iteritems(self):
        seen = set()
        for dict_ in self.dicts:
            for item in six.iteritems(dict_):
                k = item[0]
                if k in seen:
                    continue
                seen.add(k)
                yield item

3 View Complete Implementation : utils.py
Copyright GNU General Public License v3.0
Author : Uninett
def filter_dict(fun, dct):
    """Filter a dictionary on values.

    Like the built-in filter, except that dct is a dictionary, and fun
    is applied to each value. The result is a new dictionary
    containing those (key,value) pairs from dct for which fun(value) is
    true.

    """
    return subdict(dct, [key for key, val in iteritems(dct) if fun(val)])

3 View Complete Implementation : cisco_process_mib.py
Copyright GNU General Public License v3.0
Author : Uninett
    @defer.inlineCallbacks
    def get_cpu_loadavg(self):
        load = yield self.retrieve_columns([
            PHYSICAL_INDEX,
            TOTAL_5_MIN_REV,
            TOTAL_1_MIN_REV,
        ])
        self._logger.debug("cpu load results: %r", load)
        physindexes = [row[PHYSICAL_INDEX] for row in itervalues(load)
                       if row[PHYSICAL_INDEX]]
        names = yield self._get_cpu_names(physindexes)

        result = {}
        for index, row in iteritems(load):
            name = names.get(row[PHYSICAL_INDEX], str(index[-1]))
            result[name] = [(5, row[TOTAL_5_MIN_REV]),
                            (1, row[TOTAL_1_MIN_REV])]
        defer.returnValue(result)

3 View Complete Implementation : __init__.py
Copyright Apache License 2.0
Author : edisonlz
    def get_primary_key_column(self, cursor, table_name):
        """
        Returns the name of the primary key column for the given table.
        """
        for column in six.iteritems(self.get_indexes(cursor, table_name)):
            if column[1]['primary_key']:
                return column[0]
        return None

3 View Complete Implementation : options.py
Copyright GNU General Public License v2.0
Author : blackye
    def get_m2m_with_model(self):
        """
        The many-to-many version of get_fields_with_model().
        """
        try:
            self._m2m_cache
        except AttributeError:
            self._fill_m2m_cache()
        return list(six.iteritems(self._m2m_cache))

3 View Complete Implementation : cookie.py
Copyright Apache License 2.0
Author : edisonlz
    def process_messages(self, obj):
        if isinstance(obj, list) and obj:
            if obj[0] == MessageEncoder.message_key:
                if obj[1]:
                    obj[3] = mark_safe(obj[3])
                return Message(*obj[2:])
            return [self.process_messages(item) for item in obj]
        if isinstance(obj, dict):
            return dict([(key, self.process_messages(value))
                         for key, value in six.iteritems(obj)])
        return obj

3 View Complete Implementation : base.py
Copyright GNU General Public License v2.0
Author : blackye
    def __init__(self, **kwargs):
        """
        Constructor. Called in the URLconf; can contain helpful extra
        keyword arguments, and other things.
        """
        # Go through keyword arguments, and either save their values to our
        # instance, or raise an error.
        for key, value in six.iteritems(kwargs):
            setattr(self, key, value)

3 View Complete Implementation : options.py
Copyright GNU General Public License v2.0
Author : blackye
    def get_all_related_m2m_objects_with_model(self):
        """
        Returns a list of (related-m2m-object, model) pairs. Similar to
        get_fields_with_model().
        """
        try:
            cache = self._related_many_to_many_cache
        except AttributeError:
            cache = self._fill_related_many_to_many_cache()
        return list(six.iteritems(cache))

3 View Complete Implementation : loader_tags.py
Copyright GNU General Public License v2.0
Author : blackye
    def add_blocks(self, blocks):
        for name, block in six.iteritems(blocks):
            if name in self.blocks:
                self.blocks[name].insert(0, block)
            else:
                self.blocks[name] = [block]

3 View Complete Implementation : dateparse.py
Copyright Apache License 2.0
Author : edisonlz
def parse_date(value):
    """Parses a string and return a datetime.date.

    Raises ValueError if the input is well formatted but not a valid date.
    Returns None if the input isn't well formatted.
    """
    match = date_re.match(value)
    if match:
        kw = dict((k, int(v)) for k, v in six.iteritems(match.groupdict()))
        return datetime.date(**kw)

3 View Complete Implementation : defaulttags.py
Copyright GNU General Public License v2.0
Author : blackye
    def render(self, context):
        values = dict([(key, val.resolve(context)) for key, val in
                       six.iteritems(self.extra_context)])
        context.update(values)
        output = self.nodelist.render(context)
        context.pop()
        return output

3 View Complete Implementation : dateparse.py
Copyright GNU General Public License v2.0
Author : blackye
def parse_time(value):
    """Parses a string and return a datetime.time.

    This function doesn't support time zone offsets.

    Raises ValueError if the input is well formatted but not a valid time.
    Returns None if the input isn't well formatted, in particular if it
    contains an offset.
    """
    match = time_re.match(value)
    if match:
        kw = match.groupdict()
        if kw['microsecond']:
            kw['microsecond'] = kw['microsecond'].ljust(6, '0')
        kw = dict((k, int(v)) for k, v in six.iteritems(kw) if v is not None)
        return datetime.time(**kw)

3 View Complete Implementation : dateparse.py
Copyright MIT License
Author : bpgc-cte
def parse_date(value):
    """Parses a string and return a datetime.date.

    Raises ValueError if the input is well formatted but not a valid date.
    Returns None if the input isn't well formatted.
    """
    match = date_re.match(value)
    if match:
        kw = {k: int(v) for k, v in six.iteritems(match.groupdict())}
        return datetime.date(**kw)

3 View Complete Implementation : sites.py
Copyright Apache License 2.0
Author : edisonlz
    @property
    def actions(self):
        """
        Get all the enabled actions as an iterable of (name, func).
        """
        return six.iteritems(self._actions)

3 View Complete Implementation : serializers.py
Copyright GNU General Public License v3.0
Author : Uninett
    def update(self, instance, validated_data):
        new_categories = set(validated_data.pop('categories'))

        for key, value in iteritems(validated_data):
            setattr(instance, key, value)
        instance.save()

        self._update_categories(instance, new_categories)
        return instance

3 View Complete Implementation : dateparse.py
Copyright GNU General Public License v2.0
Author : blackye
def parse_date(value):
    """Parses a string and return a datetime.date.

    Raises ValueError if the input is well formatted but not a valid date.
    Returns None if the input isn't well formatted.
    """
    match = date_re.match(value)
    if match:
        kw = dict((k, int(v)) for k, v in six.iteritems(match.groupdict()))
        return datetime.date(**kw)

3 View Complete Implementation : utils.py
Copyright Apache License 2.0
Author : erigones
def process_errors(data, vm_details, row_no):
    """
    Common api error parser like in SerializerForm._set_api_errors()
    """
    errors = data.get('result', data)
    if errors:
        if 'non_field_errors' in errors:
            header_type = 'hostname'
            if errors['non_field_errors'] == ['Cannot find free IP address for net testlan.']:
                header_type = 'ip'
            vm_details['html_rows'][row_no]['errors'][header_type] = format_error(errors['non_field_errors'])
        elif 'detail' in errors:
            vm_details['html_rows'][row_no]['errors']['hostname'] = format_error(errors['detail'])
        else:
            ieb = ImportExportBase()
            for header_type, error_message in iteritems(errors):
                header_type = ieb.convert_header_to_file_header(header_type)
                vm_details['html_rows'][row_no]['errors'][header_type] = format_error(error_message)
    return vm_details

3 View Complete Implementation : base.py
Copyright Apache License 2.0
Author : edisonlz
    def set_step_files(self, step, files):
        if files and not self.file_storage:
            raise NoFileStorageConfigured(
                    "You need to define 'file_storage' in your "
                    "wizard view in order to handle file uploads.")

        if step not in self.data[self.step_files_key]:
            self.data[self.step_files_key][step] = {}

        for field, field_file in six.iteritems(files or {}):
            tmp_filename = self.file_storage.save(field_file.name, field_file)
            file_dict = {
                'tmp_name': tmp_filename,
                'name': field_file.name,
                'content_type': field_file.content_type,
                'size': field_file.size,
                'charset': field_file.charset
            }
            self.data[self.step_files_key][step][field] = file_dict

3 View Complete Implementation : subqueries.py
Copyright MIT License
Author : bpgc-cte
    def get_related_updates(self):
        """
        Returns a list of query objects: one for each update required to an
        ancestor model. Each query will have the same filtering conditions as
        the current query but will only update a single table.
        """
        if not self.related_updates:
            return []
        result = []
        for model, values in six.iteritems(self.related_updates):
            query = UpdateQuery(model)
            query.values = values
            if self.related_ids is not None:
                query.add_filter(('pk__in', self.related_ids))
            result.append(query)
        return result

3 View Complete Implementation : schedule.py
Copyright GNU General Public License v3.0
Author : Uninett
    def flush(self):
        """
        Flushes all the counters to the Carbon backend and resets them to zero
        """
        if not self:
            _logger.debug("no counters to flush yet")

        _logger.debug("flushing %d counters to graphite", len(self))
        metrics = []
        timestamp = time.time()
        for counter, count in iteritems(self):
            metrics.append((counter, (timestamp, count)))
            self[counter] = 0

        send_metrics(metrics)

3 View Complete Implementation : tests.py
Copyright Apache License 2.0
Author : edisonlz
    def test_iteritems(self):
        self.session['x'] = 1
        self.session.modified = False
        self.session.accessed = False
        i = six.iteritems(self.session)
        self.astertTrue(hasattr(i, '__iter__'))
        self.astertTrue(self.session.accessed)
        self.astertFalse(self.session.modified)
        self.astertEqual(list(i), [('x', 1)])

3 View Complete Implementation : options.py
Copyright Apache License 2.0
Author : edisonlz
    def get_all_related_m2m_objects_with_model(self):
        """
        Returns a list of (related-m2m-object, model) pairs. Similar to
        get_fields_with_model().
        """
        try:
            cache = self._related_many_to_many_cache
        except AttributeError:
            cache = self._fill_related_many_to_many_cache()
        return list(six.iteritems(cache))

3 View Complete Implementation : dateparse.py
Copyright Apache License 2.0
Author : edisonlz
def parse_time(value):
    """Parses a string and return a datetime.time.

    This function doesn't support time zone offsets.

    Raises ValueError if the input is well formatted but not a valid time.
    Returns None if the input isn't well formatted, in particular if it
    contains an offset.
    """
    match = time_re.match(value)
    if match:
        kw = match.groupdict()
        if kw['microsecond']:
            kw['microsecond'] = kw['microsecond'].ljust(6, '0')
        kw = dict((k, int(v)) for k, v in six.iteritems(kw) if v is not None)
        return datetime.time(**kw)

3 View Complete Implementation : html.py
Copyright Apache License 2.0
Author : edisonlz
def format_html(format_string, *args, **kwargs):
    """
    Similar to str.format, but pastes all arguments through conditional_escape,
    and calls 'mark_safe' on the result. This function should be used instead
    of str.format or % interpolation to build up small HTML fragments.
    """
    args_safe = map(conditional_escape, args)
    kwargs_safe = dict([(k, conditional_escape(v)) for (k, v) in
                        six.iteritems(kwargs)])
    return mark_safe(format_string.format(*args_safe, **kwargs_safe))

3 View Complete Implementation : datastructures.py
Copyright Apache License 2.0
Author : edisonlz
    def __repr__(self):
        """
        Replaces the normal dict.__repr__ with a version that returns the keys
        in their sorted order.
        """
        return '{%s}' % ', '.join(['%r: %r' % (k, v) for k, v in six.iteritems(self)])

3 View Complete Implementation : entity.py
Copyright GNU General Public License v3.0
Author : Uninett
    def index_by_serial(self):
        """
        Builds and returns a dict indexing contained ensaties by their unique
        serial numbers, if they have one.
        """
        by_serial = defaultdict(list)
        for ent in self.ensaties:
            if ent.device and ent.device.serial:
                by_serial[(ent.source, ent.device.serial)].append(ent)
        by_serial = {k: v[0] for k, v in iteritems(by_serial) if len(v) == 1}
        return by_serial