如何返回动态json作为谷歌云端点python的响应

时间:2016-05-03 19:28:09

标签: python google-app-engine google-cloud-endpoints

我希望以下json从google端点返回

{"arts":[{"id":"4","name":"punjabi"},{"id":"5","name":"hindi"}],"Science":[{"id":"1","name":"MCA"},{"id":"2","name":"physics"},{"id":"3","name":"chemistry"}]}

以下是我如何声明我的终结点

@endpoints.method(TokenAsInput,GetDepartmentListOutput,
                          path='getdepartmentlist', http_method='GET',
                          name='GetDepartmentList')
    def getDepartmentList(self,request):
        objResult = GetDepartmentListOutput()
        objResult.data = dynamicJson
        return objResult

但我不知道如何声明GetDepartmentListOutput以便它可以映射上面的JSON。对象'arts','science'是动态的,可能存在也可能不存在。

1 个答案:

答案 0 :(得分:5)

我使用ProtoRpc消息(构成Cloud Endpoints的基础)并使用以下命令返回一般的Json消息数据:

from protorpc import messages

class DetailMessage(messages.Message):
    """
    General-format Json detail response
    """
    data = GeneralField(1)

设置结果:

data = {"arts":[{"id":"4","name":"punjabi"},{"id":"5","name":"hindi"}],"Science":[{"id":"1","name":"MCA"},{"id":"2","name":"physics"},{"id":"3","name":"chemistry"}]}
return DetailMessage(data=data)

GeneralField定义为:

class GeneralField(messages.Field):
    """
    Allow for normal non-Message objects to be serialised to JSON.
    This allows for variable result objects or dictionaries to be returned (Note: these objects must be Json serialisable).
    """
    VARIANTS = frozenset([messages.Variant.MESSAGE])

    DEFAULT_VARIANT = messages.Variant.MESSAGE

    def __init__(self,
                             number,
                             required=False,
                             repeated=False,
                             variant=None):
        """Constructor.

        Args:
            number: Number of field.  Must be unique per message class.
            required: Whether or not field is required.  Mutually exclusive to
                'repeated'.
            repeated: Whether or not field is repeated.  Mutually exclusive to
                'required'.
            variant: Wire-format variant hint.

        Raises:
            FieldDefinitionError when invalid message_type is provided.
        """
        super(GeneralField, self).__init__(number,
                                                                             required=required,
                                                                             repeated=repeated,
                                                                             variant=variant)

    def __set__(self, message_instance, value):
        """Set value on message.

        Args:
            message_instance: Message instance to set value on.
            value: Value to set on message.
        """
        if isinstance(value, list):
            if len(value) > 0:
                self.type = type(value[0])
            else:
                self.type = type(self) 
        else:
            self.type = type(value)
        self.__initialized = True

        super(GeneralField, self).__set__(message_instance, value)

    def __setattr__(self, name, value):
        """Setter overidden to allow assignment to fields after creation.

        Args:
            name: Name of attribute to set.
            value: Value to assign.
        """
        object.__setattr__(self, name, value)

    def value_from_message(self, message):
        """Convert a message to a value instance.

        Used by deserializers to convert from underlying messages to
        value of expected user type.

        Args:
            message: A message instance of type self.message_type.

        Returns:
            Value of self.message_type.
        """
        return message

    def value_to_message(self, value):
        """Convert a value instance to a message.

        Used by serializers to convert Python user types to underlying
        messages for transmission.

        Args:
            value: A value of type self.type.

        Returns:
            An instance of type self.message_type.
        """
        return value

注意:GeneralField派生自其他ProtoRpc消息代码并覆盖Field set setattr 方法,以便允许普通(json可序列化)对象或要在ProtoRpc消息中使用的字典。您可能需要调整此方法以适合您的目的。

注意2:我不确定Cloud Endpoints会如何看待这一点,但它可能值得一试。