对于这个用例,EndpointsAliasProperty
was created https://code.google.com/p/endpoints-proto-datastore/source/browse/endpoints_proto_datastore/ndb/properties.py?r=183ab0ff336857e081148ac2fdaa73543ca44452#90。它的作用很像@property
Python 中的做法是,您可以指定 getter、setter 和 doc,但在此上下文中未指定删除器。
由于这些属性将通过网络发送并与 Google 的 API 基础设施一起使用,因此必须指定类型,因此我们不能只使用@property
。此外,我们还需要典型的属性/字段元数据,例如repeated
, required
, etc.
它的用途已有记录的 http://endpoints-proto-datastore.appspot.com/examples/custom_alias_properties.html在其中一个示例中,但对于您的特定用例,
from google.appengine.ext import ndb
from endpoints_proto_datastore.ndb import EndpointsAliasProperty
from endpoints_proto_datastore.ndb import EndpointsModel
class MyModel(EndpointsModel):
attr1 = ndb.StringProperty()
def attr2_set(self, value):
# Do some checks on the value, potentially raise
# endpoints.BadRequestException if not a string
self._attr2 = value
@EndpointsAliasProperty(setter=attr2_set)
def attr2(self):
# Use getattr in case the value was never set
return getattr(self, '_attr2', None)
由于没有价值property_type
被传递给EndpointsAliasProperty
,默认为protorpc.messages.StringField
用来。如果您想要一个整数,您可以使用:
@EndpointsAliasProperty(setter=attr2_set, property_type=messages.IntegerField)