Google app engine 使用endpoints原型数据存储,如何将属性传递给EndpointsModel中不包含的方法
我正在尝试将属性传递到API调用中,而API调用中不包含这些属性。例如,假设我有以下模型:Google app engine 使用endpoints原型数据存储,如何将属性传递给EndpointsModel中不包含的方法,google-app-engine,google-cloud-endpoints,endpoints-proto-datastore,Google App Engine,Google Cloud Endpoints,Endpoints Proto Datastore,我正在尝试将属性传递到API调用中,而API调用中不包含这些属性。例如,假设我有以下模型: class MyModel(EndpointsModel): attr1 = ndb.StringProperty() 然后假设我想将attr2作为参数传入,但我不想将attr2用作过滤器,也不想将其存储在模型中。我只想传入一些字符串,在方法内部检索它,并使用它执行一些业务逻辑 文档描述了用于指定要传递到方法中的字段的query\u fields参数,但这些字段似乎与模型中包含的属性相耦合,因此不能
class MyModel(EndpointsModel):
attr1 = ndb.StringProperty()
然后假设我想将attr2
作为参数传入,但我不想将attr2
用作过滤器,也不想将其存储在模型中。我只想传入一些字符串,在方法内部检索它,并使用它执行一些业务逻辑
文档描述了用于指定要传递到方法中的字段的query\u fields
参数,但这些字段似乎与模型中包含的属性相耦合,因此不能传递模型中未指定的属性
同样,文档说明可以通过path变量传入属性:
@MyModel.method(request_fields=('id',),
path='mymodel/{id}', name='mymodel.get'
http_method='GET')
def MyModelGet(self, my_model):
# do something with id
但这需要您更改URL,而且它似乎具有与
query\u字段
(该属性必须存在于模型中)相同的约束。仅此用例中,EndpointSaliaProperty
是。它的作用与Python中的@property
非常相似,因为您可以指定getter、setter和doc,但在此上下文中没有指定deleter
由于这些属性将通过网络发送并与Google的API基础设施一起使用,因此必须指定一个类型,因此我们不能只使用@property
。此外,我们还需要典型的属性/字段元数据,如重复的
,必需的
,等等
它已经在其中一个示例中使用过,但是对于您的特定用例
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\u type
的值传递给endpointSaliaProperty
,因此使用了protorpc.messages.StringField
的默认值。如果您想要一个整数,您可以使用:
@EndpointsAliasProperty(setter=attr2_set, property_type=messages.IntegerField)
这是什么意思?也许你应该问一个新问题。如果我希望我的属性是只读的,我可以省略“setter”属性吗?是的。您还可以控制哪些方法与之交互,但setter实际上是用于从请求中获取值并将其从protorpc对象移动到ndb模型对象。