本文介绍了Google App Engine和群组配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正在尝试使用Google的Provisioning API GAE(Google App Engine)使用oAuth2。我知道有一些使用oAuth1来实现这个功能的例子。但我的理解是,oAuth1现在已被弃用,我们必须使用oAuth2,如果我错了,请纠正我。



我已经搜索了互联网,并且我唯一能够找到工作是这样的:





我找到的其他示例使用oAuth 1,或者它们不是用于App Engine的。



我从上面的示例中获取了代码,并尝试修改它以使用组配置API,这里是我的代码:

  import os 

from gdata.alt import appengine $ b $ from gdata.service import RequestError $ b $ from google.appengine.api import users
from google.appengine.ext从google.appengine.ext.webapp导入模板导入webapp

from google.appengine.ext.webapp从oauth2client.appengine导入util
导入OAuth2Decorator
导入gdata.auth
导入gdata.apps.groups.client
导入gdata .client
import httplib2

$ b API_VERSION ='2.0'
BASE_URL ='/ a / feeds / group /%s'API_VERSION
#HACK将Python GData客户端库与OAuth 2令牌一起使用。
#我们使用处理AuthSub令牌的方法。
gdata.auth.AUTHSUB_AUTH_LABEL =OAuth
$ b $ class MainHandler(webapp.RequestHandler):
#client_id和client_secret从
上的API Access选项卡复制而来#Google API控制台< http://code.google.com/apis/console>
oauth2_decorator = OAuth2Decorator(
client_id =myClientID.apps.googleusercontent.com,
client_secret =myClientSecret,$ b $ scope =https://apps-apis.google .com / a / feeds / groups /)

#这个装饰器确保每当提供这个页面时,我们都有一个有效的
#OAuth 2令牌给用户。
@ oauth2_decorator.oauth_required $ b $ def handle_exception(self,exception,debug_mode):
通过强制刷新来处理OAuth 2令牌过期

对于较新的Google API,刷新由客户端
库自动处理,但对于GData API,我们需要明确强制这种行为。

if(isinstance(exception,RequestError)and
exception.args [0] [status] == 401):
body = exception.args [0] [body]
如果令牌无效 - AuthSub令牌无效。在body中:
self.oauth2_decorator.credentials._refresh(httplib2.Http()。request)
self.redirect(self.request.url)
return

webapp.RequestHandler.handle_exception(self,exception,debug_mode)

#这个装饰器确保每当提供这个页面时,我们都有一个有效的
#OAuth 2令牌给用户。
@ oauth2_decorator.oauth_required
def get(self):
self.domain ='testdomain123456.mygbiz.com'
self.baseuri ='%s /%s'%( BASE_URL,'testdomain123456.mygbiz.com')
self.token = self.oauth2_decorator.credentials.access_token
self.client = gdata.apps.groups.client.GroupsProvisioningClient(
domain = self .domain,auth_token = self.token)

self.client.SetAuthSubToken(self.token)

params = dict(
logout_url = users.create_logout_url(self .request.uri),
memberFeed = self.client.RetrieveAllMembers('test')

path = os.path.join(os.path.dirname(__ file__),'templates ','index.html')
self.response.out.write(template.render(path,params))


def main():
application = webapp.WSGIApplication([('/',MainHandler)],debug = True)
util.run_wsgi_app(应用程序)

$ b $如果__name__ =='__main__':
main()

我将它部署到,正如你可以看到它返回一个500服务器错误。我在与 app.yaml 相同的目录中拥有所有必需的库,并且我为该域设置了我的google api。



屏幕截图:



我一直在尽我所能从GAE中配置组,但没有成功。请帮助,如果可以的话,任何的输入量是赞赏。

解决方案

应用程序引擎,但它是一个命令行示例,使用带有oauth 2的gdata客户端:

  import sys 
import os
导入webbrowser
导入gdata.gauth
导入oauth2client.client
导入oauth2client.file
导入oauth2client.tools
导入gdata.gauth
导入gdata.client
导入gdata.apps.groups.client

APICONSOLE ='https://code.google.com/apis/console'
SCOPES ='https:/ /apps-apis.google.com/a/feeds/groups/'
OAUTH2FILENAME ='credentials.oauth2'
OAUTH2JSONFILE ='client_secrets.json'
OAUTH2USERAGENT ='GROUPS'
MISSING_OAUTHJSONFILE_MESSAGE =
您必须从Google API控制台< https://code.google.com/apis/console>创建或下载客户机密json文件(%s)

试图用浏览器打开页面...
%os.path.join(os.path.dirname(__ file__),OAUTH2JSONFILE)

#以适当的值填充
DOMAIN ='your-domain'
GROUP_ID ='[email protected]'

如果不是os.path.isfile(OAUTH2JSONFILE):
message = MISSING_OAUTHJSONFILE_MESSAGE
打印消息
尝试:
webbrowser.open(str(APICONSOLE))
除了例外,e:
print打开网页时出错
sys.exit(1)
message ='当%s被创建/下载时,按Enter继续...'%(OAUTH2JSONFILE)
raw_input(message)
oauth2_flow = oauth2client.client.flow_from_clientsecrets(OAUTH2JSONFILE,$ b $ scope = SCOPES,message = MISSING_OAUTHJSONFILE_MESSAGE)
storage = oauth2client.file.Storage(OAUTH2FILENAME)
oauth2_credentials = storage.get()
如果oauth2_credentials为None或oauth2_credentials.invalid:
oauth2_credentials = oauth2client.tools .run(oauth2_flow,存储)
oauth2_token = gdata.gauth.OAuth2Token(
c lient_id = oauth2_credentials.client_id,
client_secret = oauth2_credentials.client_secret,$ b $ scope = SCOPES,
user_agent = OAUTH2USERAGENT,
access_token = oauth2_credentials.access_token,
refresh_token = oauth2_credentials。 refresh_token)
#授权客户端
groups_client = oauth2_token.authorize(
gdata.apps.groups.client.GroupsProvisioningClient(domain = DOMAIN))
print'授权域%s。 。 .\\\
'%(DOMAIN)
group_entry = groups_client.RetrieveGroup(group_id = GROUP_ID)
print group_entry.group_id
print group_entry.group_name
print group_entry.description
print group_entry.email_permission

sys.exit(0)


I really need some help here, I've been at this for almost 2 weeks.

What I'm trying to do is use Google's provisioning API inside of GAE (Google App Engine) using oAuth2. I know there are a few of examples using oAuth1 to accomplish this. My understanding though is that oAuth1 is now deprecated and we must used oAuth2, please correct me if I am wrong.

I've scoured the internet and the only example I could find to work from is this:

http://gdata-samples.googlecode.com/svn-history/r232/trunk/gdata/youtube-oauth2-app-engine/main.py

Other examples I've found use oAuth 1, or they are not designed to be used with App Engine.

I've taken the code from the example above and attempted to modify it to work with the groups provisioning API, here is my code:

import os

from gdata.alt import appengine
from gdata.service import RequestError
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp import util
from oauth2client.appengine import OAuth2Decorator
import gdata.auth
import gdata.apps.groups.client
import gdata.client
import httplib2


API_VERSION = '2.0'
BASE_URL = '/a/feeds/group/%s' % API_VERSION
# HACK to use the Python GData client library with OAuth 2 tokens.
# We use the methods that deal with AuthSub tokens.
gdata.auth.AUTHSUB_AUTH_LABEL = "OAuth "

class MainHandler(webapp.RequestHandler):
  # The client_id and client_secret are copied from the API Access tab on
  # the Google APIs Console <http://code.google.com/apis/console>
  oauth2_decorator = OAuth2Decorator(
    client_id="myClientID.apps.googleusercontent.com",
    client_secret="myClientSecret",
    scope="https://apps-apis.google.com/a/feeds/groups/")

  # This decorator ensures that whenever this page is served, we have a valid
  # OAuth 2 token for the user.
  @oauth2_decorator.oauth_required
  def handle_exception(self, exception, debug_mode):
    """Handle OAuth 2 token expirations by forcing a refresh.

    For newer Google APIs, refreshes are handled automatically by the client
        library, but for GData APIs, we need to explicitly force this behavior.
    """
    if (isinstance(exception, RequestError) and
        exception.args[0]["status"] == 401):
      body = exception.args[0]["body"]
      if "Token invalid - Invalid AuthSub token." in body:
        self.oauth2_decorator.credentials._refresh(httplib2.Http().request)
        self.redirect(self.request.url)
        return

    webapp.RequestHandler.handle_exception(self, exception, debug_mode)

  # This decorator ensures that whenever this page is served, we have a valid
  # OAuth 2 token for the user.
  @oauth2_decorator.oauth_required
  def get(self):
      self.domain='testdomain123456.mygbiz.com'
      self.baseuri = '%s/%s' % (BASE_URL, 'testdomain123456.mygbiz.com')
      self.token = self.oauth2_decorator.credentials.access_token
      self.client = gdata.apps.groups.client.GroupsProvisioningClient(
        domain=self.domain, auth_token=self.token)

      self.client.SetAuthSubToken(self.token)

      params = dict(
      logout_url=users.create_logout_url(self.request.uri),
      memberFeed = self.client.RetrieveAllMembers('test')
    )
      path = os.path.join(os.path.dirname(__file__), 'templates', 'index.html')
      self.response.out.write(template.render(path, params))


def main():
  application = webapp.WSGIApplication([('/', MainHandler)], debug=True)
  util.run_wsgi_app(application)


if __name__ == '__main__':
  main()

I deployed this to http://appplat4.appspot.com, and as you can see it returns a 500 server error. I have all of the necessary libraries in the same directory as app.yaml and I have my google api set up for the domain.

Screenshot:

I've been trying everything I can to provision groups from within GAE with no success. Please help if you can, any amount of input is appreciated.

解决方案

This doesn't address app engine but it is a command line example using a gdata client with oauth 2:

import sys
import os
import webbrowser
import gdata.gauth
import oauth2client.client
import oauth2client.file
import oauth2client.tools
import gdata.gauth
import gdata.client
import gdata.apps.groups.client

APICONSOLE = 'https://code.google.com/apis/console'
SCOPES = 'https://apps-apis.google.com/a/feeds/groups/'
OAUTH2FILENAME = 'credentials.oauth2'
OAUTH2JSONFILE = 'client_secrets.json'
OAUTH2USERAGENT = 'GROUPS'
MISSING_OAUTHJSONFILE_MESSAGE = """
You must create or download a client secrets json file (%s)
from the Google APIs console <https://code.google.com/apis/console>.
Attemping to open page with your browser ...
""" % os.path.join(os.path.dirname(__file__), OAUTH2JSONFILE)

# populate with approprate values
DOMAIN = 'your-domain'
GROUP_ID = '[email protected]'

if not os.path.isfile(OAUTH2JSONFILE):
  message = MISSING_OAUTHJSONFILE_MESSAGE
  print message
  try:
    webbrowser.open(str(APICONSOLE))
  except Exception, e:
    print "Error opening web page"
    sys.exit(1)
  message = 'When %s is created/downloaded press Enter to continue ... ' %(OAUTH2JSONFILE)
  raw_input(message)
oauth2_flow = oauth2client.client.flow_from_clientsecrets(OAUTH2JSONFILE,
  scope=SCOPES,message=MISSING_OAUTHJSONFILE_MESSAGE)
storage = oauth2client.file.Storage(OAUTH2FILENAME)
oauth2_credentials = storage.get()
if oauth2_credentials is None or oauth2_credentials.invalid:
  oauth2_credentials = oauth2client.tools.run(oauth2_flow, storage)
oauth2_token = gdata.gauth.OAuth2Token(
  client_id=oauth2_credentials.client_id,
  client_secret=oauth2_credentials.client_secret,
  scope=SCOPES,
  user_agent=OAUTH2USERAGENT,
  access_token=oauth2_credentials.access_token,
  refresh_token=oauth2_credentials.refresh_token)
# authorize client
groups_client = oauth2_token.authorize(
  gdata.apps.groups.client.GroupsProvisioningClient(domain=DOMAIN))
print 'Authorized domain %s . . .\n' %(DOMAIN)
group_entry = groups_client.RetrieveGroup(group_id=GROUP_ID)
print group_entry.group_id
print group_entry.group_name
print group_entry.description
print group_entry.email_permission

sys.exit(0)

这篇关于Google App Engine和群组配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 16:31