Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
@nillable_string
def datetime_to_string(cls, value):
if cls.Attributes.as_time_zone is not None and value.tzinfo is not None:
value = value.astimezone(cls.Attributes.as_time_zone) \
.replace(tzinfo=None)
format = cls.Attributes.format
if format is None:
ret_str = value.isoformat()
else:
ret_str = datetime.datetime.strftime(value, format)
string_format = cls.Attributes.string_format
if string_format is None:
return ret_str
else:
return string_format % ret_str
@nillable_string
def time_from_string(cls, string):
"""Expects ISO formatted times."""
match = _time_re.match(string)
if match is None:
raise ValidationError(string, "%%r does not match regex %r " %
_time_re.pattern)
fields = match.groupdict(0)
microsec = fields.get('sec_frac')
if microsec is None or microsec == 0:
microsec = 0
else:
# we only get the most significant 6 digits because that's what
# datetime can handle.
microsec = int(float(microsec) * 1e6)
@nillable_string
def from_base64(cls, value):
return File.Value(data=[base64.b64decode(value)])
@nillable_string
def from_urlsafe_base64(cls, value):
return [urlsafe_b64decode(_bytes_join(value))]
@nillable_string
def attachment_to_string(cls, value):
if not (value.data is None):
# the data has already been loaded, just encode
# and return the element
data = value.data
elif not (value.file_name is None):
# the data hasn't been loaded, but a file has been
# specified
data = open(value.file_name, 'rb').read()
else:
raise ValueError("Neither data nor a file_name has been specified")
return data
@nillable_string
def to_urlsafe_base64(cls, value):
return urlsafe_b64encode(_bytes_join(value))
@nillable_string
def integer_to_string(cls, value):
int(value) # sanity check
if cls.Attributes.format is None:
return str(value)
else:
return cls.Attributes.format % value
@nillable_string
def complex_model_base_to_string(cls, value):
raise TypeError("Only primitives can be serialized to string.")
@nillable_string
def to_base64(cls, value):
ostream = StringIO()
if not (value.data is None):
istream = StringIO(value.data)
elif not (value.file_name is None):
istream = open(value.file_name, 'rb')
else:
raise ValueError("Neither data nor a file_name has been specified")
base64.encode(istream, ostream)
ostream.seek(0)
return ostream.read()
@nillable_string
def decimal_from_string(cls, string):
if cls.Attributes.max_str_len is not None and len(string) > \
cls.Attributes.max_str_len:
raise ValidationError(string, "Decimal %%r longer than %d characters"
% cls.Attributes.max_str_len)
try:
return decimal.Decimal(string)
except decimal.InvalidOperation, e:
raise ValidationError(string, "%%r: %r" % e)