端点Proto数据存储 - 祖先查询别名属性

时间:2014-02-26 23:10:14

标签: google-app-engine endpoints-proto-datastore

我是GAE和Endpoints Proto Datastore的新手。我一直在玩一个有照片的项目,每张照片都有很多评论。使用keys_with_ancestors作为指南,我已经实现了它,使得评论将照片作为父级,而照片具有名为“评论”的别名属性,该属性执行祖先查询。这是我的代码:

注释:

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处设置了一个断点,并注意到在发出api GET请求时它被调用了3次。这种行为是正常的还是我做错了什么?如果照片有很多评论,并且每次请求都会被查询3次,这似乎有问题。

0 个答案:

没有答案