Я пытаюсь взять основной учебник Python, предоставленный Google, и изменить его в отчете, который показывает мне использование Google Диска для всех пользователей 19000 в моем домене. Для каждого пользователя, я ищу для следующих параметров:Как создать отчет об использовании пользователей Google Apps в Python
документов: 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()