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

2024-05-24

我正在尝试将未包含在我的 API 调用中的属性传递给端点模型 https://code.google.com/p/endpoints-proto-datastore/source/browse/endpoints_proto_datastore/ndb/model.py?r=183ab0ff336857e081148ac2fdaa73543ca44452#593。例如,假设我有以下模型:

class MyModel(EndpointsModel):
  attr1 = ndb.StringProperty()

然后假设我想传入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

但这需要您更改 URL,而且这似乎具有与query_fields(该属性必须存在于模型中)。


对于这个用例,EndpointsAliasProperty was created https://code.google.com/p/endpoints-proto-datastore/source/browse/endpoints_proto_datastore/ndb/properties.py?r=183ab0ff336857e081148ac2fdaa73543ca44452#90。它的作用很像@propertyPython 中的做法是,您可以指定 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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