Merge pull request #25 from methane/prepare-py3
Work toward Python 3.
diff --git a/googleapiclient/discovery.py b/googleapiclient/discovery.py
index afba86f..cbb10db 100644
--- a/googleapiclient/discovery.py
+++ b/googleapiclient/discovery.py
@@ -16,6 +16,7 @@
A client library for Google's discovery based APIs.
"""
+from __future__ import absolute_import
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
__all__ = [
@@ -48,7 +49,7 @@
# Third-party imports
import httplib2
-import mimeparse
+from . import mimeparse
import uritemplate
# Local imports
@@ -205,7 +206,7 @@
try:
service = json.loads(content)
- except ValueError, e:
+ except ValueError as e:
logger.error('Failed to parse as JSON: ' + content)
raise InvalidJsonError()
@@ -329,13 +330,13 @@
The size as an integer value.
"""
if len(maxSize) < 2:
- return 0L
+ return 0
units = maxSize[-2:].upper()
bit_shift = _MEDIA_SIZE_BIT_SHIFTS.get(units)
if bit_shift is not None:
- return long(maxSize[:-2]) << bit_shift
+ return int(maxSize[:-2]) << bit_shift
else:
- return long(maxSize)
+ return int(maxSize)
def _media_path_url_from_info(root_desc, path_url):
diff --git a/googleapiclient/http.py b/googleapiclient/http.py
index 22cb80c..0edf884 100644
--- a/googleapiclient/http.py
+++ b/googleapiclient/http.py
@@ -18,6 +18,7 @@
object supporting an execute() method that does the
actuall HTTP request.
"""
+from __future__ import absolute_import
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
@@ -28,7 +29,7 @@
import httplib2
import json
import logging
-import mimeparse
+from . import mimeparse
import mimetypes
import os
import random
@@ -42,13 +43,13 @@
from email.mime.multipart import MIMEMultipart
from email.mime.nonmultipart import MIMENonMultipart
from email.parser import FeedParser
-from errors import BatchError
-from errors import HttpError
-from errors import InvalidChunkSizeError
-from errors import ResumableUploadError
-from errors import UnexpectedBodyError
-from errors import UnexpectedMethodError
-from model import JsonModel
+from .errors import BatchError
+from .errors import HttpError
+from .errors import InvalidChunkSizeError
+from .errors import ResumableUploadError
+from .errors import UnexpectedBodyError
+from .errors import UnexpectedMethodError
+from .model import JsonModel
from oauth2client import util
@@ -1330,7 +1331,7 @@
if resp.status >= 300:
raise HttpError(resp, content, uri=request.uri)
response = request.postproc(resp, content)
- except HttpError, e:
+ except HttpError as e:
exception = e
if callback is not None:
diff --git a/googleapiclient/mimeparse.py b/googleapiclient/mimeparse.py
index 8038af1..68d3a3c 100644
--- a/googleapiclient/mimeparse.py
+++ b/googleapiclient/mimeparse.py
@@ -21,6 +21,7 @@
- best_match(): Choose the mime-type with the highest quality ('q')
from a list of candidates.
"""
+from functools import reduce
__version__ = '0.1.3'
__author__ = 'Joe Gregorio'
@@ -68,7 +69,7 @@
necessary.
"""
(type, subtype, params) = parse_mime_type(range)
- if not params.has_key('q') or not params['q'] or \
+ if 'q' not in params or not params['q'] or \
not float(params['q']) or float(params['q']) > 1\
or float(params['q']) < 0:
params['q'] = '1'
@@ -99,7 +100,7 @@
if type_match and subtype_match:
param_matches = reduce(lambda x, y: x + y, [1 for (key, value) in \
target_params.iteritems() if key != 'q' and \
- params.has_key(key) and value == params[key]], 0)
+ key in params and value == params[key]], 0)
fitness = (type == target_type) and 100 or 0
fitness += (subtype == target_subtype) and 10 or 0
fitness += param_matches
diff --git a/googleapiclient/model.py b/googleapiclient/model.py
index 46e3aec..e55b4fa 100644
--- a/googleapiclient/model.py
+++ b/googleapiclient/model.py
@@ -19,6 +19,7 @@
for converting between the wire format and the Python
object representation.
"""
+from __future__ import absolute_import
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
@@ -27,7 +28,7 @@
import urllib
from googleapiclient import __version__
-from errors import HttpError
+from .errors import HttpError
dump_request_response = False
diff --git a/samples-index.py b/samples-index.py
index 712f552..086886a 100644
--- a/samples-index.py
+++ b/samples-index.py
@@ -28,6 +28,7 @@
The rest of the file is ignored when it comes to building the index.
"""
+from __future__ import print_function
import httplib2
import itertools
@@ -239,7 +240,7 @@
</tr>""" % context)
page.append('</table>\n')
- print ''.join(page)
+ print(''.join(page))
if __name__ == '__main__':
diff --git a/samples/adexchangeseller/generate_report.py b/samples/adexchangeseller/generate_report.py
index 8440caa..510c94b 100644
--- a/samples/adexchangeseller/generate_report.py
+++ b/samples/adexchangeseller/generate_report.py
@@ -20,6 +20,7 @@
Tags: reports.generate
"""
+from __future__ import print_function
__author__ = 'sgomes@google.com (Sérgio Gomes)'
@@ -68,14 +69,14 @@
sys.exit(1)
# Display headers.
for header in result['headers']:
- print '%25s' % header['name'],
- print
+ print('%25s' % header['name'], end=' ')
+ print()
# Display results.
for row in result['rows']:
for column in row:
- print '%25s' % column,
- print
+ print('%25s' % column, end=' ')
+ print()
except client.AccessTokenRefreshError:
print ('The credentials have been revoked or expired, please re-run the '
diff --git a/samples/adexchangeseller/generate_report_with_paging.py b/samples/adexchangeseller/generate_report_with_paging.py
index ed14976..9ef1b0c 100644
--- a/samples/adexchangeseller/generate_report_with_paging.py
+++ b/samples/adexchangeseller/generate_report_with_paging.py
@@ -24,6 +24,7 @@
Tags: reports.generate
"""
+from __future__ import print_function
__author__ = 'sgomes@google.com (Sérgio Gomes)'
@@ -70,14 +71,14 @@
# If this is the first page, display the headers.
if start_index == 0:
for header in result['headers']:
- print '%25s' % header['name'],
- print
+ print('%25s' % header['name'], end=' ')
+ print()
# Display results for this page.
for row in result['rows']:
for column in row:
- print '%25s' % column,
- print
+ print('%25s' % column, end=' ')
+ print()
start_index += len(result['rows'])
diff --git a/samples/adexchangeseller/get_all_ad_clients.py b/samples/adexchangeseller/get_all_ad_clients.py
index 67333d2..a06d3bd 100644
--- a/samples/adexchangeseller/get_all_ad_clients.py
+++ b/samples/adexchangeseller/get_all_ad_clients.py
@@ -18,6 +18,7 @@
Tags: adclients.list
"""
+from __future__ import print_function
__author__ = 'sgomes@google.com (Sérgio Gomes)'
@@ -43,11 +44,11 @@
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(('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'))
+ print(('\tSupports reporting: %s' %
+ (ad_client['supportsReporting'] and 'Yes' or 'No')))
request = service.adclients().list_next(request, result)
diff --git a/samples/adexchangeseller/get_all_ad_units.py b/samples/adexchangeseller/get_all_ad_units.py
index 317199b..8599545 100644
--- a/samples/adexchangeseller/get_all_ad_units.py
+++ b/samples/adexchangeseller/get_all_ad_units.py
@@ -20,6 +20,7 @@
Tags: adunits.list
"""
+from __future__ import print_function
__author__ = 'sgomes@google.com (Sérgio Gomes)'
@@ -54,8 +55,8 @@
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']))
+ 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)
diff --git a/samples/adexchangeseller/get_all_ad_units_for_custom_channel.py b/samples/adexchangeseller/get_all_ad_units_for_custom_channel.py
index 2e9f4ba..0c63225 100644
--- a/samples/adexchangeseller/get_all_ad_units_for_custom_channel.py
+++ b/samples/adexchangeseller/get_all_ad_units_for_custom_channel.py
@@ -20,6 +20,7 @@
Tags: customchannels.adunits.list
"""
+from __future__ import print_function
__author__ = 'sgomes@google.com (Sérgio Gomes)'
@@ -59,8 +60,8 @@
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']))
+ 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)
diff --git a/samples/adexchangeseller/get_all_alerts.py b/samples/adexchangeseller/get_all_alerts.py
index 459038c..f15ef51 100644
--- a/samples/adexchangeseller/get_all_alerts.py
+++ b/samples/adexchangeseller/get_all_alerts.py
@@ -18,6 +18,7 @@
Tags: alerts.list
"""
+from __future__ import print_function
__author__ = 'sgomes@google.com (Sérgio Gomes)'
@@ -43,10 +44,10 @@
if 'items' in result:
alerts = result['items']
for alert in alerts:
- print ('Alert id "%s" with severity "%s" and type "%s" was found. '
- % (alert['id'], alert['severity'], alert['type']))
+ print(('Alert id "%s" with severity "%s" and type "%s" was found. '
+ % (alert['id'], alert['severity'], alert['type'])))
else:
- print 'No alerts found!'
+ print('No alerts found!')
except client.AccessTokenRefreshError:
print ('The credentials have been revoked or expired, please re-run the '
'application to re-authorize')
diff --git a/samples/adexchangeseller/get_all_custom_channels.py b/samples/adexchangeseller/get_all_custom_channels.py
index 43b5eca..68f92d2 100644
--- a/samples/adexchangeseller/get_all_custom_channels.py
+++ b/samples/adexchangeseller/get_all_custom_channels.py
@@ -20,6 +20,7 @@
Tags: customchannels.list
"""
+from __future__ import print_function
__author__ = 'sgomes@google.com (Sérgio Gomes)'
@@ -54,20 +55,20 @@
result = request.execute()
custom_channels = result['items']
for custom_channel in custom_channels:
- print ('Custom channel with id "%s" and name "%s" was found. '
- % (custom_channel['id'], custom_channel['name']))
+ print(('Custom channel with id "%s" and name "%s" was found. '
+ % (custom_channel['id'], custom_channel['name'])))
if 'targetingInfo' in custom_channel:
- print ' Targeting info:'
+ print(' Targeting info:')
targeting_info = custom_channel['targetingInfo']
if 'adsAppearOn' in targeting_info:
- print ' Ads appear on: %s' % targeting_info['adsAppearOn']
+ print(' Ads appear on: %s' % targeting_info['adsAppearOn'])
if 'location' in targeting_info:
- print ' Location: %s' % targeting_info['location']
+ print(' Location: %s' % targeting_info['location'])
if 'description' in targeting_info:
- print ' Description: %s' % targeting_info['description']
+ print(' Description: %s' % targeting_info['description'])
if 'siteLanguage' in targeting_info:
- print ' Site language: %s' % targeting_info['siteLanguage']
+ print(' Site language: %s' % targeting_info['siteLanguage'])
request = service.customchannels().list_next(request, result)
diff --git a/samples/adexchangeseller/get_all_custom_channels_for_ad_unit.py b/samples/adexchangeseller/get_all_custom_channels_for_ad_unit.py
index 78205a1..b73bf15 100644
--- a/samples/adexchangeseller/get_all_custom_channels_for_ad_unit.py
+++ b/samples/adexchangeseller/get_all_custom_channels_for_ad_unit.py
@@ -21,6 +21,7 @@
Tags: customchannels.list
"""
+from __future__ import print_function
__author__ = 'sgomes@google.com (Sérgio Gomes)'
@@ -62,20 +63,20 @@
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']))
+ print(('Custom channel with code "%s" and name "%s" was found. '
+ % (custom_channel['code'], custom_channel['name'])))
if 'targetingInfo' in custom_channel:
- print ' Targeting info:'
+ print(' Targeting info:')
targeting_info = custom_channel['targetingInfo']
if 'adsAppearOn' in targeting_info:
- print ' Ads appear on: %s' % targeting_info['adsAppearOn']
+ print(' Ads appear on: %s' % targeting_info['adsAppearOn'])
if 'location' in targeting_info:
- print ' Location: %s' % targeting_info['location']
+ print(' Location: %s' % targeting_info['location'])
if 'description' in targeting_info:
- print ' Description: %s' % targeting_info['description']
+ print(' Description: %s' % targeting_info['description'])
if 'siteLanguage' in targeting_info:
- print ' Site language: %s' % targeting_info['siteLanguage']
+ print(' Site language: %s' % targeting_info['siteLanguage'])
request = service.customchannels().list_next(request, result)
diff --git a/samples/adexchangeseller/get_all_dimensions.py b/samples/adexchangeseller/get_all_dimensions.py
index 6c0e585..0c6bec7 100644
--- a/samples/adexchangeseller/get_all_dimensions.py
+++ b/samples/adexchangeseller/get_all_dimensions.py
@@ -18,6 +18,7 @@
Tags: metadata.dimensions.list
"""
+from __future__ import print_function
__author__ = 'sgomes@google.com (Sérgio Gomes)'
@@ -43,10 +44,10 @@
if 'items' in result:
dimensions = result['items']
for dimension in dimensions:
- print ('Dimension id "%s" for product(s): [%s] was found. '
- % (dimension['id'], ', '.join(dimension['supportedProducts'])))
+ print(('Dimension id "%s" for product(s): [%s] was found. '
+ % (dimension['id'], ', '.join(dimension['supportedProducts']))))
else:
- print 'No dimensions found!'
+ print('No dimensions found!')
except client.AccessTokenRefreshError:
print ('The credentials have been revoked or expired, please re-run the '
'application to re-authorize')
diff --git a/samples/adexchangeseller/get_all_metrics.py b/samples/adexchangeseller/get_all_metrics.py
index c1bf06f..0f2df22 100644
--- a/samples/adexchangeseller/get_all_metrics.py
+++ b/samples/adexchangeseller/get_all_metrics.py
@@ -18,6 +18,7 @@
Tags: metadata.metrics.list
"""
+from __future__ import print_function
__author__ = 'sgomes@google.com (Sérgio Gomes)'
@@ -43,10 +44,10 @@
if 'items' in result:
metrics = result['items']
for metric in metrics:
- print ('Metric id "%s" for product(s): [%s] was found. '
- % (metric['id'], ', '.join(metric['supportedProducts'])))
+ print(('Metric id "%s" for product(s): [%s] was found. '
+ % (metric['id'], ', '.join(metric['supportedProducts']))))
else:
- print 'No metrics found!'
+ print('No metrics found!')
except client.AccessTokenRefreshError:
print ('The credentials have been revoked or expired, please re-run the '
'application to re-authorize')
diff --git a/samples/adexchangeseller/get_all_preferred_deals.py b/samples/adexchangeseller/get_all_preferred_deals.py
index 1614183..3ef38a4 100644
--- a/samples/adexchangeseller/get_all_preferred_deals.py
+++ b/samples/adexchangeseller/get_all_preferred_deals.py
@@ -18,6 +18,7 @@
Tags: preferreddeals.list
"""
+from __future__ import print_function
__author__ = 'sgomes@google.com (Sérgio Gomes)'
@@ -54,7 +55,7 @@
output += 'was found.'
print(output)
else:
- print 'No preferred deals found!'
+ print('No preferred deals found!')
except client.AccessTokenRefreshError:
print ('The credentials have been revoked or expired, please re-run the '
'application to re-authorize')
diff --git a/samples/adexchangeseller/get_all_saved_reports.py b/samples/adexchangeseller/get_all_saved_reports.py
index 5f19e7c..fed0885 100644
--- a/samples/adexchangeseller/get_all_saved_reports.py
+++ b/samples/adexchangeseller/get_all_saved_reports.py
@@ -19,6 +19,7 @@
Tags: savedreports.list
"""
+from __future__ import print_function
__author__ = 'sgomes@google.com (Sérgio Gomes)'
@@ -44,8 +45,8 @@
result = request.execute()
saved_reports = result['items']
for saved_report in saved_reports:
- print ('Saved report with ID "%s" and name "%s" was found.'
- % (saved_report['id'], saved_report['name']))
+ print(('Saved report with ID "%s" and name "%s" was found.'
+ % (saved_report['id'], saved_report['name'])))
request = service.reports().saved().list_next(request, result)
diff --git a/samples/adexchangeseller/get_all_url_channels.py b/samples/adexchangeseller/get_all_url_channels.py
index 262cab3..c19c6ee 100644
--- a/samples/adexchangeseller/get_all_url_channels.py
+++ b/samples/adexchangeseller/get_all_url_channels.py
@@ -20,6 +20,7 @@
Tags: urlchannels.list
"""
+from __future__ import print_function
__author__ = 'sgomes@google.com (Sérgio Gomes)'
@@ -55,8 +56,8 @@
url_channels = result['items']
for url_channel in url_channels:
- print ('URL channel with URL pattern "%s" was found.'
- % url_channel['urlPattern'])
+ print(('URL channel with URL pattern "%s" was found.'
+ % url_channel['urlPattern']))
request = service.customchannels().list_next(request, result)
diff --git a/samples/analytics/core_reporting_v3_reference.py b/samples/analytics/core_reporting_v3_reference.py
index 566cf2d..671f4ef 100755
--- a/samples/analytics/core_reporting_v3_reference.py
+++ b/samples/analytics/core_reporting_v3_reference.py
@@ -56,6 +56,7 @@
$ python core_reporting_v3_reference.py --help
"""
+from __future__ import print_function
__author__ = 'api.nickm@gmail.com (Nick Mihailovski)'
@@ -84,14 +85,14 @@
results = get_api_query(service, flags.table_id).execute()
print_results(results)
- except TypeError, error:
+ except TypeError as error:
# Handle errors in constructing a query.
- print ('There was an error in constructing your query : %s' % error)
+ print(('There was an error in constructing your query : %s' % error))
- except HttpError, error:
+ except HttpError as error:
# Handle API errors.
- print ('Arg, there was an API error : %s : %s' %
- (error.resp.status, error._get_reason()))
+ print(('Arg, there was an API error : %s : %s' %
+ (error.resp.status, error._get_reason())))
except AccessTokenRefreshError:
# Handle Auth errors.
@@ -142,12 +143,12 @@
results: The response returned from the Core Reporting API.
"""
- print 'Report Infos:'
- print 'Contains Sampled Data = %s' % results.get('containsSampledData')
- print 'Kind = %s' % results.get('kind')
- print 'ID = %s' % results.get('id')
- print 'Self Link = %s' % results.get('selfLink')
- print
+ print('Report Infos:')
+ print('Contains Sampled Data = %s' % results.get('containsSampledData'))
+ print('Kind = %s' % results.get('kind'))
+ print('ID = %s' % results.get('id'))
+ print('Self Link = %s' % results.get('selfLink'))
+ print()
def print_pagination_info(results):
@@ -157,16 +158,16 @@
results: The response returned from the Core Reporting API.
"""
- print 'Pagination Infos:'
- print 'Items per page = %s' % results.get('itemsPerPage')
- print 'Total Results = %s' % results.get('totalResults')
+ print('Pagination Infos:')
+ print('Items per page = %s' % results.get('itemsPerPage'))
+ print('Total Results = %s' % results.get('totalResults'))
# These only have values if other result pages exist.
if results.get('previousLink'):
- print 'Previous Link = %s' % results.get('previousLink')
+ print('Previous Link = %s' % results.get('previousLink'))
if results.get('nextLink'):
- print 'Next Link = %s' % results.get('nextLink')
- print
+ print('Next Link = %s' % results.get('nextLink'))
+ print()
def print_profile_info(results):
@@ -176,14 +177,14 @@
results: The response returned from the Core Reporting API.
"""
- print 'Profile Infos:'
+ print('Profile Infos:')
info = results.get('profileInfo')
- print 'Account Id = %s' % info.get('accountId')
- print 'Web Property Id = %s' % info.get('webPropertyId')
- print 'Profile Id = %s' % info.get('profileId')
- print 'Table Id = %s' % info.get('tableId')
- print 'Profile Name = %s' % info.get('profileName')
- print
+ print('Account Id = %s' % info.get('accountId'))
+ print('Web Property Id = %s' % info.get('webPropertyId'))
+ print('Profile Id = %s' % info.get('profileId'))
+ print('Table Id = %s' % info.get('tableId'))
+ print('Profile Name = %s' % info.get('profileName'))
+ print()
def print_query(results):
@@ -193,11 +194,11 @@
results: The response returned from the Core Reporting API.
"""
- print 'Query Parameters:'
+ print('Query Parameters:')
query = results.get('query')
for key, value in query.iteritems():
- print '%s = %s' % (key, value)
- print
+ print('%s = %s' % (key, value))
+ print()
def print_column_headers(results):
@@ -211,15 +212,15 @@
results: The response returned from the Core Reporting API.
"""
- print 'Column Headers:'
+ print('Column Headers:')
headers = results.get('columnHeaders')
for header in headers:
# Print Dimension or Metric name.
- print '\t%s name: = %s' % (header.get('columnType').title(),
- header.get('name'))
- print '\tColumn Type = %s' % header.get('columnType')
- print '\tData Type = %s' % header.get('dataType')
- print
+ print('\t%s name: = %s' % (header.get('columnType').title(),
+ header.get('name')))
+ print('\tColumn Type = %s' % header.get('columnType'))
+ print('\tData Type = %s' % header.get('dataType'))
+ print()
def print_totals_for_all_results(results):
@@ -229,17 +230,17 @@
results: The response returned from the Core Reporting API.
"""
- print 'Total Metrics For All Results:'
- print 'This query returned %s rows.' % len(results.get('rows'))
- print ('But the query matched %s total results.' %
- results.get('totalResults'))
- print 'Here are the metric totals for the matched total results.'
+ print('Total Metrics For All Results:')
+ print('This query returned %s rows.' % len(results.get('rows')))
+ print(('But the query matched %s total results.' %
+ results.get('totalResults')))
+ print('Here are the metric totals for the matched total results.')
totals = results.get('totalsForAllResults')
for metric_name, metric_total in totals.iteritems():
- print 'Metric Name = %s' % metric_name
- print 'Metric Total = %s' % metric_total
- print
+ print('Metric Name = %s' % metric_name)
+ print('Metric Total = %s' % metric_total)
+ print()
def print_rows(results):
@@ -249,12 +250,12 @@
results: The response returned from the Core Reporting API.
"""
- print 'Rows:'
+ print('Rows:')
if results.get('rows', []):
for row in results.get('rows'):
- print '\t'.join(row)
+ print('\t'.join(row))
else:
- print 'No Rows Found'
+ print('No Rows Found')
if __name__ == '__main__':
diff --git a/samples/analytics/hello_analytics_api_v3.py b/samples/analytics/hello_analytics_api_v3.py
index 686197b..783594f 100755
--- a/samples/analytics/hello_analytics_api_v3.py
+++ b/samples/analytics/hello_analytics_api_v3.py
@@ -40,6 +40,7 @@
$ python hello_analytics_api_v3.py --help
"""
+from __future__ import print_function
__author__ = 'api.nickm@gmail.com (Nick Mihailovski)'
@@ -61,19 +62,19 @@
try:
first_profile_id = get_first_profile_id(service)
if not first_profile_id:
- print 'Could not find a valid profile for this user.'
+ print('Could not find a valid profile for this user.')
else:
results = get_top_keywords(service, first_profile_id)
print_results(results)
- except TypeError, error:
+ except TypeError as error:
# Handle errors in constructing a query.
- print ('There was an error in constructing your query : %s' % error)
+ print(('There was an error in constructing your query : %s' % error))
- except HttpError, error:
+ except HttpError as error:
# Handle API errors.
- print ('Arg, there was an API error : %s : %s' %
- (error.resp.status, error._get_reason()))
+ print(('Arg, there was an API error : %s : %s' %
+ (error.resp.status, error._get_reason())))
except AccessTokenRefreshError:
# Handle Auth errors.
@@ -151,15 +152,15 @@
results: The response returned from the Core Reporting API.
"""
- print
- print 'Profile Name: %s' % results.get('profileInfo').get('profileName')
- print
+ print()
+ print('Profile Name: %s' % results.get('profileInfo').get('profileName'))
+ print()
# Print header.
output = []
for header in results.get('columnHeaders'):
output.append('%30s' % header.get('name'))
- print ''.join(output)
+ print(''.join(output))
# Print data table.
if results.get('rows', []):
@@ -167,10 +168,10 @@
output = []
for cell in row:
output.append('%30s' % cell)
- print ''.join(output)
+ print(''.join(output))
else:
- print 'No Rows Found'
+ print('No Rows Found')
if __name__ == '__main__':
diff --git a/samples/analytics/management_v3_reference.py b/samples/analytics/management_v3_reference.py
index 5fdbd93..51bf78d 100755
--- a/samples/analytics/management_v3_reference.py
+++ b/samples/analytics/management_v3_reference.py
@@ -50,6 +50,7 @@
$ python management_v3_reference.py --help
"""
+from __future__ import print_function
__author__ = 'api.nickm@gmail.com (Nick Mihailovski)'
@@ -71,14 +72,14 @@
try:
traverse_hiearchy(service)
- except TypeError, error:
+ except TypeError as error:
# Handle errors in constructing a query.
- print ('There was an error in constructing your query : %s' % error)
+ print(('There was an error in constructing your query : %s' % error))
- except HttpError, error:
+ except HttpError as error:
# Handle API errors.
- print ('Arg, there was an API error : %s : %s' %
- (error.resp.status, error._get_reason()))
+ print(('Arg, there was an API error : %s : %s' %
+ (error.resp.status, error._get_reason())))
except AccessTokenRefreshError:
print ('The credentials have been revoked or expired, please re-run'
@@ -139,25 +140,25 @@
collection.
"""
- print '------ Account Collection -------'
+ print('------ Account Collection -------')
print_pagination_info(accounts_response)
- print
+ print()
for account in accounts_response.get('items', []):
- print 'Account ID = %s' % account.get('id')
- print 'Kind = %s' % account.get('kind')
- print 'Self Link = %s' % account.get('selfLink')
- print 'Account Name = %s' % account.get('name')
- print 'Created = %s' % account.get('created')
- print 'Updated = %s' % account.get('updated')
+ print('Account ID = %s' % account.get('id'))
+ print('Kind = %s' % account.get('kind'))
+ print('Self Link = %s' % account.get('selfLink'))
+ print('Account Name = %s' % account.get('name'))
+ print('Created = %s' % account.get('created'))
+ print('Updated = %s' % account.get('updated'))
child_link = account.get('childLink')
- print 'Child link href = %s' % child_link.get('href')
- print 'Child link type = %s' % child_link.get('type')
- print
+ print('Child link href = %s' % child_link.get('href'))
+ print('Child link type = %s' % child_link.get('type'))
+ print()
if not accounts_response.get('items'):
- print 'No accounts found.\n'
+ print('No accounts found.\n')
def print_webproperties(webproperties_response):
@@ -168,32 +169,32 @@
Webproperties collection.
"""
- print '------ Web Properties Collection -------'
+ print('------ Web Properties Collection -------')
print_pagination_info(webproperties_response)
- print
+ print()
for webproperty in webproperties_response.get('items', []):
- print 'Kind = %s' % webproperty.get('kind')
- print 'Account ID = %s' % webproperty.get('accountId')
- print 'Web Property ID = %s' % webproperty.get('id')
- print ('Internal Web Property ID = %s' %
- webproperty.get('internalWebPropertyId'))
+ print('Kind = %s' % webproperty.get('kind'))
+ print('Account ID = %s' % webproperty.get('accountId'))
+ print('Web Property ID = %s' % webproperty.get('id'))
+ print(('Internal Web Property ID = %s' %
+ webproperty.get('internalWebPropertyId')))
- print 'Website URL = %s' % webproperty.get('websiteUrl')
- print 'Created = %s' % webproperty.get('created')
- print 'Updated = %s' % webproperty.get('updated')
+ print('Website URL = %s' % webproperty.get('websiteUrl'))
+ print('Created = %s' % webproperty.get('created'))
+ print('Updated = %s' % webproperty.get('updated'))
- print 'Self Link = %s' % webproperty.get('selfLink')
+ print('Self Link = %s' % webproperty.get('selfLink'))
parent_link = webproperty.get('parentLink')
- print 'Parent link href = %s' % parent_link.get('href')
- print 'Parent link type = %s' % parent_link.get('type')
+ print('Parent link href = %s' % parent_link.get('href'))
+ print('Parent link type = %s' % parent_link.get('type'))
child_link = webproperty.get('childLink')
- print 'Child link href = %s' % child_link.get('href')
- print 'Child link type = %s' % child_link.get('type')
- print
+ print('Child link href = %s' % child_link.get('href'))
+ print('Child link type = %s' % child_link.get('type'))
+ print()
if not webproperties_response.get('items'):
- print 'No webproperties found.\n'
+ print('No webproperties found.\n')
def print_profiles(profiles_response):
@@ -204,44 +205,44 @@
Profiles collection.
"""
- print '------ Profiles Collection -------'
+ print('------ Profiles Collection -------')
print_pagination_info(profiles_response)
- print
+ print()
for profile in profiles_response.get('items', []):
- print 'Kind = %s' % profile.get('kind')
- print 'Account ID = %s' % profile.get('accountId')
- print 'Web Property ID = %s' % profile.get('webPropertyId')
- print ('Internal Web Property ID = %s' %
- profile.get('internalWebPropertyId'))
- print 'Profile ID = %s' % profile.get('id')
- print 'Profile Name = %s' % profile.get('name')
+ print('Kind = %s' % profile.get('kind'))
+ print('Account ID = %s' % profile.get('accountId'))
+ print('Web Property ID = %s' % profile.get('webPropertyId'))
+ print(('Internal Web Property ID = %s' %
+ profile.get('internalWebPropertyId')))
+ print('Profile ID = %s' % profile.get('id'))
+ print('Profile Name = %s' % profile.get('name'))
- print 'Currency = %s' % profile.get('currency')
- print 'Timezone = %s' % profile.get('timezone')
- print 'Default Page = %s' % profile.get('defaultPage')
+ print('Currency = %s' % profile.get('currency'))
+ print('Timezone = %s' % profile.get('timezone'))
+ print('Default Page = %s' % profile.get('defaultPage'))
- print ('Exclude Query Parameters = %s' %
- profile.get('excludeQueryParameters'))
- print ('Site Search Category Parameters = %s' %
- profile.get('siteSearchCategoryParameters'))
- print ('Site Search Query Parameters = %s' %
- profile.get('siteSearchQueryParameters'))
+ print(('Exclude Query Parameters = %s' %
+ profile.get('excludeQueryParameters')))
+ print(('Site Search Category Parameters = %s' %
+ profile.get('siteSearchCategoryParameters')))
+ print(('Site Search Query Parameters = %s' %
+ profile.get('siteSearchQueryParameters')))
- print 'Created = %s' % profile.get('created')
- print 'Updated = %s' % profile.get('updated')
+ print('Created = %s' % profile.get('created'))
+ print('Updated = %s' % profile.get('updated'))
- print 'Self Link = %s' % profile.get('selfLink')
+ print('Self Link = %s' % profile.get('selfLink'))
parent_link = profile.get('parentLink')
- print 'Parent link href = %s' % parent_link.get('href')
- print 'Parent link type = %s' % parent_link.get('type')
+ print('Parent link href = %s' % parent_link.get('href'))
+ print('Parent link type = %s' % parent_link.get('type'))
child_link = profile.get('childLink')
- print 'Child link href = %s' % child_link.get('href')
- print 'Child link type = %s' % child_link.get('type')
- print
+ print('Child link href = %s' % child_link.get('href'))
+ print('Child link type = %s' % child_link.get('type'))
+ print()
if not profiles_response.get('items'):
- print 'No profiles found.\n'
+ print('No profiles found.\n')
def print_goals(goals_response):
@@ -252,32 +253,32 @@
collection
"""
- print '------ Goals Collection -------'
+ print('------ Goals Collection -------')
print_pagination_info(goals_response)
- print
+ print()
for goal in goals_response.get('items', []):
- print 'Goal ID = %s' % goal.get('id')
- print 'Kind = %s' % goal.get('kind')
- print 'Self Link = %s' % goal.get('selfLink')
+ print('Goal ID = %s' % goal.get('id'))
+ print('Kind = %s' % goal.get('kind'))
+ print('Self Link = %s' % goal.get('selfLink'))
- print 'Account ID = %s' % goal.get('accountId')
- print 'Web Property ID = %s' % goal.get('webPropertyId')
- print ('Internal Web Property ID = %s' %
- goal.get('internalWebPropertyId'))
- print 'Profile ID = %s' % goal.get('profileId')
+ print('Account ID = %s' % goal.get('accountId'))
+ print('Web Property ID = %s' % goal.get('webPropertyId'))
+ print(('Internal Web Property ID = %s' %
+ goal.get('internalWebPropertyId')))
+ print('Profile ID = %s' % goal.get('profileId'))
- print 'Goal Name = %s' % goal.get('name')
- print 'Goal Value = %s' % goal.get('value')
- print 'Goal Active = %s' % goal.get('active')
- print 'Goal Type = %s' % goal.get('type')
+ print('Goal Name = %s' % goal.get('name'))
+ print('Goal Value = %s' % goal.get('value'))
+ print('Goal Active = %s' % goal.get('active'))
+ print('Goal Type = %s' % goal.get('type'))
- print 'Created = %s' % goal.get('created')
- print 'Updated = %s' % goal.get('updated')
+ print('Created = %s' % goal.get('created'))
+ print('Updated = %s' % goal.get('updated'))
parent_link = goal.get('parentLink')
- print 'Parent link href = %s' % parent_link.get('href')
- print 'Parent link type = %s' % parent_link.get('type')
+ print('Parent link href = %s' % parent_link.get('href'))
+ print('Parent link type = %s' % parent_link.get('type'))
# Print the goal details depending on the type of goal.
if goal.get('urlDestinationDetails'):
@@ -295,10 +296,10 @@
elif goal.get('eventDetails'):
print_event_goal_details(goal.get('eventDetails'))
- print
+ print()
if not goals_response.get('items'):
- print 'No goals found.\n'
+ print('No goals found.\n')
def print_url_destination_goal_details(goal_details):
@@ -308,20 +309,20 @@
goal_details: The details portion of the goal response.
"""
- print '------ Url Destination Goal -------'
- print 'Goal URL = %s' % goal_details.get('url')
- print 'Case Sensitive = %s' % goal_details.get('caseSensitive')
- print 'Match Type = %s' % goal_details.get('matchType')
- print 'First Step Required = %s' % goal_details.get('firstStepRequired')
+ print('------ Url Destination Goal -------')
+ print('Goal URL = %s' % goal_details.get('url'))
+ print('Case Sensitive = %s' % goal_details.get('caseSensitive'))
+ print('Match Type = %s' % goal_details.get('matchType'))
+ print('First Step Required = %s' % goal_details.get('firstStepRequired'))
- print '------ Url Destination Goal Steps -------'
+ print('------ Url Destination Goal Steps -------')
for goal_step in goal_details.get('steps', []):
- print 'Step Number = %s' % goal_step.get('number')
- print 'Step Name = %s' % goal_step.get('name')
- print 'Step URL = %s' % goal_step.get('url')
+ print('Step Number = %s' % goal_step.get('number'))
+ print('Step Name = %s' % goal_step.get('name'))
+ print('Step URL = %s' % goal_step.get('url'))
if not goal_details.get('steps'):
- print 'No Steps Configured'
+ print('No Steps Configured')
def print_visit_time_on_site_goal_details(goal_details):
@@ -331,9 +332,9 @@
goal_details: The details portion of the goal response.
"""
- print '------ Visit Time On Site Goal -------'
- print 'Comparison Type = %s' % goal_details.get('comparisonType')
- print 'comparison Value = %s' % goal_details.get('comparisonValue')
+ print('------ Visit Time On Site Goal -------')
+ print('Comparison Type = %s' % goal_details.get('comparisonType'))
+ print('comparison Value = %s' % goal_details.get('comparisonValue'))
def print_visit_num_pages_goal_details(goal_details):
@@ -343,9 +344,9 @@
goal_details: The details portion of the goal response.
"""
- print '------ Visit Num Pages Goal -------'
- print 'Comparison Type = %s' % goal_details.get('comparisonType')
- print 'comparison Value = %s' % goal_details.get('comparisonValue')
+ print('------ Visit Num Pages Goal -------')
+ print('Comparison Type = %s' % goal_details.get('comparisonType'))
+ print('comparison Value = %s' % goal_details.get('comparisonValue'))
def print_event_goal_details(goal_details):
@@ -355,19 +356,19 @@
goal_details: The details portion of the goal response.
"""
- print '------ Event Goal -------'
- print 'Use Event Value = %s' % goal_details.get('useEventValue')
+ print('------ Event Goal -------')
+ print('Use Event Value = %s' % goal_details.get('useEventValue'))
for event_condition in goal_details.get('eventConditions', []):
event_type = event_condition.get('type')
- print 'Type = %s' % event_type
+ print('Type = %s' % event_type)
if event_type in ('CATEGORY', 'ACTION', 'LABEL'):
- print 'Match Type = %s' % event_condition.get('matchType')
- print 'Expression = %s' % event_condition.get('expression')
+ print('Match Type = %s' % event_condition.get('matchType'))
+ print('Expression = %s' % event_condition.get('expression'))
else: # VALUE type.
- print 'Comparison Type = %s' % event_condition.get('comparisonType')
- print 'Comparison Value = %s' % event_condition.get('comparisonValue')
+ print('Comparison Type = %s' % event_condition.get('comparisonType'))
+ print('Comparison Value = %s' % event_condition.get('comparisonValue'))
def print_segments(segments_response):
@@ -378,19 +379,19 @@
Segments collection.
"""
- print '------ Segments Collection -------'
+ print('------ Segments Collection -------')
print_pagination_info(segments_response)
- print
+ print()
for segment in segments_response.get('items', []):
- print 'Segment ID = %s' % segment.get('id')
- print 'Kind = %s' % segment.get('kind')
- print 'Self Link = %s' % segment.get('selfLink')
- print 'Name = %s' % segment.get('name')
- print 'Definition = %s' % segment.get('definition')
- print 'Created = %s' % segment.get('created')
- print 'Updated = %s' % segment.get('updated')
- print
+ print('Segment ID = %s' % segment.get('id'))
+ print('Kind = %s' % segment.get('kind'))
+ print('Self Link = %s' % segment.get('selfLink'))
+ print('Name = %s' % segment.get('name'))
+ print('Definition = %s' % segment.get('definition'))
+ print('Created = %s' % segment.get('created'))
+ print('Updated = %s' % segment.get('updated'))
+ print()
def print_pagination_info(management_response):
@@ -401,15 +402,15 @@
Management API.
"""
- print 'Items per page = %s' % management_response.get('itemsPerPage')
- print 'Total Results = %s' % management_response.get('totalResults')
- print 'Start Index = %s' % management_response.get('startIndex')
+ print('Items per page = %s' % management_response.get('itemsPerPage'))
+ print('Total Results = %s' % management_response.get('totalResults'))
+ print('Start Index = %s' % management_response.get('startIndex'))
# These only have values if other result pages exist.
if management_response.get('previousLink'):
- print 'Previous Link = %s' % management_response.get('previousLink')
+ print('Previous Link = %s' % management_response.get('previousLink'))
if management_response.get('nextLink'):
- print 'Next Link = %s' % management_response.get('nextLink')
+ print('Next Link = %s' % management_response.get('nextLink'))
if __name__ == '__main__':
diff --git a/samples/audit/audit.py b/samples/audit/audit.py
index b59938d..1595ddb 100644
--- a/samples/audit/audit.py
+++ b/samples/audit/audit.py
@@ -33,6 +33,7 @@
$ python audit.py --logging_level=DEBUG
"""
+from __future__ import print_function
__author__ = 'rahulpaul@google.com (Rahul Paul)'
@@ -55,7 +56,7 @@
activities = service.activities()
# Retrieve the first two activities
- print 'Retrieving the first 2 activities...'
+ print('Retrieving the first 2 activities...')
activity_list = activities.list(
applicationId='207535951991', customerId='C01rv1wm7', maxResults='2',
actorEmail='admin@enterprise-audit-clientlib.com').execute()
@@ -66,7 +67,7 @@
if match is not None:
next_token = match.group(0)
- print '\nRetrieving the next 2 activities...'
+ print('\nRetrieving the next 2 activities...')
activity_list = activities.list(
applicationId='207535951991', customerId='C01rv1wm7',
maxResults='2', actorEmail='admin@enterprise-audit-clientlib.com',
diff --git a/samples/blogger/blogger.py b/samples/blogger/blogger.py
index e5279c8..a0ce5cd 100644
--- a/samples/blogger/blogger.py
+++ b/samples/blogger/blogger.py
@@ -31,6 +31,7 @@
$ python blogger.py --logging_level=DEBUG
"""
+from __future__ import print_function
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
@@ -54,24 +55,24 @@
# Retrieve this user's profile information
thisuser = users.get(userId='self').execute(http=http)
- print 'This user\'s display name is: %s' % thisuser['displayName']
+ print('This user\'s display name is: %s' % thisuser['displayName'])
# Retrieve the list of Blogs this user has write privileges on
thisusersblogs = users.blogs().list(userId='self').execute()
for blog in thisusersblogs['items']:
- print 'The blog named \'%s\' is at: %s' % (blog['name'], blog['url'])
+ print('The blog named \'%s\' is at: %s' % (blog['name'], blog['url']))
posts = service.posts()
# List the posts for each blog this user has
for blog in thisusersblogs['items']:
- print 'The posts for %s:' % blog['name']
+ print('The posts for %s:' % blog['name'])
request = posts.list(blogId=blog['id'])
while request != None:
posts_doc = request.execute(http=http)
if 'items' in posts_doc and not (posts_doc['items'] is None):
for post in posts_doc['items']:
- print ' %s (%s)' % (post['title'], post['url'])
+ print(' %s (%s)' % (post['title'], post['url']))
request = posts.list_next(request, posts_doc)
except client.AccessTokenRefreshError:
diff --git a/samples/coordinate/coordinate.py b/samples/coordinate/coordinate.py
index 722e894..16775eb 100644
--- a/samples/coordinate/coordinate.py
+++ b/samples/coordinate/coordinate.py
@@ -35,6 +35,7 @@
$ python coordinate.py -t teamId --logging_level=DEBUG
"""
+from __future__ import print_function
__author__ = 'zachn@google.com (Zach Newell)'
@@ -91,7 +92,7 @@
pprint.pprint(update_result)
- except AccessTokenRefreshError, e:
+ except AccessTokenRefreshError as e:
print ('The credentials have been revoked or expired, please re-run'
'the application to re-authorize')
diff --git a/samples/django_sample/manage.py b/samples/django_sample/manage.py
index 0b932da..b2f07f1 100755
--- a/samples/django_sample/manage.py
+++ b/samples/django_sample/manage.py
@@ -1,7 +1,8 @@
#!/usr/bin/python
+from __future__ import absolute_import
from django.core.management import execute_manager
try:
- import settings # Assumed to be in the same directory.
+ from . import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("""Error: Can't find the file 'settings.py' in the
diff --git a/samples/groupssettings/groupsettings.py b/samples/groupssettings/groupsettings.py
index 018a2a2..c403757 100644
--- a/samples/groupssettings/groupsettings.py
+++ b/samples/groupssettings/groupsettings.py
@@ -24,6 +24,7 @@
$ python groupsettings.py --help
"""
+from __future__ import print_function
__author__ = 'Shraddha Gupta <shraddhag@google.com>'
@@ -75,12 +76,12 @@
# Retrieve the group properties
g = group.get(groupUniqueId=groupId).execute()
- print '\nGroup properties for group %s\n' % g['name']
+ print('\nGroup properties for group %s\n' % g['name'])
pprint.pprint(g)
# If dictionary is empty, return without updating the properties.
if not settings.keys():
- print '\nGive access parameters to update group access permissions\n'
+ print('\nGive access parameters to update group access permissions\n')
return
body = {}
@@ -94,7 +95,7 @@
# Update the properties of group
g1 = group.update(groupUniqueId=groupId, body=body).execute()
- print '\nUpdated Access Permissions to the group\n'
+ print('\nUpdated Access Permissions to the group\n')
pprint.pprint(g1)
@@ -126,7 +127,7 @@
(options, args) = parser.parse_args()
if options.groupId is None:
- print 'Give the groupId for the group'
+ print('Give the groupId for the group')
parser.print_help()
return
@@ -134,7 +135,7 @@
if (options.whoCanInvite or options.whoCanJoin or options.whoCanPostMessage
or options.whoCanPostMessage or options.whoCanViewMembership) is None:
- print 'No access parameters given in input to update access permissions'
+ print('No access parameters given in input to update access permissions')
parser.print_help()
else:
settings = {'whoCanInvite': options.whoCanInvite,
@@ -152,7 +153,7 @@
credentials = storage.get()
if credentials is None or credentials.invalid:
- print 'invalid credentials'
+ print('invalid credentials')
# Save the credentials in storage to be used in subsequent runs.
credentials = run(FLOW, storage)
diff --git a/samples/plus/plus.py b/samples/plus/plus.py
index ce3e712..cc7d146 100755
--- a/samples/plus/plus.py
+++ b/samples/plus/plus.py
@@ -18,6 +18,7 @@
"""Simple command-line sample for the Google+ API.
Command-line application that retrieves the list of the user's posts."""
+from __future__ import print_function
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
@@ -36,9 +37,9 @@
try:
person = service.people().get(userId='me').execute()
- print 'Got your ID: %s' % person['displayName']
- print
- print '%-040s -> %s' % ('[Activitity ID]', '[Content]')
+ print('Got your ID: %s' % person['displayName'])
+ print()
+ print('%-040s -> %s' % ('[Activitity ID]', '[Content]'))
# Don't execute the request until we reach the paging loop below.
request = service.activities().list(
@@ -48,7 +49,7 @@
while request is not None:
activities_doc = request.execute()
for item in activities_doc.get('items', []):
- print '%-040s -> %s' % (item['id'], item['object']['content'][:30])
+ print('%-040s -> %s' % (item['id'], item['object']['content'][:30]))
request = service.activities().list_next(request, activities_doc)
diff --git a/samples/prediction/prediction.py b/samples/prediction/prediction.py
index a4bff3f..ae93721 100644
--- a/samples/prediction/prediction.py
+++ b/samples/prediction/prediction.py
@@ -33,6 +33,7 @@
$ python prediction.py --logging_level=DEBUG
"""
+from __future__ import print_function
__author__ = ('jcgregorio@google.com (Joe Gregorio), '
'marccohen@google.com (Marc Cohen)')
@@ -66,9 +67,9 @@
'''Format and print header block sized to length of line'''
header_str = '='
header_line = header_str * len(line)
- print '\n' + header_line
- print line
- print header_line
+ print('\n' + header_line)
+ print(line)
+ print(header_line)
def main(argv):
@@ -89,14 +90,14 @@
# List models.
print_header('Fetching list of first ten models')
result = papi.list(maxResults=10, project=flags.project_id).execute()
- print 'List results:'
+ print('List results:')
pprint.pprint(result)
# Start training request on a data set.
print_header('Submitting model training request')
body = {'id': flags.model_id, 'storageDataLocation': flags.object_name}
start = papi.insert(body=body, project=flags.project_id).execute()
- print 'Training results:'
+ print('Training results:')
pprint.pprint(start)
# Wait for the training to complete.
@@ -104,7 +105,7 @@
while True:
status = papi.get(id=flags.model_id, project=flags.project_id).execute()
state = status['trainingStatus']
- print 'Training state: ' + state
+ print('Training state: ' + state)
if state == 'DONE':
break
elif state == 'RUNNING':
@@ -114,14 +115,14 @@
raise Exception('Training Error: ' + state)
# Job has completed.
- print 'Training completed:'
+ print('Training completed:')
pprint.pprint(status)
break
# Describe model.
print_header('Fetching model description')
result = papi.analyze(id=flags.model_id, project=flags.project_id).execute()
- print 'Analyze results:'
+ print('Analyze results:')
pprint.pprint(result)
# Make some predictions using the newly trained model.
@@ -130,13 +131,13 @@
body = {'input': {'csvInstance': [sample_text]}}
result = papi.predict(
body=body, id=flags.model_id, project=flags.project_id).execute()
- print 'Prediction results for "%s"...' % sample_text
+ print('Prediction results for "%s"...' % sample_text)
pprint.pprint(result)
# Delete model.
print_header('Deleting model')
result = papi.delete(id=flags.model_id, project=flags.project_id).execute()
- print 'Model deleted.'
+ print('Model deleted.')
except client.AccessTokenRefreshError:
print ('The credentials have been revoked or expired, please re-run '
diff --git a/samples/searchforshopping/histograms.py b/samples/searchforshopping/histograms.py
index da75b3b..1f9f349 100644
--- a/samples/searchforshopping/histograms.py
+++ b/samples/searchforshopping/histograms.py
@@ -4,6 +4,7 @@
# Copyright 2014 Google Inc. All Rights Reserved.
"""Query with ranked results against the shopping search API"""
+from __future__ import print_function
from googleapiclient.discovery import build
@@ -37,7 +38,7 @@
# Pick the first and only facet for this query
facet = response['facets'][0]
- print '\n\tHistogram for "%s":\n' % facet['property']
+ print('\n\tHistogram for "%s":\n' % facet['property'])
labels = []
values = []
@@ -49,9 +50,9 @@
weighting = 50.0 / max(values)
for label, value in zip(labels, values):
- print label, '#' * int(weighting * value), '(%s)' % value
+ print(label, '#' * int(weighting * value), '(%s)' % value)
- print
+ print()
if __name__ == '__main__':
diff --git a/samples/searchforshopping/main.py b/samples/searchforshopping/main.py
index c1add4c..0ff2051 100644
--- a/samples/searchforshopping/main.py
+++ b/samples/searchforshopping/main.py
@@ -8,6 +8,7 @@
Command-line application that does a search for products.
'''
+from __future__ import print_function
__author__ = 'aherrman@google.com (Andy Herrman)'
@@ -22,7 +23,7 @@
developerKey='AIzaSyDRRpR3GS1F1_jKNNM9HCNd2wJQyPG3oN0')
# Search over all public offers:
- print 'Searching all public offers.'
+ print('Searching all public offers.')
res = p.products().list(
country='US',
source='public',
@@ -31,8 +32,8 @@
print_items(res['items'])
# Search over a specific merchant's offers:
- print
- print 'Searching Google Store.'
+ print()
+ print('Searching Google Store.')
res = p.products().list(
country='US',
source='public',
@@ -45,8 +46,8 @@
googleId = res['items'][0]['product']['googleId']
# Get data for the single public offer:
- print
- print 'Getting data for offer %s' % googleId
+ print()
+ print('Getting data for offer %s' % googleId)
res = p.products().get(
source='public',
accountId='5968952',
@@ -59,9 +60,9 @@
def print_item(item):
"""Displays a single item: title, merchant, link."""
product = item['product']
- print '- %s [%s] (%s)' % (product['title'],
+ print('- %s [%s] (%s)' % (product['title'],
product['author']['name'],
- product['link'])
+ product['link']))
def print_items(items):
diff --git a/samples/translate/main.py b/samples/translate/main.py
index ee67d40..21d01ee 100644
--- a/samples/translate/main.py
+++ b/samples/translate/main.py
@@ -19,6 +19,7 @@
Command-line application that translates some text.
"""
+from __future__ import print_function
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
@@ -32,11 +33,11 @@
# to get an API key for your own application.
service = build('translate', 'v2',
developerKey='AIzaSyDRRpR3GS1F1_jKNNM9HCNd2wJQyPG3oN0')
- print service.translations().list(
+ print(service.translations().list(
source='en',
target='fr',
q=['flower', 'car']
- ).execute()
+ ).execute())
if __name__ == '__main__':
main()
diff --git a/samples/urlshortener/urlshortener.py b/samples/urlshortener/urlshortener.py
index 9c75260..9d4a6db 100644
--- a/samples/urlshortener/urlshortener.py
+++ b/samples/urlshortener/urlshortener.py
@@ -32,6 +32,7 @@
$ python urlshortener.py --logging_level=DEBUG
"""
+from __future__ import print_function
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
diff --git a/tests/test_discovery.py b/tests/test_discovery.py
index de2e6b2..c16f470 100644
--- a/tests/test_discovery.py
+++ b/tests/test_discovery.py
@@ -142,7 +142,7 @@
parameters = self._base_fix_up_parameters_test(self.zoo_get_method_desc,
'GET', self.zoo_root_desc)
# Since http_method is 'GET'
- self.assertFalse(parameters.has_key('body'))
+ self.assertFalse('body' in parameters)
def test_fix_up_parameters_insert(self):
parameters = self._base_fix_up_parameters_test(self.zoo_insert_method_desc,
@@ -165,15 +165,15 @@
parameters = _fix_up_parameters(invalid_method_desc, dummy_root_desc,
no_payload_http_method)
- self.assertFalse(parameters.has_key('body'))
+ self.assertFalse('body' in parameters)
parameters = _fix_up_parameters(valid_method_desc, dummy_root_desc,
no_payload_http_method)
- self.assertFalse(parameters.has_key('body'))
+ self.assertFalse('body' in parameters)
parameters = _fix_up_parameters(invalid_method_desc, dummy_root_desc,
with_payload_http_method)
- self.assertFalse(parameters.has_key('body'))
+ self.assertFalse('body' in parameters)
parameters = _fix_up_parameters(valid_method_desc, dummy_root_desc,
with_payload_http_method)
@@ -253,7 +253,7 @@
http_method = 'GET'
method_id = 'bigquery.query'
accept = []
- max_size = 0L
+ max_size = 0
media_path_url = None
self.assertEqual(result, (path_url, http_method, method_id, accept,
max_size, media_path_url))
@@ -265,7 +265,7 @@
http_method = 'POST'
method_id = 'zoo.animals.insert'
accept = ['image/png']
- max_size = 1024L
+ max_size = 1024
media_path_url = 'https://www.googleapis.com/upload/zoo/v1/animals'
self.assertEqual(result, (path_url, http_method, method_id, accept,
max_size, media_path_url))
@@ -388,7 +388,7 @@
zoo = build('zoo', 'v1', http=http, developerKey='foo',
discoveryServiceUrl='http://example.com')
self.fail('Should have raised an exception.')
- except HttpError, e:
+ except HttpError as e:
self.assertEqual(e.uri, 'http://example.com?userIp=10.0.0.1')
def test_userip_missing_is_not_added_to_discovery_uri(self):
@@ -401,7 +401,7 @@
zoo = build('zoo', 'v1', http=http, developerKey=None,
discoveryServiceUrl='http://example.com')
self.fail('Should have raised an exception.')
- except HttpError, e:
+ except HttpError as e:
self.assertEqual(e.uri, 'http://example.com')
@@ -415,28 +415,28 @@
try:
plus.activities().list()
self.fail()
- except TypeError, e:
+ except TypeError as e:
self.assertTrue('Missing' in str(e))
# Missing required parameters even if supplied as None.
try:
plus.activities().list(collection=None, userId=None)
self.fail()
- except TypeError, e:
+ except TypeError as e:
self.assertTrue('Missing' in str(e))
# Parameter doesn't match regex
try:
plus.activities().list(collection='not_a_collection_name', userId='me')
self.fail()
- except TypeError, e:
+ except TypeError as e:
self.assertTrue('not an allowed value' in str(e))
# Unexpected parameter
try:
plus.activities().list(flubber=12)
self.fail()
- except TypeError, e:
+ except TypeError as e:
self.assertTrue('unexpected' in str(e))
def _check_query_types(self, request):
@@ -805,7 +805,7 @@
try:
request.execute(http=http)
self.fail('Should have raised ResumableUploadError.')
- except ResumableUploadError, e:
+ except ResumableUploadError as e:
self.assertEqual(400, e.resp.status)
def test_resumable_media_fail_unknown_response_code_subsequent_request(self):
@@ -905,7 +905,7 @@
try:
body = request.execute(http=http)
- except HttpError, e:
+ except HttpError as e:
self.assertEqual('01234', e.content)
except ImportError:
@@ -1060,7 +1060,7 @@
try:
# Should resume the upload by first querying the status of the upload.
request.next_chunk(http=http)
- except HttpError, e:
+ except HttpError as e:
expected = {
'Content-Range': 'bytes */14',
'content-length': '0'
diff --git a/tests/test_http.py b/tests/test_http.py
index e8a3580..8989409 100644
--- a/tests/test_http.py
+++ b/tests/test_http.py
@@ -796,7 +796,7 @@
try:
batch.execute(http=http)
self.fail('Should raise exception')
- except BatchError, e:
+ except BatchError as e:
boundary, _ = e.content.split(None, 1)
self.assertEqual('--', boundary[:2])
parts = e.content.split(boundary)
diff --git a/tests/test_json_model.py b/tests/test_json_model.py
index c8a985b..af9841a 100644
--- a/tests/test_json_model.py
+++ b/tests/test_json_model.py
@@ -152,7 +152,7 @@
try:
content = model.response(resp, content)
self.fail('Should have thrown an exception')
- except HttpError, e:
+ except HttpError as e:
self.assertTrue('not authorized' in str(e))
resp['content-type'] = 'application/json'
@@ -160,7 +160,7 @@
try:
content = model.response(resp, content)
self.fail('Should have thrown an exception')
- except HttpError, e:
+ except HttpError as e:
self.assertTrue('not authorized' in str(e))
def test_good_response(self):
diff --git a/tests/test_mocks.py b/tests/test_mocks.py
index 4d9fd80..e3c550f 100644
--- a/tests/test_mocks.py
+++ b/tests/test_mocks.py
@@ -140,7 +140,7 @@
try:
activity = plus.activities().list(collection='public', userId='me').execute()
self.fail('An exception should have been thrown')
- except HttpError, e:
+ except HttpError as e:
self.assertEqual('{}', e.content)
self.assertEqual(500, e.resp.status)
self.assertEqual('Server Error', e.resp.reason)