Beispiel #1
0
 def _ConvertValueMessage(self, value, message):
     """Convert a JSON representation into Value message."""
     if isinstance(value, dict):
         self._ConvertStructMessage(value, message.struct_value)
     elif isinstance(value, list):
         self._ConvertListValueMessage(value, message.list_value)
     elif value is None:
         message.null_value = 0
     elif isinstance(value, bool):
         message.bool_value = value
     elif isinstance(value, json_format.six.string_types):
         message.string_value = value
     elif isinstance(value, json_format._INT_OR_FLOAT):  # noqa
         message.number_value = value
     elif isinstance(value, date):
         message.string_value = value.isoformat()
     elif isinstance(value, datetime):
         if is_aware(value):
             value = value.astimezone(pytz.utc)
         message.string_value = value.isoformat()
     elif isinstance(value, Enum):
         message.string_value = value.name
     elif isinstance(value, Decimal):
         message.string_value = str(value)
     else:
         raise json_format.ParseError(
             'Value {0} has unexpected type {1}.'.format(
                 value, type(value)))
Beispiel #2
0
def parse_doc_to_proto(document, proto_type):
    """Parse a single proto from a document."""
    proto = proto_type()
    try:
        json_format.Parse(json.dumps(document), proto)
    except json_format.ParseError as error:
        raise json_format.ParseError(
            'Error while parsing item {}: {}\n{}'.format(
                id, error, json.dumps(document, indent=2)))
    return proto
Beispiel #3
0
def parse_doc_to_proto(document: JsonType,
                       proto_type: Type[_ProtoType]) -> _ProtoType:
    """Parse a single proto from a document."""

    proto = proto_type()
    try:
        json_format.Parse(json.dumps(document), proto)
    except json_format.ParseError as error:
        raise json_format.ParseError(
            f'Error while parsing item {id}: {error}\n{json.dumps(document, indent=2)}'
        )
    return proto
Beispiel #4
0
def parse_doc_to_proto(document: JsonType,
                       proto_type: Type[_ProtoType]) -> _ProtoType:
    """Parse a single proto from a document."""

    proto = proto_type()
    to_delete = [k for k in document if k.startswith('_')]
    for k in to_delete:
        del document[k]
    try:
        json_format.ParseDict(document, proto)
    except json_format.ParseError as error:
        raise json_format.ParseError(
            f'Error while parsing item {id}: {error}\n{json.dumps(document, indent=2)}'
        )
    return proto