如何在 Google Cloud Endpoints 中使用 Google Python 客户端?

How to use Google Python client in Google Cloud Endpoints?

我正在使用 Google 云端点制作 REST API。

我的 API 提供事件服务,例如 Google 日历事件。

但我的事件模型具有不同于 Google 日历的其他属性。

所以我想将其他属性存储到我的数据存储中。

其他人存储 Google 日历 API。

顺便说一下,我不知道如何使用 Google API Python 客户端进行 OAuth2 身份验证。

decorator = OAuth2Decorator(
    client_id='',
    client_secret='',
    scope='https://www.googleapis.com/auth/calendar')

service = build('calendar', 'v3')

@space_api.api_class(resource_name='events')
class EventsApi(remote.Service):

  @endpoints.method(EVENT_RESOURCE, EventMessage,
                    path='events', http_method='POST',
                    name='events.insert')
  @decorator.oauth_required
  def events_insert(self, request):
    event = service.events().insert(calendarId='primary', body=encode_message(request)).execute(http=decorator.http())
    return decode_message(EventMessage, event)

我使用 OAuth2Decorator 但 remote.Service class 没有重定向方法。

所以它会导致错误。

在 Google Cloud Endpoints 中使用 Google API Python 客户端应该怎么做。

请告诉我如何验证 OAuth2。

欢迎任何评论,例如文档 link。

要创建一个 API,其中 API 的方法需要通过文档 [1] 进行身份验证。你想创建一个需要身份验证的 API 使用文档 [2]。要在 Google API Python 客户端中使用 OAuth,请阅读文档 [3].

[1] https://cloud.google.com/appengine/docs/python/endpoints/getstarted/backend/auth

[2] https://cloud.google.com/appengine/docs/python/endpoints/auth

[3] https://cloud.google.com/appengine/docs/python/endpoints/access_from_python

您需要为服务器到服务器应用程序使用 OAuth 2.0。由于您在 App Engine 中使用 google 云端点,因此您可以使用 AppAssertionCredentials 对 Google 日历 API 进行授权 API 调用。下面是修改后的代码:

from oauth2client.appengine import AppAssertionCredentials

credentials = AppAssertionCredentials('https://www.googleapis.com/auth/calendar')
http_auth = credentials.authorize(Http())
calendar_service = build('calendar', 'v3', http=http_auth)

@space_api.api_class(resource_name='events')
class EventsApi(remote.Service):

  @endpoints.method(EVENT_RESOURCE, EventMessage,
                    path='events', http_method='POST',
                    name='events.insert')
  def events_insert(self, request):
    event = service.events().insert(calendarId='primary', body=encode_message(request)).execute(http_auth)
    return decode_message(EventMessage, event)

您可以在此处找到更多详细信息:

https://developers.google.com/api-client-library/python/auth/service-accounts#callinganapi