如何在Python

时间:2016-05-11 17:48:17

标签: python sdk admin google-apps

我正在尝试使用Google提供的基本Python教程,并将其修改为一个报告,向我显示我所在域中所有19000个用户的Google云端硬盘使用情况。对于每个用户,我都在寻找以下参数:

文档:NUM_DOCS, 文档:num_docs_edited, 文档:num_docs_viewed, 文档:num_uploaded_files

然而,我一直没有获得足够的特权"尝试执行以下代码时出错。我也明白代码可能无法正确打印我的参数,即使它确实运行了,所以请随时建议我如何实现这一点。

基本教程在这里:https://developers.google.com/admin-sdk/reports/v1/quickstart/python#step_3_set_up_the_sample

我使用用户使用情况报告API的修改版本如下。

from __future__ import print_function
import httplib2
import os

from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools

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/admin-reports_v1-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/admin.reports.usage.readonly'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Reports 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,
                                   'admin-reports_v1-python-quickstart.json')

    store = oauth2client.file.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 Google Admin SDK Reports API.

    Creates a Google Admin SDK Reports API service object and outputs a list of
    last 10 login events.
    """
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('admin', 'reports_v1', http=http)

    print('Getting the last 10 Drive events')
    results = reports.userUsageReport().get(userKey='all',
                                            date='2016-05-08',
                                            parameters='docs:num_docs, docs:num_docs_edited, docs:num_docs_viewed, docs:num_uploaded_files',
                                            customerId='*********',
                                            maxResults=20).execute()
    activities = results.get('items', [])

    if not activities:
        print('No logins found.')
    else:
        print('Logins:')
        for activity in activities:
            print('{0}: {1} ({2})'.format(activity['id']['time'],
                activity['actor']['email'], activity['events'][0]['name']))


if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:0)

我认为你错过了create_delegated部分。

service_credentials = ServiceAccountCredentials.from_json_keyfile_dict(config.gspread_credentials,
                                                                       admin_scopes)
 delegate_cred =  service_credentials.create_delegated(google_account_with_admin_privileges)
 http = delegate_cred.authorize(httplib2.Http())
 service = discovery.build('admin', 'reports_v1', http=http)