2017-09-04 84 views
0

獲得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對象,所以任何鏈接到這些也將有所幫助。

回答

0

這是一個相關的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 whether path 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 
+0

我意識到這意味着什麼,但在Gmail API文檔中存在'messagesTotal',我似乎無法使用它。我嘗試了其他屬性,其中一些屬性起作用,而其中一些屬性不起作用。 – Apple