Using endpoints-proto-datastore, how do you pass attributes to a method that are not contained in the EndpointsModel

北城以北 提交于 2019-12-05 22:35:13

For just this use case, EndpointsAliasProperty was created. It acts much like @property does in Python in that you can specify a getter, setter and doc, but no deleter is specified in this context.

Since these properties will be sent over the wire and used with Google's API infrastructure, a type must be specified, so we can't just use @property. In addition, we need the typical property/field metadata such as repeated, required, etc.

Its use has been documented in one of the samples, but for your specific use case,

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)

Since no value for property_type was passed to EndpointsAliasProperty, the default of protorpc.messages.StringField is used. If instead you wanted an integer, you could've instead used:

@EndpointsAliasProperty(setter=attr2_set, property_type=messages.IntegerField)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!