1

我想让我的 GAE 后端 API 返回一个联系人列表以及每个联系人的相应电子邮件集合。我正在使用endpoints-proto-datastore并按照此问题中的指南实施此操作。

我的问题是,当contacts_list调用该方法时,我得到:

Encountered unexpected error from ProtoRPC method implementation: BadValueError (Expected Key, got [])

我猜这是因为 Contact.email_keys 可能是空的 ([]) 但不知道在哪里控制这种行为。

这是我的 API 实现的相关部分:

class Email(EndpointsModel):
    type = ndb.StringProperty(choices=('home', 'work', 'other'))
    email = ndb.StringProperty()
    #.... other properties

class Contact(EndpointsModel):
    first_name = ndb.StringProperty()
    last_name = ndb.StringProperty()
    email_keys = ndb.KeyProperty(kind=Email, repeated=True)
    #.... other properties

    @EndpointsAliasProperty(repeated=True, property_type=Email.ProtoModel())
    def emails(self):
        return ndb.get_multi(self.email_keys)

    _message_fields_schema = ('id', 'first_name', 'last_name')


@endpoints.api(name='cd', version='v1')
class MyApi(remote.Service):
    @Contact.query_method(query_fields=('limit', 'order', 'pageToken'),
                          collection_fields=('id', 'first_name', 'last_name', 'emails'),
                          path='contacts', name='contacts.list')
    def contacts_list(self, query):
        return query
4

1 回答 1

0

好吧,我自己找到了解决方案;这里是。

事实证明,当模型继承自EndpointsModel,具有属性repeated=True并且您创建端点原型数据存储query_method以检索模型列表时,堆栈中会调用库的模块 model.py 中的 _PopulateFilters 方法;这是相关的堆栈跟踪:

_PopulateFilters self._AddFilter(prop == current_value) 中的文件“lib/endpoints_proto_datastore/ndb/model.py”,第 229 行

model.py 中第 229 行的内容如下:

  # Only filter for non-null values
  if current_value is not None:
    self._AddFilter(prop == current_value)

如果有问题的模型属性有repeated=True,那么current_value将是[],这就是我的代码被破坏的地方。我将model.py中的相关部分更改如下,并解决了这个问题。

  # Only filter for non-null values...
  if current_value is not None:
      # ...and non empty arrays in case of properties with repeated=True 
      if current_value:
          self._AddFilter(prop == current_value)

将在 github 上创建评论,以查看是否包含在下一个版本中。

于 2014-01-09T00:47:13.767 回答