使用endpoints-proto-datastore,如何将属性传递给EndpointsModel中未包含的方法

use*_*693 3 google-app-engine google-cloud-endpoints endpoints-proto-datastore

我试图将属性传递给我的EndpointsModel中未包含的API调用.例如,假设我有以下型号:

class MyModel(EndpointsModel):
  attr1 = ndb.StringProperty()
Run Code Online (Sandbox Code Playgroud)

然后假设我想attr2作为参数传入,但我不想attr2用作过滤器,也不希望它存储在模型中.我只是想传入一些字符串,在方法内部检索它并使用它来执行一些业务逻辑.

该文档描述了query_fields用于指定要传递给方法的字段的参数,但这些参数似乎与模型中包含的属性相关联,因此您无法传递模型中未指定的属性.

同样,文档声明您可以通过路径变量传递属性:

@MyModel.method(request_fields=('id',),
                path='mymodel/{id}', name='mymodel.get'
                http_method='GET')
def MyModelGet(self, my_model):
  # do something with id
Run Code Online (Sandbox Code Playgroud)

但这需要您更改URL,此外它似乎具有与query_fields(该属性必须存在于模型中)相同的约束.

bos*_*ter 9

对于刚刚这个用例,EndpointsAliasProperty创建.它的行为与@propertyPython中的行为非常类似,您可以指定getter,setter和doc,但在此上下文中未指定删除器.

由于这些属性将通过网络发送并与Google的API基础结构一起使用,因此必须指定类型,因此我们不能仅使用@property.此外,我们需要的典型属性/字段元数据,例如repeated,required等等.

它的使用已记录在其中一个样本中,但针对您的具体用例,

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)
Run Code Online (Sandbox Code Playgroud)

由于没有property_type传递EndpointsAliasProperty值,protorpc.messages.StringField因此使用默认值.如果你想要一个整数,你可以改为使用:

@EndpointsAliasProperty(setter=attr2_set, property_type=messages.IntegerField)
Run Code Online (Sandbox Code Playgroud)