Skip to content

Commit

Permalink
First commit, adsense management api samples for v1.4
Browse files Browse the repository at this point in the history
  • Loading branch information
JoseAlcerreca committed Mar 10, 2014
0 parents commit 1abebce
Show file tree
Hide file tree
Showing 20 changed files with 1,436 additions and 0 deletions.
40 changes: 40 additions & 0 deletions python/v1.4/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# AdSense Management API v1.4 Samples

A collection of command-line samples for the AdSense Management API.

##Installation and first request

1. Download Google APIs Client Library for Python (google-api-python-client):
https://code.google.com/p/google-api-python-client/

or use pip:

```bash
$ pip install google-api-python-client```
2. Make sure you can import the client library:
```
$ python
>>> import apiclient```
3. Execute any of the scripts to begin the auth flow:
```bash
$ python get_all_accounts.py```
A browser window will open and ask you to login. Use the AdSense account.
4. Accept the permissions dialog. The browser should display
`The authentication flow has completed.`
Close the window and go back to the shell.
5. The script will output:
`Account with ID "pub-1234567890123456" and name "My account" was found.`
6. The tokens will be stored in adsense.dat.
Remove this file to restart the auth flow.
173 changes: 173 additions & 0 deletions python/v1.4/adsense_util.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
#!/usr/bin/python
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Utility class to handle multiple accounts per login.
"""

import copy
import datetime

__author__ = 'jalc@google.com (Jose Alcerreca)'

DATE_FORMAT = '%Y-%m-%d'
MONTH_FORMAT = '%Y-%m'


def get_account_id(service):
"""Gets the AdSense account id, letting the user choose if multiple exist.
Returns the selected account id.
"""
account_id = None
accounts = service.accounts().list().execute()
if len(accounts['items']) == 1:
account_id = accounts['items'][0]['id']
else:
print 'Multiple accounts were found. Please choose:'
for i, account in enumerate(accounts['items']):

print ' %d) %s (%s)' % (i, account['name'], account['id'])
selection = (raw_input('Please choose number 1-%d>'
% (len(accounts['items']))))
account_id = accounts['items'][int(selection) - 1]['id']
return account_id


def fill_date_gaps(result):
"""Fills gaps and sorts the result object. Doesn't fill "WEEK" or "MONTH"
dimensions.
Returns the same structure with dummy rows for non-existing dates.
>>> result = {'headers': [{'name':'DATE'}, {'name':'EARNINGS'}], 'rows': [],\
'startDate':'2012-12-29', 'endDate':'2013-01-01'}
>>> fill_date_gaps(result)
{'headers': [{'name': 'DATE'}, {'name': 'EARNINGS'}], 'rows': [['2012-12-29'\
, 'N/A'], ['2012-12-30', 'N/A'], ['2012-12-31', 'N/A'], ['2013-01-01', 'N/A']]\
, 'endDate': '2013-01-01', 'startDate': '2012-12-29'}
"""

date_index = None
month_index = None
try:
date_index = [x['name'] for x in result['headers']].index('DATE')
except ValueError:
pass
try:
month_index = [x['name'] for x in result['headers']].index('MONTH')
except ValueError:
pass

if date_index is None and month_index is None:
return result

# Convert dates
from_st, to_st = result['startDate'], result['endDate']
from_date = datetime.datetime.strptime(from_st, DATE_FORMAT)
to_date = datetime.datetime.strptime(to_st, DATE_FORMAT)

# Rebuild result.
result_fill = copy.deepcopy(result)
result_fill['rows'] = []

# Days.
if date_index is not None:
for i in range((to_date - from_date).days + 1):
cursor_date = from_date + datetime.timedelta(days=i)
cursor_st = cursor_date.strftime(DATE_FORMAT)

new_row = ['N/A' for x in result['headers']]
new_row[date_index] = cursor_st
if month_index is not None:
new_row[month_index] = cursor_date.strftime(MONTH_FORMAT)

# Get the data from original object.
if 'rows' in result:
for row in result['rows']:
if row[date_index] == cursor_st:
new_row = row
break

result_fill['rows'].append(new_row)

return result_fill
# Months.
months_delta = _months_delta(to_date, from_date)
if month_index is not None:
for i in range(months_delta):
cursor_date = from_date
for _ in range(i):
cursor_date = _increase_month(cursor_date)
cursor_st = cursor_date.strftime(MONTH_FORMAT)

new_row = ['N/A' for x in result['headers']]
new_row[month_index] = cursor_st

# Get the data from original object.
if 'rows' in result:
for row in result['rows']:
if row[month_index] == cursor_st:
new_row = row
break

result_fill['rows'].append(new_row)
return result_fill


def _months_delta(to_date, from_date):
"""Check how many months, inclusive, between two months
Returns the number of months as an integer.
>>> _months_delta(datetime.datetime(2014,01,01), \
datetime.datetime(2013,12,31))
2
>>> _months_delta(datetime.datetime(2014,01,01), \
datetime.datetime(2013,12,01))
2
>>> _months_delta(datetime.datetime(2013,12,31), \
datetime.datetime(2013,12,01))
1
>>> _months_delta(datetime.datetime(2014,01,01), \
datetime.datetime(2013,01,31))
13
>>> _months_delta(datetime.datetime(2014,05,01), \
datetime.datetime(2012,12,31))
18
"""
months_delta = (to_date.year - from_date.year) * 12
return to_date.month - from_date.month + months_delta + 1


def _increase_month(date):
"""Increase a date one month.
Returns a datetime object.
>>> _increase_month(datetime.datetime(2014,05,01))
datetime.datetime(2014, 6, 1, 0, 0)
>>> _increase_month(datetime.datetime(2014,12,01))
datetime.datetime(2015, 1, 1, 0, 0)
"""
if date.month == 12:
return datetime.datetime(date.year + 1, 1, date.day)
return datetime.datetime(date.year, date.month + 1, date.day)

if __name__ == "__main__":
import doctest
doctest.testmod()
9 changes: 9 additions & 0 deletions python/v1.4/client_secrets.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"installed": {
"client_id": "[[INSERT CLIENT ID HERE]]",
"client_secret": "[[INSERT CLIENT SECRET HERE]]",
"redirect_uris": [],
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token"
}
}
88 changes: 88 additions & 0 deletions python/v1.4/generate_report.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
#!/usr/bin/python
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Retrieves a saved report or generates a new one.
To get ad clients, run get_all_ad_clients.py.
Tags: reports.generate
"""

