![](/img/trans.png)
[英]Use oauth2 service account to authenticate to Google API in python
[英]How to authenticate with Google Email Settings API using service account oauth2 Python client?
我正在使用Python 2.6和Google API的客戶端庫,我嘗試使用它來獲取對電子郵件設置的身份驗證訪問權限:
f = file(SERVICE_ACCOUNT_PKCS12_FILE_PATH, 'rb')
key = f.read()
f.close()
credentials = client.SignedJwtAssertionCredentials(SERVICE_ACCOUNT_EMAIL, key, scope='https://apps-apis.google.com/a/feeds/emailsettings/2.0/', sub=user_email)
http = httplib2.Http()
http = credentials.authorize(http)
return discovery.build('email-settings', 'v2', http=http)
當我執行此代碼時,我得到了以下錯誤:UnknownApiNameOrVersion:name:email-settings version:v2
電子郵件設置V2的api名稱和版本是什么? 是否可以將其與服務帳戶一起使用? 問候
我找到了使用服務帳戶oauth2獲取電子郵件設置的解決方案:以下是一個示例:
SERVICE_ACCOUNT_EMAIL = ''
SERVICE_ACCOUNT_PKCS12_FILE_PATH = ''
EMAIL_SETTING_URI = "https://apps-apis.google.com/a/feeds/emailsettings/2.0/%s/%s/%s"
def fctEmailSettings():
user_email = "user@mail.com"
f = file(SERVICE_ACCOUNT_PKCS12_FILE_PATH, 'rb')
key = f.read()
f.close()
credentials = client.SignedJwtAssertionCredentials(SERVICE_ACCOUNT_EMAIL, key, scope='https://apps-apis.google.com/a/feeds/emailsettings/2.0/', sub=user_email)
auth2token = OAuth2TokenFromCredentials(credentials)
ESclient = EmailSettingsClient(domain='doamin.com')
auth2token.authorize(ESclient)
username = 'username'
setting='forwarding'
uri = ESclient.MakeEmailSettingsUri(username, setting)
entry = ESclient.get_entry(uri = uri, desired_class = GS.gdata.apps.emailsettings.data.EmailSettingsEntry)
似乎使用Discovery API無法使用emailsettings API。 API Discovery服務返回API的詳細信息 - 可用的方法等。
請參閱PHP客戶端API上引發的以下問題
https://github.com/google/google-api-php-client/issues/246
我不清楚為什么通過發現API無法提供電子郵件設置,或者是否有計划這樣做。 真的感覺很多這些系統和庫都沒有維護。
不推薦使用的gdata客戶端庫確實有支持。 嘗試以下示例,我可以確認它可以正常工作。
https://code.google.com/p/gdata-python-client/source/browse/samples/apps/emailsettings_example.py
如果您的應用中有多個需要訪問EmailSettings API的入口點,這里有一個可重用的函數,它返回一個“客戶端”對象:
def google_get_emailsettings_credentials():
'''
Google's EmailSettings API is not yet service-based, so delegation data
has to be accessed differently from our other Google functions.
TODO: Refactor when API is updated.
'''
with open(settings.GOOGLE_PATH_TO_KEYFILE) as f:
private_key = f.read()
client = EmailSettingsClient(domain='example.com')
credentials = SignedJwtAssertionCredentials(
settings.GOOGLE_CLIENT_EMAIL,
private_key,
scope='https://apps-apis.google.com/a/feeds/emailsettings/2.0/',
sub=settings.GOOGLE_SUB_USER)
auth2token = gdata.gauth.OAuth2TokenFromCredentials(credentials)
auth2token.authorize(client)
return client
然后可以從其他地方調用它,例如到達DelegationFeed:
client = google_get_emailsettings_credentials()
uri = client.MakeEmailSettingsUri(username, 'delegation')
delegates_xml = client.get_entry(
uri=uri,
desired_class=gdata.apps.emailsettings.data.EmailSettingsDelegationFeed)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.