【问题标题】:Google cloud endpoint RequestMessage with multiple fields resolution具有多字段解析的 Google 云端点 RequestMessage
【发布时间】:2013-03-20 17:04:51
【问题描述】:

云端点 ResponseMessage 对我来说似乎很简单。如果我有响应消息类

class FoodieResponseMessage(messages.Message):
  name = messages.StringField(1)
  fav_food = messages.StringField(2)
  city = messages.StringField(3)

调用它就像

一样简单
FoodieResponseMessage(name="A", fav_food="B", city="C")

但是有多个字段的RequestMessage 呢?我从服务端点方法得到的只是一个request 对象。我怎么知道哪个字段去了哪里?

class FoodieRequestMessage(messages.Message):
  name = messages.StringField(1)
  id = messages.StringField(2)
  sitting_table = messages.StringField(3)

 @endpoints.method(FoodieRequestMessage, FoodieResponseMessage)
 def process(self, request):
   name = request.name
   id = request.id
   table = request.sitting_table

请求如何匹配该字段,以便我在执行request.name 时不会得到用户的sitting_table

【问题讨论】:

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


    【解决方案1】:

    您的方法必须是 API 类的成员:

    from protorpc import remote
    
    class FoodieAPI(remote.Service):
    
      @endpoints.method(FoodieRequestMessage, FoodieResponseMessage)
      def process(self, request):
        # Handle request
    

    由于processremote.Service 子类的成员,因此由

    创建的实际处理程序
    application = endpoints.api_server([FoodieApi])
    

    知道如何将 JSON 转换为您指定的本机消息请求类 (FoodieRequestMessage),并且还希望您返回您指定的响应类的实例 (FoodieResponseMessage),因为它可以将其转换回 JSON也是。

    例如:

    >>> import json
    >>> from protorpc import protojson
    >>>
    >>> payload = json.dumps({
    >>>     'name': 'Dan', 
    >>>     'fav_food': 'Mac and Cheese', 
    >>>     'city': 'San Francisco'
    >>> })
    >>> message = protojson.decode_message(FoodieResponseMessage, payload)
    >>> message
    <FoodieResponseMessage
     name: u'Dan'
     fav_food: u'Mac and Cheese'
     city: u'San Francisco'>
    

    所以当你的请求负载是

    {"city": "San Francisco", "fav_food": "Mac and Cheese", "name": "Dan"}
    

    您方法中的request 对象将具有

    >>> message.name
    u'Dan'
    >>> message.fav_food
    u'Mac and Cheese'
    >>> message.city
    u'San Francisco'
    

    【讨论】:

    • 那么我的FoodieRequestMessage 课程好吗?我见过人们使用各种东西,例如messages.EnumField。我认为以某种方式告诉endpoints api 设置哪个查询参数/路径参数是必要的,比如sitting_table 到。
    • 它本来就很好。如果您使用枚举,则可以使用EnumField,但这不会改变字段的解析方式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-15
    相关资源
    最近更新 更多