Coverage for /home/lvcong/PythonProjects/sanic-restful/sanic_restful/fields.py : 68%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
"Integer", "Arbitrary", "Nested", "List", "Raw", "Boolean", "Fixed", "Price"]
""" This is an encapsulating Exception in case of marshalling error. """
# just put the contextual representation of the error to hint on what # went wrong without exposing internals super().__init__(str(underlying_exception))
"""Helper for pulling a keyed value off various types of objects""" return key(obj) else:
else: return _get_value_for_keys( keys[1:], _get_value_for_key(keys[0], obj, default), default)
except (IndexError, TypeError, KeyError): pass return getattr(obj, key, default)
"""Helper for converting an object to a dictionary only if it is not dictionary already or an indexable object nor a simple type""" return None # make it idempotent for None
return obj.__marshallable__()
return dict(obj.__dict__)
"""Raw provides a base field class from which others should extend. It applies no formatting by default, and should only be used in cases where data does not need to be formatted before being serialized. Fields should throw a :class:`MarshallingException` in case of parsing problem.
:param default: The default value for the field, if no value is specified. :param attribute: If the public facing value differs from the internal value, use this to retrieve a different attribute from the response than the publicly named value. """
"""Formats a field's value. No-op by default - field classes that modify how the value of existing object keys should be presented should override this and apply the appropriate formatting.
:param value: The value to format :exception MarshallingException: In case of formatting problem
Ex::
class TitleCase(Raw): def format(self, value): return unicode(value).title() """ return value
"""Pulls the value for the given key from the object, applies the field's formatting and returns the result. If the key is not found in the object, returns the default value. Field classes that create values which do not require the existence of the key in the object should override this and return the desired value.
:exception MarshallingException: In case of formatting problem """
if self.attribute is None else self.attribute, obj)
return self.default
"""Allows you to nest one set of fields inside another. See :ref:`nested-field` for more information
:param dict nested: The dictionary to nest :param bool allow_null: Whether to return None instead of a dictionary with null keys, if a nested dictionary has all-null keys :param kwargs: If ``default`` keyword argument is present, a nested dictionary will be marshaled as its value if nested dictionary is all-null keys (e.g. lets you return an empty JSON object instead of null) """
self.nested = nested self.allow_null = allow_null super().__init__(**kwargs)
value = get_value(key if self.attribute is None else self.attribute, obj) if value is None: if self.allow_null: return None elif self.default is not None: return self.default
return marshal(value, self.nested)
""" Field for marshalling lists of other fields.
See :ref:`list-field` for more information.
:param cls_or_instance: The field type the list will contain. """
"flask_restful.fields.Raw") raise MarshallingException(error_msg) else: if not isinstance(cls_or_instance, Raw): raise MarshallingException(error_msg) self.container = cls_or_instance
# Convert all instances in typed list to container type value = list(value)
self.container.output( idx, val if (isinstance(val, dict) or (self.container.attribute and hasattr(val, self.container.attribute))) and not isinstance(self.container, Nested) and not type(self.container) is Raw else value) for idx, val in enumerate(value) ]
if self.attribute is None else self.attribute, data) # we cannot really test for external dict behavior
if value is None: return self.default
return [marshal(value, self.container.nested)]
""" Marshal a value as a string. Uses ``six.text_type`` so values will be converted to :class:`unicode` in python2 and :class:`str` in python3. """ except ValueError as ve: raise MarshallingException(ve)
""" Field for outputting an integer value.
:param int default: The default value for the field, if no value is specified. """
return self.default except ValueError as ve: raise MarshallingException(ve)
""" Field for outputting a boolean value.
Empty collections such as ``""``, ``{}``, ``[]``, etc. will be converted to ``False``. """
""" FormattedString is used to interpolate other values from the response into this field. The syntax for the source string is the same as the string :meth:`~str.format` method from the python stdlib.
Ex::
fields = { 'name': fields.String, 'greeting': fields.FormattedString("Hello {name}") } data = { 'name': 'Doug', } marshal(data, fields) """ """ :param string src_str: the string to format with the other values from the response. """
except (TypeError, IndexError) as error: raise MarshallingException(error)
""" A double as IEEE-754 double precision. ex : 3.141592653589793 3.1415926535897933e-06 3.141592653589793e+24 nan inf -inf """
except ValueError as ve: raise MarshallingException(ve)
""" A floating point number with an arbitrary precision ex: 634271127864378216478362784632784678324.23432 """
return str(MyDecimal(value))
""" Return a formatted datetime string in UTC. Supported formats are RFC 822 and ISO 8601.
See :func:`email.utils.formatdate` for more info on the RFC 822 format.
See :meth:`datetime.datetime.isoformat` for more info on the ISO 8601 format.
:param dt_format: ``'rfc822'`` or ``'iso8601'`` :type dt_format: str """
else: raise MarshallingException( 'Unsupported date format %s' % self.dt_format ) except AttributeError as ae: raise MarshallingException(ae)
""" A decimal number with a fixed precision. """ super().__init__(**kwargs) self.precision = MyDecimal('0.' + '0' * (decimals - 1) + '1')
dvalue = MyDecimal(value) if not dvalue.is_normal() and dvalue != ZERO: raise MarshallingException('Invalid Fixed precision number.') return str( dvalue.quantize(self.precision, rounding=ROUND_HALF_EVEN))
"""Alias for :class:`~fields.Fixed`"""
"""Turn a datetime object into a formatted date.
Example::
fields._rfc822(datetime(2011, 1, 1)) => "Sat, 01 Jan 2011 00:00:00 -0000"
:param dt: The datetime to transform :type dt: datetime :return: A RFC 822 formatted date string """
"""Turn a datetime object into an ISO8601 formatted date.
Example::
fields._iso8601(datetime(2012, 1, 1, 0, 0)) => "2012-01-01T00:00:00"
:param dt: The datetime to transform :type dt: datetime :return: A ISO 8601 formatted date string """ |