• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/python
2#
3# Copyright 2014 Google Inc. All Rights Reserved.
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#      http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17"""This example retrieves a report for the specified ad client.
18
19Please only use pagination if your application requires it due to memory or
20storage constraints.
21If you need to retrieve more than 5000 rows, please check generate_report.py, as
22due to current limitations you will not be able to use paging for large reports.
23To get ad clients, run get_all_ad_clients.py.
24
25Tags: reports.generate
26"""
27from __future__ import print_function
28
29__author__ = 'sgomes@google.com (Sérgio Gomes)'
30
31import argparse
32import sys
33
34from googleapiclient import sample_tools
35from oauth2client import client
36
37MAX_PAGE_SIZE = 50
38# This is the maximum number of obtainable rows for paged reports.
39ROW_LIMIT = 5000
40
41# Declare command-line flags.
42argparser = argparse.ArgumentParser(add_help=False)
43argparser.add_argument('ad_client_id',
44    help='The ID of the ad client for which to generate a report')
45
46
47def main(argv):
48  # Authenticate and construct service.
49  service, flags = sample_tools.init(
50      argv, 'adexchangeseller', 'v1.1', __doc__, __file__, parents=[argparser],
51      scope='https://www.googleapis.com/auth/adexchange.seller.readonly')
52
53  ad_client_id = flags.ad_client_id
54
55  try:
56    # Retrieve report in pages and display data as we receive it.
57    start_index = 0
58    rows_to_obtain = MAX_PAGE_SIZE
59    while True:
60      result = service.reports().generate(
61          startDate='2011-01-01', endDate='2011-08-31',
62          filter=['AD_CLIENT_ID==' + ad_client_id],
63          metric=['PAGE_VIEWS', 'AD_REQUESTS', 'AD_REQUESTS_COVERAGE',
64                  'CLICKS', 'AD_REQUESTS_CTR', 'COST_PER_CLICK',
65                  'AD_REQUESTS_RPM', 'EARNINGS'],
66          dimension=['DATE'],
67          sort=['+DATE'],
68          startIndex=start_index,
69          maxResults=rows_to_obtain).execute()
70
71      # If this is the first page, display the headers.
72      if start_index == 0:
73        for header in result['headers']:
74          print('%25s' % header['name'], end=' ')
75        print()
76
77      # Display results for this page.
78      for row in result['rows']:
79        for column in row:
80          print('%25s' % column, end=' ')
81        print()
82
83      start_index += len(result['rows'])
84
85      # Check to see if we're going to go above the limit and get as many
86      # results as we can.
87      if start_index + MAX_PAGE_SIZE > ROW_LIMIT:
88        rows_to_obtain = ROW_LIMIT - start_index
89        if rows_to_obtain <= 0:
90          break
91
92      if (start_index >= int(result['totalMatchedRows'])):
93        break
94
95  except client.AccessTokenRefreshError:
96    print ('The credentials have been revoked or expired, please re-run the '
97           'application to re-authorize')
98
99if __name__ == '__main__':
100  main(sys.argv)
101