__author__ = 'jalc@google.com (Jose Alcerreca)'

import argparse
import sys
from apiclient import sample_tools
from oauth2client import client
from adsense_util import fill_date_gaps
from adsense_util import get_account_id

# Declare command-line flags.
argparser = argparse.ArgumentParser(add_help=False)
argparser.add_argument(
'--report_id',
help='The ID of the saved report to generate')


def main(argv):
# Authenticate and construct service.
service, flags = sample_tools.init(
argv, 'adsense', 'v1.4', __doc__, __file__, parents=[argparser],
scope='https://www.googleapis.com/auth/adsense.readonly')

# Process flags and read their values.
saved_report_id = flags.report_id

try:
# Let the user pick account if more than one.
account_id = get_account_id(service)

# Retrieve report.
if saved_report_id:
result = service.accounts().reports().saved().generate(
accountId=account_id, savedReportId=saved_report_id).execute()
else:
result = service.accounts().reports().generate(
accountId=account_id, startDate='today-1y', endDate='today',
metric=['PAGE_VIEWS', 'AD_REQUESTS', 'AD_REQUESTS_COVERAGE',
'CLICKS', 'AD_REQUESTS_CTR', 'COST_PER_CLICK',
'AD_REQUESTS_RPM', 'EARNINGS'],
dimension=['DATE', 'MONTH', 'WEEK'],
sort=['+DATE']).execute()

result = fill_date_gaps(result)

# Display headers.
for header in result['headers']:
print '%25s' % header['name'],
print

# Display results.
for row in result['rows']:
for column in row:
print '%25s' % column,
print

# Display date range.
print 'Report from %s to %s.' % (result['startDate'], result['endDate'])
print

except client.AccessTokenRefreshError:
print ('The credentials have been revoked or expired, please re-run the '
'application to re-authorize')

if __name__ == '__main__':
main(sys.argv)
Loading

0 comments on commit 1abebce

Please sign in to comment.