我是 GAE 和 Endpoints Proto Datastore 的新手。我一直在玩一个有照片的项目,每张照片都可以有很多评论。使用keys_with_ancestors作为指导,我已经实现了它,使得评论有一张照片作为父母,而照片有一个名为“comments”的别名属性,它执行祖先查询。这是我的代码:
评论:
class Comment(EndpointsModel):
_message_fields_schema = ('id', 'comment_text', 'owner', 'timestamp','parent')
_parent = None
comment_text = ndb.StringProperty(required=True)
owner = ndb.UserProperty(required=True)
timestamp = ndb.DateTimeProperty(auto_now_add=True)
parent_kind = ndb.StringProperty(required=True)
def SetKey(self):
if self._parent is not None and self.id is not None:
key = ndb.Key(self.parent_kind, self._parent, Comment, self.id)
self.UpdateFromKey(key)
def ParentSet(self, value):
self._parent = value
if ndb.Key(self.parent_kind, value).get() is None:
raise endpoints.NotFoundException('Parent %s does not exist.' % value)
if self.id is None:
self.key = ndb.Key(self.parent_kind, self._parent, Comment, None)
else:
self.SetKey()
self._endpoints_query_info.ancestor = ndb.Key(self.parent_kind, value)
@EndpointsAliasProperty(setter=ParentSet,required=True,property_type= messages.IntegerField)
def parent(self):
if self._parent is None and self.key is not None:
self._parent = self.key.parent().integer_id()
return self._parent
照片:
class Photo(EndpointsModel):
DEFAULT_ORDER = '-timestamp'
_message_fields_schema = ('id', 'photo_link', 'description', 'owner','timestamp','comments')
photo_link = ndb.StringProperty(required=True)
description = ndb.StringProperty(required=True)
owner = ndb.UserProperty(required=True)
timestamp = ndb.DateTimeProperty(auto_now_add=True)
@EndpointsAliasProperty(repeated=True, property_type=Comment.ProtoModel())
def comments(self):
return Comment.query(ancestor=self.key).order(-Comment.timestamp).fetch()
以及 API 获取请求:
@Photo.method(request_fields=('id',),
name='photo.get',
http_method='GET',
path='photo/{id}')
def get_photo(self,photo):
if not photo.from_datastore:
raise endpoints.NotFoundException('Photo not found.')
return photo
首先,这甚至是实现它的最佳方式吗?其次,我在评论处设置了一个断点,EndPointsAliasProperty
并注意到它在发出 apiGET
请求时被调用了 3 次。这种行为是正常的还是我做错了什么?如果一张照片有很多评论并且每个请求都被查询 3 次,这似乎是有问题的。