LoginSignup
2
2

More than 5 years have passed since last update.

endpoints-proto-datastore

Last updated at Posted at 2015-02-22

endpoints-proto-datastoreは、Google Cloud Endpointsの定義を省略できる、便利なモジュールです。

ancestorの指定方法

ドキュメントには、リクエストのPATHからancestorを指定するサンプルコードが紹介されています。

  @MyModel.query_method(query_fields=('parent',),
                        path='mymodels/{parent}', name='mymodel.list')
  def MyModelList(self, query):
    return query

しかしこのコードは、そもそもリクエストを送信するクライアントがancestorとして有効な値を知り得ないケースでは、利用できません。

また、ancestorQueryオブジェクトのコンストラクタで指定しなければならず、Queryオブジェクトのfilterメソッドでは指定できません。
よって、EndpointsModel.query_methodが返すqueryインスタンスを操作しても、ancestorを指定する処理はできません。

例えば、リクエストのGoogle OAuth2.0認証に基いてancestor値が決定する場合、つぎのようにModelのコンストラクタで_EndpointsQueryInfoインスタンスの_GetAncestorメソッドを書き換えると、うまく動きます。

def get_ancestor_key_by_oauth(_self=None):
  user = endpoints.get_current_user()
  if user is None:
    raise endpoints.UnauthorizedException('Unauthorized')
  ancestor_key = get_ancestor_key(user.id())
  if ancestor_key is None:
    raise endpoints.UnauthorizedException('Unauthorized')
  return ancestor_key


class MyModel(EndpointsModel):

  @classmethod
  def new(cls):
    ancestor_key = get_ancestor_key_by_oauth()
    return cls(parent=ancestor_key)

  def __init__(self, *args, **kwargs):
    super(self.__class__, self).__init__(*args, **kwargs)
    self._endpoints_query_info._GetAncestor = get_ancestor_key_by_oauth
  @MyModel.query_method(
    query_fields=('limit', 'pageToken'),
    user_required=True,
    auth_level=endpoints.AUTH_LEVEL.REQUIRED,
  )
  def MyModelList(self, query):
    return query
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2