使用Gmail API的Python
问题描述:
获得KeyError异常这是从这个页面复制代码:https://developers.google.com/gmail/api/quickstart/python使用Gmail API的Python
from __future__ import print_function
import httplib2
import os
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/gmail-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/gmail.readonly'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Gmail API Python Quickstart'
def get_credentials():
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'gmail-python-quickstart.json')
store = Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatibility with Python 2.6
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials
def main():
"""Shows basic usage of the Gmail API.
Creates a Gmail API service object and outputs a list of label names
of the user's Gmail account.
"""
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('gmail', 'v1', http=http)
results = service.users().labels().list(userId='me').execute()
labels = results.get('labels', [])
if not labels:
print('No labels found.')
else:
print('Labels:')
for label in labels:
print(label['name'] + ": " + label['messagesTotal'])
if __name__ == '__main__':
main()
这是我唯一改变的行:
print(label['name'] + ": " + label['messagesTotal'])
为了显示标签和它的相应的总消息数量按照这里的文档:https://developers.google.com/gmail/api/v1/reference/users/labels
但是当我试图用python3运行这个,我得到这个错误:
Traceback (most recent call last):
File "quickstart.py", line 74, in <module>
main()
File "quickstart.py", line 70, in main
print(label['name'] + ": " + label['messagesTotal'])
KeyError: 'messagesTotal'
我很新的Python和使用JSON对象,所以任何链接到这些也将有所帮助。
答
这是一个相关的SO post面临同样的错误。
KeyError
表示该键不存在。
这是一篇文章中给出的例子。
>>> mydict = {'a':'1','b':'2'} >>> mydict['a'] '1' >>> mydict['c'] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'c' >>>
So, try to print the content of
meta_entry
and check whetherpath
exists or not.>>> mydict = {'a':'1','b':'2'} >>> print mydict {'a': '1', 'b': '2'}
Or, you can do:
>>> 'a' in mydict True >>> 'c' in mydict False
我意识到这意味着什么,但在Gmail API文档中存在'messagesTotal',我似乎无法使用它。我尝试了其他属性,其中一些属性起作用,而其中一些属性不起作用。 – Apple