soussa77
soussa77

Reputation: 39

google cloud endpoints messages.Message to json python

How to decode messages.Message to JSON in python 2.7 for Google Cloud Endpoints Frameworks ? Especially when we have some nested messages. Endpoints version :

google-endpoints==2.4.5 and google-endpoints-api-management==1.3.0

from protorpc import messages

# messsage definition
class GPSCoord(messages.Message):
    """
    GPS data obj
    """
    latitude = messages.FloatField(1)
    longitude = messages.FloatField(2)


class Address(messages.Message):
    """
    Address objectt
    """
    type = messages.StringField(1)
    name = messages.StringField(2)
    number = messages.StringField(3)
    city = messages.StringField(4)
    zip_code = messages.IntegerField(5)
    gps_coord = messages.MessageField(GPSCoord, 6)

I tried to add a method "to_json" to messages definition but I had "MessageDefinitionError: May only use fields in message definitions. " exception.

It looks like a rudimentary operation but it's not that easy. Python SDK needs a huge improvement for this part.

Upvotes: 0

Views: 427

Answers (2)

saiyr
saiyr

Reputation: 2595

You should make use of the built-in Endpoints JSON code. This is not exact, but something like this:

from endpoints import protojson
p = protojson.EndpointsProtoJson()
p.decode_message(Address, '{...}')

Upvotes: 2

soussa77
soussa77

Reputation: 39

I developed my own solution finally, here the code :

def request_to_json(request):
    """
    Take a coming request (POST) and
    get JSON.
    """
    json_dict = {}

    for field in request.all_fields():
        if field.__class__.__name__ == 'MessageField':

            data = getattr(request, field.name)

            if data:
                if data.__class__.__name__ == 'FieldList':
                    json_dict.update({
                        field.name: [request_to_json(data[i]) for i in range(len(data))]
                    })

                else:
                    json_dict.update({
                        field.name: request_to_json(data)
                    })

        else:
            json_dict.update({
                field.name: getattr(request, field.name)
            })

    return json_dict

It considers the nested messages fields, the list fields and primitive fields. I tested it on POST requests and it works well.

Upvotes: 1

Related Questions