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
として有効な値を知り得ないケースでは、利用できません。
また、ancestor
はQuery
オブジェクトのコンストラクタで指定しなければならず、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