def to_dict(obj):
"""Helper to flatten models into dicts for rendering.
The following conversions are applied:
* datetime.date, datetime.datetime, datetime.time
are converted into ISO8601 UTC strings
"""
# Shortcut strings so they don't count as Iterables
if isinstance(obj, six.string_types):
return obj
elif obj is NONE_SENTINEL:
return None
elif isinstance(obj, (datetime.datetime, datetime.time)):
# always use UTC
if not obj.tzinfo:
obj = pytz.utc.localize(obj)
if isinstance(obj, datetime.datetime):
# only datetime.datetime takes a separator
return obj.isoformat(sep="T")
return obj.isoformat()
elif isinstance(obj, datetime.date):
# datetime.date doesn't have a timezone
return obj.isoformat()
elif isinstance(obj, abc.Mapping):
return {k: to_dict(v) for k, v in six.iteritems(obj)}
elif isinstance(obj, abc.Iterable):
return [to_dict(v) for v in obj]
# Not a string, datetime, dict, list, or model - return directly
elif not hasattr(obj, "swagger_types"):
return obj
# Collect attrs from obj according to swagger_types into a dict
as_dict = {}
for key in six.iterkeys(obj.swagger_types):
value = getattr(obj, key, missing_attr)
if value is not missing_attr:
as_dict[key] = to_dict(value)
return as_dict
评论列表
文章目录