如何 return 动态 json 作为来自 google 云端点 python 的响应

how to return dynamic json as response from google cloud endpoint python

我想要以下 json 到 return 从 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.The 对象 'arts','science' 是动态的,可能存在也可能不存在。

我使用 ProtoRpc 消息(Cloud Endpoints 的基础)并将以下内容用于 return 一般 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 Message 代码并覆盖 Field 的 setsetattr 方法以允许正常的 (json-serialisable) 要在 ProtoRpc 消息中使用的对象或字典。您可能需要调整此方法以满足您的目的。

注意 2:我不确定 Cloud Endpoints 会如何,但值得一试。