这是一个使用gdata库在Google App Engine中如何在Python中进行域范围委派的示例:
创建一个项目(https://cloud.google.com/console#/project)。
在“ API和验证”下,启用您需要使用的API(某些gdata API不会出现在此处,如果是,请跳过此步骤)。
在“ API和身份验证”->“凭据”下,创建一个新的OAuth2客户ID类型的服务帐户。记下电子邮件地址和客户端ID,然后将下载的私钥保存到安全位置。
作为域管理员,请转到管理控制台(https://admin.google.com/AdminHome),导航至“安全”->“高级设置”->“托管的第三方OAuth客户端访问权限”。
将先前的完整客户端ID粘贴到“客户端名称”字段中,并将API访问所需的范围粘贴到范围字段中。
由于我们在Google App Engine上运行,因此我们需要将PKCS12格式的私钥转换为PEM格式(因为当前在Google App Engine上部署的PyCrypto库不支持PCKS12):
cat secret-privatekey.p12 | openssl pkcs12 -nodes -nocerts -passin pass:notasecret | openssl rsa > secret-privatekey.pem
将此文件放在您的应用目录中。
从@L_404_4@https://code.google.com/p/google-api-python-client/downloads/list下载Google Api Python客户端,然后选择google-api-python-client-gae-1.2.zip
。
将其解压缩到您的应用目录中:
unzip ~/Downloads/google-api-python-client-gae-1.2.zip
从https://code.google.com/p/gdata-python-client/downloads/list下载gdata python客户端,选择gdata-2.0.18.zip
。
将其安装在您的应用目录中:
unzip ~/Downloads/gdata-2.0.18.zip
mv gdata-2.0.18/src/* . rm -rf gdata-2.0.18/
确保PyCrypto安装在本地(但不在您的应用程序目录中):
sudo easy_install pycrypto
libraries:
声明以下帮助程序类:
import httplib2
class TokenFromOAuth2Creds: def (self, creds): self.creds = creds def modify_request(self, req): if self.creds.access_token_expired or not self.creds.access_token: self.creds.refresh(httplib2.Http()) self.creds.apply(req.headers)
使用私钥创建一个SignedJwtAssertionCredentials
对象:
from oauth2client.client import SignedJwtAssertionCredentials
credentials = SignedJwtAssertionCredentials( “<service account email>@developer.gserviceaccount.com”, file(“secret-privatekey.pem”, “rb”).read(),scope=["http://www.google.com/m8/Feeds/”], prn=”<user to impersonate>@your-domain.com“ )
创建一个gdata客户端并使用它:
gd_client = gdata.contacts.client.ContactsClient('your-domain.com')
gd_client.auth_token = TokenFromOAuth2Creds(credentials) xxx = gd_client.get_contacts()