2

云端点 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

请求如何匹配该字段,以便我最终不会得到用户sitting_tablerequest.name

4

1 回答 1

2

您的方法需要是 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'
于 2013-03-21T17:40:52.247 回答