有没有办法通过在python中的云端点api实现中将它作为请求/响应消息的一部分来返回数据存储区实体?
例如:
我将实体模型定义如下
class District(ndb.Model):
code = ndb.StringProperty(required=True)
现在我想在python中实现cloud api
@endpoints.method(request_message=DistrictMessage, response_message=DistrictMessage, name="DistrictApi.get_by_code")
def get_by_code(self, request):
#get code from District object in request message and
#try to get entity based on it from datastore
其中DistrictMessage定义为
class DistrictMessage(messages.Message):
district = messages.MessageField(District, 1, required=False)
上面不起作用,因为区域不是message.Message而是ndb.Model。我们可以在GAE Java中做类似的事情,但我无法找到它用于python。它甚至可能吗?或者我是否必须为每个实体定义一个Message类并执行/映射?
谢谢你, rizTaak
答案 0 :(得分:1)
没有办法直接这样做。您可以查看http://endpoints-proto-datastore.appspot.com/以获取可以使用模型而非消息的补充库。
如果你想自己做,你将不得不做这样的事情。
class DistrictMessage(messages.Message):
code = messages.StringField(1, required=True)
class SomeApiClass(): # incomplete class def for syntax highlighting
@endpoints.method(request_message=DistrictMessage, response_message=DistrictMessage, name="DistrictApi.get_by_code")
def get_by_code(self, request):
# get code from District object in request message and
# try to get entity based on it from datastore
district = District.query(District.code == request.code).get()
if district:
# copy District properties to DistrictMessage kwargs
# ndb.Model.to_dict() can be used here if you filter
# out properties that aren't used in the DistrictMessage
return DistrictMessage(code=district.code)
raise endpoints.NotFoundException()