python - 使用 Python 在 Google App Engine 中提供 Google 配置 API 和 oAuth2

标签 python google-app-engine oauth google-api google-provisioning-api

好吧,我想做的是使用 Google 的配置 API 在后台将成员添加到 Google 群组,因为他们在 Google 类(class)构建器(由 Google 应用引擎提供支持)中注册/注册。

我尝试的第一个方法是使用此处显示的 clientLogin 方法:https://developers.google.com/google-apps/provisioning/#adding_a_member_to_a_group

groupClient = gdata.apps.groups.client.GroupsProvisioningClient(domain=domain)
groupClient.ClientLogin(email=email, password=password, source='apps')
groupClient.AddMemberToGroup(group_id, member_id)

尽管这在 App Engine 之外有效,但在实现后我遇到了一些错误并被告知 (http://stackoverflow.com/questions/13867535/python-import-gdata-google-apps-engine-course-builder )在 App Engine 中使用它是一个坏主意,因为它已被弃用。

我现在尝试使用此处找到的 python 配置 oAuth 示例 (https://developers.google.com/google-apps/help/libraries-samples#provisioningv2) 来完成此任务

来源如下:

"""Sample for the Provisioning API and the Email Settings API with OAuth 2.0."""

__author__ = 'Shraddha Gupta <shraddhag@google.com>'

from optparse import OptionParser
import gdata.apps
import gdata.apps.emailsettings.client
import gdata.apps.groups.client
import gdata.client
import gdata.gauth
import httplib


API_VERSION = '2.0'
BASE_URL = '/a/feeds/group/%s' % API_VERSION
SCOPE = ('https://apps-apis.google.com/a/feeds/groups/')
HOST = 'apps-apis.google.com'


class OAuth2ClientSample(object):
"""OAuth2ClientSample object demos the use of OAuth2Token for retrieving
Members of a Group and updating Email Settings for them."""

def __init__(self, domain, client_id, client_secret):
"""
Args:
  domain: string Domain name (e.g. domain.com)
  client_id: string Client_id of domain admin account.
  client_secret: string Client_secret of domain admin account.
"""
try:
  self.token = gdata.gauth.OAuth2Token(client_id=client_id,
                                       client_secret=client_secret,
                                       scope=SCOPE,
                                       user_agent='oauth2-provisioningv2')
  self.uri = self.token.generate_authorize_url()
  #print 'Please visit this URL to authorize the application:'
  #print self.uri
  # Get the verification code from the standard input.
  #code = raw_input('What is the verification code? ').strip()
  conn = httplib.HTTPConnection(self.uri)
  conn.request("GET")
  r1 = conn.getresponse()
  print r1.read()
  self.token.get_access_token(code)
  except gdata.gauth.OAuth2AccessTokenError, e:
  print 'Invalid Access token, Check your credentials %s' % e
  exit(0)
  self.domain = domain
  self.baseuri = '%s/%s' % (BASE_URL, domain)
  self.client = gdata.apps.groups.client.GroupsProvisioningClient(
    domain=self.domain, auth_token=self.token)
# Authorize the client. 
# This will add the Authorization header to all future requests.
self.token.authorize(self.client)
self.email_client = gdata.apps.emailsettings.client.EmailSettingsClient(
    domain=self.domain, auth_token=self.token)
self.token.authorize(self.email_client)

def create_filter(self, feed):
"""Creates a mail filter that marks as read all messages not containing
Domain name as one of their words for each member of the group.

Args:
  feed: GroupMemberFeed members whose emailsettings need to updated
"""
for entry in feed.entry:
  user_name, domain = entry.member_id.split('@', 1)
  if entry.member_type == 'User' and domain == self.domain:
    print 'creating filter for %s' % entry.member_id
    self.email_client.CreateFilter(user_name,
                                   does_not_have_the_word=self.domain,
                                   mark_as_read=True)
  elif entry.member_type == 'User':
    print 'User belongs to other Domain %s' %entry.member_id
  else:
    print 'Member is a group %s' %entry.member_id

def run(self, group):
feed = self.client.RetrieveAllMembers(group)
self.create_filter(feed)


def main():

  sample = OAuth2ClientSample('mydomain.mygbiz.com',
  'mydomain', 'My client secret')
  sample.run('test')


if __name__ == '__main__':
  main()

我意识到这只是列出我的组的成员,但现在我只是想通过身份验证阶段。

我具体提到的代码是:

  #print 'Please visit this URL to authorize the application:'
  #print self.uri
  # Get the verification code from the standard input.
  #code = raw_input('What is the verification code? ').strip()
  conn = httplib.HTTPConnection(self.uri)
  conn.request("GET")
  r1 = conn.getresponse()
  print r1.read()
  self.token.get_access_token(code)

我注释掉了原始代码,该代码采用 token 的原始输入。这需要在后台无缝运行,因此我需要它自动检索 token 。我已启动 httplib,但它返回了 URL 错误。

我有几个问题。

首先,这是我需要做的最简单的方法吗,这似乎有点矫枉过正。 clientLogin 更加优雅和简单。

第二,如果我必须这样做,那么一旦获得验证 URL,我该如何检索 token ?我使用 httplib 吗?

认真考虑在 Python 中模拟浏览器......为什么这个过程如此复杂?

我们非常感谢您提供的任何帮助。

编辑:我只是想指出,首先执行所有这些操作的原因是为了开发 MOOC类(class) build 者可能拥有数万到数十万的成员(member)。讨论平台将是Google群组,但我们不能向公众开放,但我们也无法手动批准每个成员。

最佳答案

您可以继续使用 ClientLogin,弃用过程很慢 (https://developers.google.com/accounts/terms)。 我的应用程序使用 Oauth 2,但不使用应用程序引擎。您可以从项目的 API 控制台页面 (https://code.google.com/apis/console) 下载 client_secrets.json 文件,并从该文件中检索 secret 等。 例如:

import oauth2client.client
import oauth2client.file
import oauth2client.tools
...
oauth2_flow = oauth2client.client.flow_from_clientsecrets('client_secrets.json',
  scope='list of scopes',message='Missing client_secrets.json file message')
storage = oauth2client.file.Storage('creedentials.ouath2')
oauth2_credentials = storage.get()
if oauth2_credentials is None or oauth2_credentials.invalid:
  oauth2_credentials = oauth2client.tools.run(oauth2_flow, storage)
...

关于python - 使用 Python 在 Google App Engine 中提供 Google 配置 API 和 oAuth2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13870185/

相关文章:

python - 是否可以更改(更新)已保存在 .npy 文件中的 numpy 数组的条目?如何?

java - 将数据输入 Google Cloud Datastore

facebook - Oauth——Facebook/Twitter/Foursquare

python - 你如何在 Django 中使用 rauth?

python - 如何加速 PyMC 马尔可夫模型?

当我们运行许多任务时,python 多处理池不起作用

python - Keras 中的全局权重衰减

python - App Engine 中的列表属性字段是如何排序的?

java - 如何访问输出阶段的 Mapper/Reducer 计数器?

security - 通过 ssl 完成 OAuth 请求时是否需要验证随机数?