Google Sites API + OAuth2(在Appengine上)
我一直在尝试使用Python库来访问Google Sites的API。
第一步是需要用户授权我们的应用程序,他们推荐使用OAuth2,并提供了一个可以在这里找到的库。
在授权过程结束时,你会得到一个OAuth2Credentials对象。
问题是,当我尝试向Google Sites API发送请求时,比如我这样做:
import gdata.sites.client
client = gdata.sites.client.SitesClient(site=None, domain='mydomain.com')
我不知道怎么使用这个OAuth2Credentials对象。
2 个回答
2
我的应用程序使用的是.p12密钥,而不是流式处理。经过一些调整,我让它成功运行了,下面是我做的步骤:
from oauth2client.client import SignedJwtAssertionCredentials
import gdata.sites.client
import gdata.sites.data
scope = 'https://sites.google.com/feeds/'
key_file = 'xxxxxxxxxxxxxxxxxxx.p12'
with open(key_file) as f:
key = f.read()
credentials = SignedJwtAssertionCredentials(
'xxxxxxxxxxxxxxxxxxx@developer.gserviceaccount.com',
key,
sub='aleh@vaolix.com',
scope=[scope])
auth2token = gdata.gauth.OAuth2TokenFromCredentials(credentials)
client = gdata.sites.client.SitesClient(source='sites-test',
domain='mydomain.com')
auth2token.authorize(client)
feed = client.GetSiteFeed()
for entry in feed.entry:
print entry.title.text
10
我花了不少时间才找到这个问题的答案,最后在一个博客帖子里找到了:
https://groups.google.com/forum/m/#!msg/google-apps-developer-blog/1pGRCivuSUI/3EAIioKp0-wJ
这里有一个完整的例子,展示了如何使用oauth2client和gdata API来访问Google Sites,包括“猴子补丁”的部分:
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import run
import gdata.sites.client
import gdata.sites.data
SCOPE = 'https://sites.google.com/feeds/'
# client_secrets.json is downloaded from the API console:
# https://code.google.com/apis/console/#project:<PROJECT_ID>:access
# where <PROJECT_ID> is the ID of your project
flow = flow_from_clientsecrets('client_secrets.json',
scope=SCOPE,
redirect_uri='http://localhost')
storage = Storage('plus.dat')
credentials = storage.get()
if credentials is None or credentials.invalid:
credentials = run(flow, storage)
# 'Monkey Patch' the data in the credentials into a gdata OAuth2Token
# This is based on information in this blog post:
# https://groups.google.com/forum/m/#!msg/google-apps-developer-blog/1pGRCivuSUI/3EAIioKp0-wJ
auth2token = gdata.gauth.OAuth2Token(client_id=credentials.client_id,
client_secret=credentials.client_secret,
scope=SCOPE,
access_token=credentials.access_token,
refresh_token=credentials.refresh_token,
user_agent='sites-test/1.0')
# Create a gdata client
client = gdata.sites.client.SitesClient(source='sites-test',
site='YOUR.SITE',
domain='YOUR.DOMAIN',
auth_token=auth2token)
# Authorize it
auth2token.authorize(client)
# Call an API e.g. to get the site content feed
feed = client.GetContentFeed()
for entry in feed.entry:
print '%s [%s]' % (entry.title.text, entry.Kind())