2017-09-04 1 views
0

でGmailのAPIを使用してKeyError例外を取得:https://developers.google.com/gmail/api/quickstart/pythonこれは、このページからコピーしたコードである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

関連する問題