Add AdSense Management API sample code to repository.
Reviewed in http://codereview.appspot.com/5310054/ Index: samples/adsense/client_secrets.json =================================================================== new file mode 100755
This commit is contained in:
9
samples/adsense/client_secrets.json
Normal file
9
samples/adsense/client_secrets.json
Normal file
@@ -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"
|
||||
}
|
||||
}
|
||||
65
samples/adsense/generate_report.py
Normal file
65
samples/adsense/generate_report.py
Normal file
@@ -0,0 +1,65 @@
|
||||
#!/usr/bin/python
|
||||
#
|
||||
# Copyright 2011 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.
|
||||
|
||||
"""This example retrieves a report for the specified ad client.
|
||||
|
||||
To get ad clients, run get_all_ad_clients.py.
|
||||
Tags: reports.generate
|
||||
"""
|
||||
|
||||
__author__ = 'sergio.gomes@google.com (Sergio Gomes)'
|
||||
|
||||
import sys
|
||||
from oauth2client.client import AccessTokenRefreshError
|
||||
import sample_utils
|
||||
|
||||
|
||||
def main(argv):
|
||||
sample_utils.process_flags(argv)
|
||||
|
||||
# Authenticate and construct service.
|
||||
service = sample_utils.initialize_service()
|
||||
|
||||
ad_client_id = 'INSERT_AD_CLIENT_ID_HERE'
|
||||
|
||||
try:
|
||||
# Retrieve report.
|
||||
result = service.reports().generate(
|
||||
startDate='2011-01-01', endDate='2011-08-31',
|
||||
filter=['AD_CLIENT_ID==' + ad_client_id],
|
||||
metric=['PAGE_VIEWS', 'AD_REQUESTS', 'AD_REQUESTS_COVERAGE',
|
||||
'CLICKS', 'AD_REQUESTS_CTR', 'COST_PER_CLICK',
|
||||
'AD_REQUESTS_RPM', 'EARNINGS'],
|
||||
dimension=['DATE'],
|
||||
sort=['+DATE']).execute()
|
||||
|
||||
# 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
|
||||
|
||||
except AccessTokenRefreshError:
|
||||
print ('The credentials have been revoked or expired, please re-run the '
|
||||
'application to re-authorize')
|
||||
|
||||
if __name__ == '__main__':
|
||||
main(sys.argv)
|
||||
91
samples/adsense/generate_report_with_paging.py
Normal file
91
samples/adsense/generate_report_with_paging.py
Normal file
@@ -0,0 +1,91 @@
|
||||
#!/usr/bin/python
|
||||
#
|
||||
# Copyright 2011 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.
|
||||
|
||||
"""This example retrieves a report for the specified ad client.
|
||||
|
||||
Please only use pagination if your application requires it due to memory or
|
||||
storage constraints.
|
||||
If you need to retrieve more than 5000 rows, please check generate_report.py, as
|
||||
due to current limitations you will not be able to use paging for large reports.
|
||||
To get ad clients, run get_all_ad_clients.py.
|
||||
Tags: reports.generate
|
||||
"""
|
||||
|
||||
__author__ = 'sergio.gomes@google.com (Sergio Gomes)'
|
||||
|
||||
import sys
|
||||
from oauth2client.client import AccessTokenRefreshError
|
||||
import sample_utils
|
||||
|
||||
MAX_PAGE_SIZE = 50
|
||||
# This is the maximum number of obtainable rows for paged reports.
|
||||
ROW_LIMIT = 5000
|
||||
|
||||
|
||||
def main(argv):
|
||||
sample_utils.process_flags(argv)
|
||||
|
||||
# Authenticate and construct service.
|
||||
service = sample_utils.initialize_service()
|
||||
|
||||
ad_client_id = 'INSERT_AD_CLIENT_ID_HERE'
|
||||
|
||||
try:
|
||||
# Retrieve report in pages and display data as we receive it.
|
||||
start_index = 0
|
||||
rows_to_obtain = MAX_PAGE_SIZE
|
||||
while True:
|
||||
result = service.reports().generate(
|
||||
startDate='2011-01-01', endDate='2011-08-31',
|
||||
filter=['AD_CLIENT_ID==' + ad_client_id],
|
||||
metric=['PAGE_VIEWS', 'AD_REQUESTS', 'AD_REQUESTS_COVERAGE',
|
||||
'CLICKS', 'AD_REQUESTS_CTR', 'COST_PER_CLICK',
|
||||
'AD_REQUESTS_RPM', 'EARNINGS'],
|
||||
dimension=['DATE'],
|
||||
sort=['+DATE'],
|
||||
startIndex=start_index,
|
||||
maxResults=rows_to_obtain).execute()
|
||||
|
||||
# If this is the first page, display the headers.
|
||||
if start_index == 0:
|
||||
for header in result['headers']:
|
||||
print '%25s' % header['name'],
|
||||
print
|
||||
|
||||
# Display results for this page.
|
||||
for row in result['rows']:
|
||||
for column in row:
|
||||
print '%25s' % column,
|
||||
print
|
||||
|
||||
start_index += len(result['rows'])
|
||||
|
||||
# Check to see if we're going to go above the limit and get as many
|
||||
# results as we can.
|
||||
if start_index + MAX_PAGE_SIZE > ROW_LIMIT:
|
||||
rows_to_obtain = ROW_LIMIT - start_index
|
||||
if rows_to_obtain <= 0:
|
||||
break
|
||||
|
||||
if (start_index >= int(result['totalMatchedRows'])):
|
||||
break
|
||||
|
||||
except AccessTokenRefreshError:
|
||||
print ('The credentials have been revoked or expired, please re-run the '
|
||||
'application to re-authorize')
|
||||
|
||||
if __name__ == '__main__':
|
||||
main(sys.argv)
|
||||
58
samples/adsense/get_all_ad_clients.py
Normal file
58
samples/adsense/get_all_ad_clients.py
Normal file
@@ -0,0 +1,58 @@
|
||||
#!/usr/bin/python
|
||||
#
|
||||
# Copyright 2011 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.
|
||||
|
||||
"""This example gets all ad clients for an account.
|
||||
|
||||
Tags: adclients.list
|
||||
"""
|
||||
|
||||
__author__ = 'sergio.gomes@google.com (Sergio Gomes)'
|
||||
|
||||
import sys
|
||||
from oauth2client.client import AccessTokenRefreshError
|
||||
import sample_utils
|
||||
|
||||
MAX_PAGE_SIZE = 50
|
||||
|
||||
|
||||
def main(argv):
|
||||
sample_utils.process_flags(argv)
|
||||
|
||||
# Authenticate and construct service.
|
||||
service = sample_utils.initialize_service()
|
||||
|
||||
try:
|
||||
# Retrieve ad client list in pages and display data as we receive it.
|
||||
request = service.adclients().list(maxResults=MAX_PAGE_SIZE)
|
||||
|
||||
while ( request != None ):
|
||||
result = request.execute()
|
||||
ad_clients = result['items']
|
||||
for ad_client in ad_clients:
|
||||
print ('Ad client for product "%s" with ID "%s" was found. '
|
||||
% (ad_client['productCode'], ad_client['id']))
|
||||
|
||||
print ('\tSupports reporting: %s' %
|
||||
(ad_client['supportsReporting'] and 'Yes' or 'No'))
|
||||
|
||||
request = service.adclients().list_next(request, result)
|
||||
|
||||
except AccessTokenRefreshError:
|
||||
print ('The credentials have been revoked or expired, please re-run the '
|
||||
'application to re-authorize')
|
||||
|
||||
if __name__ == '__main__':
|
||||
main(sys.argv)
|
||||
59
samples/adsense/get_all_ad_units.py
Normal file
59
samples/adsense/get_all_ad_units.py
Normal file
@@ -0,0 +1,59 @@
|
||||
#!/usr/bin/python
|
||||
#
|
||||
# Copyright 2011 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.
|
||||
|
||||
"""This example gets all ad units in an ad client.
|
||||
|
||||
To get ad clients, run get_all_ad_clients.py.
|
||||
Tags: adunits.list
|
||||
"""
|
||||
|
||||
__author__ = 'sergio.gomes@google.com (Sergio Gomes)'
|
||||
|
||||
import sys
|
||||
from oauth2client.client import AccessTokenRefreshError
|
||||
import sample_utils
|
||||
|
||||
MAX_PAGE_SIZE = 50
|
||||
|
||||
|
||||
def main(argv):
|
||||
sample_utils.process_flags(argv)
|
||||
|
||||
# Authenticate and construct service.
|
||||
service = sample_utils.initialize_service()
|
||||
|
||||
ad_client_id = 'INSERT_AD_CLIENT_ID_HERE'
|
||||
|
||||
try:
|
||||
# Retrieve ad unit list in pages and display data as we receive it.
|
||||
request = service.adunits().list(adClientId=ad_client_id,
|
||||
maxResults=MAX_PAGE_SIZE)
|
||||
|
||||
while ( request != None ):
|
||||
result = request.execute()
|
||||
ad_units = result['items']
|
||||
for ad_unit in ad_units:
|
||||
print ('Ad unit with code "%s", name "%s" and status "%s" was found. ' %
|
||||
(ad_unit['code'], ad_unit['name'], ad_unit['status']))
|
||||
|
||||
request = service.adunits().list_next(request, result)
|
||||
|
||||
except AccessTokenRefreshError:
|
||||
print ('The credentials have been revoked or expired, please re-run the '
|
||||
'application to re-authorize')
|
||||
|
||||
if __name__ == '__main__':
|
||||
main(sys.argv)
|
||||
59
samples/adsense/get_all_custom_channels.py
Normal file
59
samples/adsense/get_all_custom_channels.py
Normal file
@@ -0,0 +1,59 @@
|
||||
#!/usr/bin/python
|
||||
#
|
||||
# Copyright 2011 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.
|
||||
|
||||
"""This example gets all custom channels in an ad client.
|
||||
|
||||
To get ad clients, run get_all_ad_clients.py.
|
||||
Tags: customchannels.list
|
||||
"""
|
||||
|
||||
__author__ = 'sergio.gomes@google.com (Sergio Gomes)'
|
||||
|
||||
import sys
|
||||
from oauth2client.client import AccessTokenRefreshError
|
||||
import sample_utils
|
||||
|
||||
MAX_PAGE_SIZE = 50
|
||||
|
||||
|
||||
def main(argv):
|
||||
sample_utils.process_flags(argv)
|
||||
|
||||
# Authenticate and construct service.
|
||||
service = sample_utils.initialize_service()
|
||||
|
||||
ad_client_id = 'INSERT_AD_CLIENT_ID_HERE'
|
||||
|
||||
try:
|
||||
# Retrieve custom channel list in pages and display data as we receive it.
|
||||
request = service.customchannels().list(adClientId=ad_client_id,
|
||||
maxResults=MAX_PAGE_SIZE)
|
||||
|
||||
while ( request != None ):
|
||||
result = request.execute()
|
||||
custom_channels = result['items']
|
||||
for custom_channel in custom_channels:
|
||||
print ('Custom channel with code "%s" and name "%s" was found. '
|
||||
% (custom_channel['code'], custom_channel['name']))
|
||||
|
||||
request = service.customchannels().list_next(request, result)
|
||||
|
||||
except AccessTokenRefreshError:
|
||||
print ('The credentials have been revoked or expired, please re-run the '
|
||||
'application to re-authorize')
|
||||
|
||||
if __name__ == '__main__':
|
||||
main(sys.argv)
|
||||
61
samples/adsense/get_all_url_channels.py
Normal file
61
samples/adsense/get_all_url_channels.py
Normal file
@@ -0,0 +1,61 @@
|
||||
#!/usr/bin/python
|
||||
#
|
||||
# Copyright 2011 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.
|
||||
|
||||
"""This example gets all URL channels in an ad client.
|
||||
|
||||
To get ad clients, run get_all_ad_clients.py.
|
||||
Tags: urlchannels.list
|
||||
"""
|
||||
|
||||
__author__ = 'sergio.gomes@google.com (Sergio Gomes)'
|
||||
|
||||
import sys
|
||||
from oauth2client.client import AccessTokenRefreshError
|
||||
import sample_utils
|
||||
|
||||
MAX_PAGE_SIZE = 50
|
||||
|
||||
|
||||
def main(argv):
|
||||
sample_utils.process_flags(argv)
|
||||
|
||||
# Authenticate and construct service.
|
||||
service = sample_utils.initialize_service()
|
||||
|
||||
ad_client_id = 'INSERT_AD_CLIENT_ID_HERE'
|
||||
|
||||
try:
|
||||
# Retrieve URL channel list in pages and display data as we receive it.
|
||||
request = service.urlchannels().list(adClientId=ad_client_id,
|
||||
maxResults=MAX_PAGE_SIZE)
|
||||
|
||||
while ( request != None ):
|
||||
result = request.execute()
|
||||
custom_channels = result['items']
|
||||
|
||||
url_channels = result['items']
|
||||
for url_channel in url_channels:
|
||||
print ('URL channel with URL pattern "%s" was found.'
|
||||
% url_channel['urlPattern'])
|
||||
|
||||
request = service.customchannels().list_next(request, result)
|
||||
|
||||
except AccessTokenRefreshError:
|
||||
print ('The credentials have been revoked or expired, please re-run the '
|
||||
'application to re-authorize')
|
||||
|
||||
if __name__ == '__main__':
|
||||
main(sys.argv)
|
||||
116
samples/adsense/sample_utils.py
Normal file
116
samples/adsense/sample_utils.py
Normal file
@@ -0,0 +1,116 @@
|
||||
#!/usr/bin/python
|
||||
#
|
||||
# Copyright 2011 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.
|
||||
|
||||
"""Auxiliary file for AdSense Management API code samples.
|
||||
|
||||
Handles various tasks to do with logging, authentication and initialization.
|
||||
"""
|
||||
|
||||
__author__ = 'sergio.gomes@google.com (Sergio Gomes)'
|
||||
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
from apiclient.discovery import build
|
||||
import gflags
|
||||
import httplib2
|
||||
from oauth2client.client import flow_from_clientsecrets
|
||||
from oauth2client.file import Storage
|
||||
from oauth2client.tools import run
|
||||
|
||||
|
||||
FLAGS = gflags.FLAGS
|
||||
|
||||
# CLIENT_SECRETS, name of a file containing the OAuth 2.0 information for this
|
||||
# application, including client_id and client_secret, which are found
|
||||
# on the API Access tab on the Google APIs
|
||||
# Console <http://code.google.com/apis/console>
|
||||
CLIENT_SECRETS = 'client_secrets.json'
|
||||
|
||||
# Helpful message to display in the browser if the CLIENT_SECRETS file
|
||||
# is missing.
|
||||
MISSING_CLIENT_SECRETS_MESSAGE = """
|
||||
WARNING: Please configure OAuth 2.0
|
||||
|
||||
To make this sample run you will need to populate the client_secrets.json file
|
||||
found at:
|
||||
|
||||
%s
|
||||
|
||||
with information from the APIs Console <https://code.google.com/apis/console>.
|
||||
|
||||
""" % os.path.join(os.path.dirname(__file__), CLIENT_SECRETS)
|
||||
|
||||
# Set up a Flow object to be used if we need to authenticate.
|
||||
FLOW = flow_from_clientsecrets(CLIENT_SECRETS,
|
||||
scope='https://www.googleapis.com/auth/adsense.readonly',
|
||||
message=MISSING_CLIENT_SECRETS_MESSAGE)
|
||||
|
||||
# The gflags module makes defining command-line options easy for applications.
|
||||
# Run this program with the '--help' argument to see all the flags that it
|
||||
# understands.
|
||||
gflags.DEFINE_enum('logging_level', 'ERROR',
|
||||
['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
|
||||
'Set the level of logging detail.')
|
||||
|
||||
|
||||
def process_flags(argv):
|
||||
"""Uses the command-line flags to set the logging level."""
|
||||
|
||||
# Let the gflags module process the command-line arguments.
|
||||
try:
|
||||
argv = FLAGS(argv)
|
||||
except gflags.FlagsError, e:
|
||||
print '%s\\nUsage: %s ARGS\\n%s' % (e, argv[0], FLAGS)
|
||||
sys.exit(1)
|
||||
|
||||
# Set the logging according to the command-line flag.
|
||||
logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level))
|
||||
|
||||
|
||||
def prepare_credentials():
|
||||
"""Handles auth. Reuses credentialss if available or runs the auth flow."""
|
||||
|
||||
# If the credentials don't exist or are invalid run through the native client
|
||||
# flow. The Storage object will ensure that if successful the good
|
||||
# Credentials will get written back to a file.
|
||||
storage = Storage('adsense.dat')
|
||||
credentials = storage.get()
|
||||
if credentials is None or credentials.invalid:
|
||||
credentials = run(FLOW, storage)
|
||||
return credentials
|
||||
|
||||
|
||||
def retrieve_service(http):
|
||||
"""Retrieves an AdSense Management API service via the discovery service."""
|
||||
|
||||
# Construct a service object via the discovery service.
|
||||
service = build("adsense", "v1", http=http)
|
||||
return service
|
||||
|
||||
|
||||
def initialize_service():
|
||||
"""Builds instance of service from discovery data and does auth."""
|
||||
|
||||
# Create an httplib2.Http object to handle our HTTP requests.
|
||||
http = httplib2.Http()
|
||||
|
||||
# Prepare credentials, and authorize HTTP object with them.
|
||||
credentials = prepare_credentials()
|
||||
http = credentials.authorize(http)
|
||||
|
||||
# Retrieve service.
|
||||
return retrieve_service(http)
|
||||
Reference in New Issue
Block a user