本文整理匯總了Python中django.utils.six.iteritems方法的典型用法代碼示例。如果您正苦於以下問題:Python six.iteritems方法的具體用法?Python six.iteritems怎麽用?Python six.iteritems使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類django.utils.six
的用法示例。
在下文中一共展示了six.iteritems方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: parse_time
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import iteritems [as 別名]
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)
示例2: parse_duration
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import iteritems [as 別名]
def parse_duration(value):
"""Parses a duration string and returns a datetime.timedelta.
The preferred format for durations in Django is '%d %H:%M:%S.%f'.
Also supports ISO 8601 representation.
"""
match = standard_duration_re.match(value)
if not match:
match = iso8601_duration_re.match(value)
if match:
kw = match.groupdict()
if kw.get('microseconds'):
kw['microseconds'] = kw['microseconds'].ljust(6, '0')
kw = {k: float(v) for k, v in six.iteritems(kw) if v is not None}
return datetime.timedelta(**kw)
示例3: add_update_values
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import iteritems [as 別名]
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 = self.get_meta().get_field(name)
direct = not (field.auto_created and not field.concrete) or not field.concrete
model = field.model._meta.concrete_model
if not direct or (field.is_relation and field.many_to_many):
raise FieldError(
'Cannot update model field %r (only non-relations and '
'foreign keys permitted).' % field
)
if model is not self.get_meta().model:
self.add_related_update(model, field, val)
continue
values_seq.append((field, model, val))
return self.add_update_fields(values_seq)
示例4: get_related_updates
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import iteritems [as 別名]
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
示例5: set_group_by
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import iteritems [as 別名]
def set_group_by(self):
"""
Expands the GROUP BY clause required by the query.
This will usually be the set of all non-aggregate fields in the
return data. If the database backend supports grouping by the
primary key, and the query would be equivalent, the optimization
will be made automatically.
"""
self.group_by = []
for col in self.select:
self.group_by.append(col)
if self._annotations:
for alias, annotation in six.iteritems(self.annotations):
for col in annotation.get_group_by_cols():
self.group_by.append(col)
示例6: update_or_create
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import iteritems [as 別名]
def update_or_create(self, defaults=None, **kwargs):
"""
Looks up an object with the given kwargs, updating one with defaults
if it exists, otherwise creates a new one.
Returns a tuple (object, created), where created is a boolean
specifying whether an object was created.
"""
defaults = defaults or {}
lookup, params = self._extract_model_params(defaults, **kwargs)
self._for_write = True
try:
obj = self.get(**lookup)
except self.model.DoesNotExist:
obj, created = self._create_object_from_params(lookup, params)
if created:
return obj, created
for k, v in six.iteritems(defaults):
setattr(obj, k, v)
with transaction.atomic(using=self.db, savepoint=False):
obj.save(using=self.db)
return obj, False
示例7: render
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import iteritems [as 別名]
def render(self, context):
try:
template = self.template.resolve(context)
# Does this quack like a Template?
if not callable(getattr(template, 'render', None)):
# If not, we'll try get_template
template = context.template.engine.get_template(template)
values = {
name: var.resolve(context)
for name, var in six.iteritems(self.extra_context)
}
if self.isolated_context:
return template.render(context.new(values))
with context.push(**values):
return template.render(context)
except Exception:
if context.template.engine.debug:
raise
return ''
示例8: changes_str
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import iteritems [as 別名]
def changes_str(self, colon=': ', arrow=smart_text(' \u2192 '), separator='; '):
"""
Return the changes recorded in this log entry as a string.
The formatting of the string can be customized by
setting alternate values for colon, arrow and separator.
If the formatting is still not satisfying, please use
:py:func:`LogAction.changes_dict` and format the string yourself.
:param colon: The string to place between the field name and the values.
:param arrow: The string to place between each old and new value.
:param separator: The string to place between each field.
:return: A readable string of the changes in this log entry.
"""
substrings = []
for field, values in iteritems(self.changes_dict):
substring = smart_text('{field_name:s}{colon:s}{old:s}{arrow:s}{new:s}').format(
field_name=field,
colon=colon,
old=values[0],
arrow=arrow,
new=values[1],
)
substrings.append(substring)
return separator.join(substrings)
示例9: _to_xml
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import iteritems [as 別名]
def _to_xml(self, xml, data):
if isinstance(data, (list, tuple)):
for item in data:
xml.startElement(self.element_node, {})
self._to_xml(xml, item)
xml.endElement(self.element_node)
elif isinstance(data, dict):
for key, value in six.iteritems(data):
xml.startElement(key, {})
self._to_xml(xml, value)
xml.endElement(key)
elif data is None:
# Don't output any value
pass
else:
xml.characters(smart_text(data))
示例10: get_user_obj
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import iteritems [as 別名]
def get_user_obj(self,username=None,attribute_list=[],metadata={},attr_map={}):
user_attrs = cognito_to_dict(attribute_list,CognitoUser.COGNITO_ATTR_MAPPING)
django_fields = [f.name for f in CognitoUser.user_class._meta.get_fields()]
extra_attrs = {}
for k, v in user_attrs.items():
if k not in django_fields:
extra_attrs.update({k: user_attrs.pop(k, None)})
if getattr(settings, 'COGNITO_CREATE_UNKNOWN_USERS', True):
user, created = CognitoUser.user_class.objects.update_or_create(
username=username,
defaults=user_attrs)
else:
try:
user = CognitoUser.user_class.objects.get(username=username)
for k, v in iteritems(user_attrs):
setattr(user, k, v)
user.save()
except CognitoUser.user_class.DoesNotExist:
user = None
if user:
for k, v in extra_attrs.items():
setattr(user, k, v)
return user
示例11: parse_duration
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import iteritems [as 別名]
def parse_duration(value):
"""Parses a duration string and returns a datetime.timedelta.
Unlike the standard Django 1.8 function, this only accepts ISO 8601 durations.
"""
match = iso8601_duration_re.match(value)
if match:
kw = match.groupdict()
kw = {k: float(v) for k, v in six.iteritems(kw) if v is not None}
return datetime.timedelta(**kw)
# Hack to fix ISO8601 for datetime filters.
# This should be taken care of by a future Django fix. And might even be handled
# by a newer version of django-rest-framework. Unfortunately, both of these solutions
# will accept datetimes without timezone information which we do not want to allow
# see https://code.djangoproject.com/tickets/23448
# Solution modified from http://akinfold.blogspot.com/2012/12/datetimefield-doesnt-accept-iso-8601.html
示例12: _validate_patch_all
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import iteritems [as 別名]
def _validate_patch_all(self, data):
if not isinstance(data, dict):
raise ValidationError(
'Patch-all data must be in object form'
)
serializer = self.get_serializer()
fields = serializer.get_all_fields()
validated = {}
for name, value in six.iteritems(data):
field = fields.get(name, None)
if field is None:
raise ValidationError(
'Unknown field: "%s"' % name
)
source = field.source or name
if source == '*' or field.read_only:
raise ValidationError(
'Cannot update field: "%s"' % name
)
validated[source] = value
return validated
示例13: _patch_all_loop
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import iteritems [as 別名]
def _patch_all_loop(self, queryset, data):
# update by transaction loop
updated = 0
try:
with transaction.atomic():
for record in queryset:
for k, v in six.iteritems(data):
setattr(record, k, v)
record.save()
updated += 1
return updated
except IntegrityError as e:
raise ValidationError(
'Failed to update records:\n'
'%s\n'
'Data: %s' % (
str(e),
str(data)
)
)
示例14: _get_implicit_requirements
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import iteritems [as 別名]
def _get_implicit_requirements(
self,
fields,
requirements
):
"""Extract internal prefetch requirements from serializer fields."""
for name, field in six.iteritems(fields):
source = field.source
# Requires may be manually set on the field -- if not,
# assume the field requires only its source.
requires = getattr(field, 'requires', None) or [source]
for require in requires:
if not require:
# ignore fields with empty source
continue
requirement = require.split('.')
if requirement[-1] == '':
# Change 'a.b.' -> 'a.b.*',
# supporting 'a.b.' for backwards compatibility.
requirement[-1] = '*'
requirements.insert(requirement, TreeMap(), update=True)
示例15: _link_fields
# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import iteritems [as 別名]
def _link_fields(self):
"""Construct dict of name:field for linkable fields."""
query_params = self.get_request_attribute('query_params', {})
if 'exclude_links' in query_params:
return {}
else:
all_fields = self.get_all_fields()
return {
name: field for name, field in six.iteritems(all_fields)
if isinstance(field, DynamicRelationField) and
getattr(field, 'link', True) and
not (
# Skip sideloaded fields
name in self.fields and
self.is_field_sideloaded(name)
) and not (
# Skip included single relations
# TODO: Use links, when we can generate canonical URLs
name in self.fields and
not getattr(field, 'many', False)
)
}